<?php

namespace Ekyna\Bundle\SitemapBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Class SitemapController
 * @package Ekyna\Bundle\SitemapBundle\Controller
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
class SitemapController extends Controller
{
    /**
     * Renders the sitemaps index.
     *
     * @param Request $request
     * @return Response
     */
    public function indexAction(Request $request)
    {
        $registry = $this->get('ekyna_sitemap.provider_registry');
        $sitemaps = [];

        $lastUpdateDate = null;
        foreach($registry->getSitemaps() as $sitemap) {
            $providers = $registry->getProvidersBySitemap($sitemap);
            $sitemapLastUpdateDate = null;
            /** @var \Ekyna\Bundle\SitemapBundle\Provider\ProviderInterface $provider */
            foreach ($providers as $provider) {
                if (null === $sitemapLastUpdateDate || $sitemapLastUpdateDate < $provider->getLastUpdateDate()) {
                    $sitemapLastUpdateDate = $provider->getLastUpdateDate();
                }
            }
            $sitemaps[$sitemap] = $sitemapLastUpdateDate;
            if (null === $lastUpdateDate || $lastUpdateDate < $sitemapLastUpdateDate) {
                $lastUpdateDate = $sitemapLastUpdateDate;
            }
        }

        $response = new Response();
        $response->setLastModified($lastUpdateDate);
        $response->setPublic();
        if ($response->isNotModified($request)) {
            return $response;
        }
        $response->setMaxAge($this->container->getParameter('ekyna_sitemap.index_ttl'));
        $response->headers->add(['Content-Type' => 'application/xml; charset=UTF-8']);

        return $response->setContent($this->renderView('EkynaSitemapBundle:Sitemap:index.xml.twig', [
            'sitemaps' => $sitemaps,
        ]));
    }

    /**
     * Renders the sitemap.
     *
     * @param Request $request
     * @return Response
     */
    public function sitemapAction(Request $request)
    {
        $sitemap = $request->attributes->get('sitemap', null);

        $registry = $this->get('ekyna_sitemap.provider_registry');
        $providers = $registry->getProvidersBySitemap($sitemap);

        if (0 === count($providers)) {
            throw new NotFoundHttpException('Sitemap not found.');
        }

        $lastUpdateDate = null;
        /** @var \Ekyna\Bundle\SitemapBundle\Provider\ProviderInterface $provider */
        foreach($providers as $provider) {
            if (null === $lastUpdateDate || $lastUpdateDate < $provider->getLastUpdateDate()) {
                $lastUpdateDate = $provider->getLastUpdateDate();
            }
        }

        $response = new Response();
        $response->setLastModified($lastUpdateDate);
        $response->setPublic();
        if ($response->isNotModified($request)) {
            return $response;
        }
        $response->setMaxAge($this->container->getParameter('ekyna_sitemap.sitemap_ttl'));
        $response->headers->add(['Content-Type' => 'application/xml; charset=UTF-8']);

        return $response->setContent($this->renderView('EkynaSitemapBundle:Sitemap:sitemap.xml.twig', [
            'providers' => $providers,
        ]));
    }
}


<?php
namespace Interpro\QuickStorage\Laravel;

use Interpro\QuickStorage\Concept\QSource as QSourceInterface;

class ImageRepository implements \Interpro\QuickStorage\Concept\ImageRepository
{
    private $block_images;
    private $group_images;
    private $qSource;

    public function __construct(QSourceInterface $qSource)
    {
        $this->qSource = $qSource;
        $this->block_images = [];
        $this->group_images = [];
    }

    private function createIfNotExistBlock($block_name)
    {
        if(!array_key_exists($block_name, $this->block_images))
        {
            $images_array = $this->qSource->imageQueryForBlock($block_name);

            $this->block_images[$block_name] = [];

            $block_arr = & $this->block_images[$block_name];

            foreach($images_array as $image)
            {
                $block_arr[$image['name']] = $image;
            }
        }
    }

    private function createIfNotExistGroup($block_name, $group_name)
    {
        if(!array_key_exists($group_name, $this->group_images))
        {
            $images_array = $this->qSource->imageQueryForGroup($block_name, $group_name);

            $this->group_images[$group_name] = [];

            $group_arr = & $this->group_images[$group_name];

            foreach($images_array as $image)
            {
                if(!array_key_exists($image['name'], $group_arr))
                {
                    $group_arr[$image['name']] = [];
                }

                $group_arr[$image['name']]['id_'.$image['group_id']] = $image;
            }
        }
    }

    /**
     * @param string $block_name
     * @param string $image_name
     *
     * @return array
     */
    public function getBlockImage($block_name, $image_name)
    {
        $this->createIfNotExistBlock($block_name);

        return $this->block_images[$block_name][$image_name];
    }

    /**
     * @param string $block_name
     * @param string $group_name
     * @param string $group_id
     * @param string $image_name
     *
     * @return array
     */
    public function getGroupImage($block_name, $group_name, $group_id, $image_name)
    {
        $this->createIfNotExistGroup($block_name, $group_name);

        return $this->group_images[$group_name][$image_name]['id_'.$group_id];
    }

    /**
     * @param string $block_name
     * @param string $group_name
     * @param string $image_name
     *
     * @return array
     */
    public function getAllGroupImages($block_name, $group_name, $image_name)
    {
        $this->createIfNotExistGroup($block_name, $group_name);

        return $this->group_images[$group_name][$image_name];
    }

}


<?php
declare(strict_types = 1);

namespace Innmind\Rest\Client\Definition\Type;

use Innmind\Rest\Client\{
    Definition\Types,
    Definition\Type,
    Exception\DomainException,
    Exception\NormalizationException,
    Exception\DenormalizationException,
};
use Innmind\Immutable\Str;

final class DateType implements Type
{
    const PATTERN = '~date<(?<format>.+)>~';

    private $format;

    public function __construct(string $format)
    {
        if (Str::of($format)->empty()) {
            throw new DomainException;
        }

        $this->format = $format;
    }

    public static function fromString(string $type, Types $build): Type
    {
        $type = new Str($type);

        if (!$type->matches(self::PATTERN)) {
            throw new DomainException;
        }

        return new self(
            (string) $type
                ->capture(self::PATTERN)
                ->get('format')
        );
    }

    /**
     * {@inheritdoc}
     */
    public function normalize($data)
    {
        if (\is_string($data)) {
            try {
                $data = new \DateTimeImmutable($data);
            } catch (\Exception $e) {
                throw new NormalizationException('The value must be a date');
            }
        }

        if (!$data instanceof \DateTimeInterface) {
            throw new NormalizationException(
                'The value must be an instance of \DateTimeInterface'
            );
        }

        return $data->format($this->format);
    }

    /**
     * {@inheritdoc}
     */
    public function denormalize($data)
    {
        if (!\is_string($data)) {
            throw new DenormalizationException('The value must be a string');
        }

        try {
            $date = \DateTimeImmutable::createFromFormat(
                $this->format,
                $data
            );

            if (!$date instanceof \DateTimeImmutable) {
                throw new \Exception;
            }

            return $date;
        } catch (\Throwable $e) {
            throw new DenormalizationException('The value must be a valid date');
        }
    }

    public function __toString(): string
    {
        return 'date<'.$this->format.'>';
    }
}


<?php

namespace Thruster\Component\EventEmitter;

/**
 * Trait EventEmitterTrait
 *
 * @package Thruster\Component\EventEmitter
 * @author  Aurimas Niekis <aurimas@niekis.lt>
 */
trait EventEmitterTrait
{
    /**
     * @var callable[]
     */
    protected $listeners = [];

    /**
     * @param string   $event
     * @param callable $listener
     *
     * @return $this
     */
    public function on(string $event, callable $listener) : self
    {
        $this->listeners[$event][] = $listener;

        return $this;
    }

    /**
     * @param string   $event
     * @param callable $listener
     *
     * @return $this
     */
    public function once(string $event, callable $listener) : self
    {
        $onceListener = function () use (&$onceListener, $event, $listener) {
            $this->removeListener($event, $onceListener);

            call_user_func_array($listener, func_get_args());
        };

        $this->on($event, $onceListener);

        return $this;
    }

    /**
     * @param string   $event
     * @param callable $listener
     *
     * @return $this
     */
    public function removeListener(string $event, callable $listener) : self
    {
        if (array_key_exists($event, $this->listeners)) {
            $index = array_search($listener, $this->listeners[$event], true);

            if (false !== $index) {
                unset($this->listeners[$event][$index]);
            }
        }

        return $this;
    }

    /**
     * @param string $event
     *
     * @return $this
     */
    public function removeListeners(string $event = null) : self
    {
        if (null !== $event) {
            unset($this->listeners[$event]);
        } else {
            $this->listeners = [];
        }

        return $this;
    }

    /**
     * @param string $event
     *
     * @return array|callable[]
     */
    public function getListeners(string $event) : array
    {
        return isset($this->listeners[$event]) ? $this->listeners[$event] : [];
    }

    /**
     * @param string $event
     * @param array  $arguments
     *
     * @return $this
     */
    public function emit(string $event, array $arguments = []) : self
    {
        foreach ($this->getListeners($event) as $listener) {
            call_user_func_array($listener, $arguments);
        }

        return $this;
    }
}


<?php

/**
 * Openbizx Framework
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin.util
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: xmltoarray.php 2553 2010-11-21 08:36:48Z mr_a_ton $
 */

namespace Openbizx\Helpers;

// Based on code found online at:
// http://php.net/manual/en/function.xml-parse-into-struct.php
//
// Author: Eric Pollmann
// Released into public domain September 2003
//http://eric.pollmann.net/work/public_domain/
/*
  //$parser = new XMLParser('./BOEvent.xml', 'file', 1);
  //$parser = new XMLParser('./FMSponsor_chart.xml', 'file', 1);
  //$parser = new XMLParser('./EventView.xml', 'file', 1);
  $parser = new XMLParser('./FMEvent.xml', 'file', 1);
  $tree = $parser->getTree();
  echo "<pre>";
  print_r($tree);
  echo "</pre>";
 */
class XMLParser
{
    var $data;  // Input XML data buffer
    var $vals;  // Struct created by xml_parse_into_struct
    var $collapse_dups; // If there is only one tag of a given name,
    //   shall we store as scalar or array?
    var $index_numeric; // Index tags by numeric position, not name.

    //   useful for ordered XML like CallXML.
    // Read in XML on object creation.
    // We can take raw XML data, a stream, a filename, or a url.
    function __construct($data_source, $data_source_type = 'raw', $collapse_dups = 0, $index_numeric = 0)
    {
        $this->collapse_dups = $collapse_dups;
        $this->index_numeric = $index_numeric;

        $this->data = '';
        if ($data_source_type == 'raw') {
            $this->data = $data_source;
        } elseif ($data_source_type == 'stream') {
            while (!feof($data_source)) {
                $this->data .= fread($data_source, 1000);
            }
        // try filename, then if that fails...
        } elseif (file_exists($data_source)) {
            $this->data = implode('', file($data_source));
        } else { // try url
            $fp = fopen($data_source, 'r');
            while (!feof($fp)) {
                $this->data .= fread($fp, 1000);
            }
            fclose($fp);
        }

        //add support for load encoded files
        if (function_exists("ioncube_read_file")) {
            $data = ioncube_read_file($data_source);
            if (!is_int($data)) {
                $this->data = $data;
            }
        } elseif (substr($this->data, 0, 7) == '!odMbo!') {
            header("Location: " . OPENBIZ_APP_INDEX_URL . '/common/loader_not_installed');
            exit;
        }
    }

    // Parse the XML file into a verbose, flat array struct.
    // Then, coerce that into a simple nested array.
    function &getTree()
    {
        // load xml and check if it turns a valid object. TODO: it will throw error.
        /* $xml = simplexml_load_file($this->data);
          if (!$xml) {
          echo 'invalid xml file '.$this->data; exit;
          } */
        //$parser = xml_parser_create('ISO-8859-1');
        $parser = xml_parser_create('');
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
        xml_parse_into_struct($parser, $this->data, $vals, $index);
        xml_parser_free($parser);

        $i = -1;
        return $this->getchildren($vals, $i);
    }

    // internal function: build a node of the tree
    function buildtag($thisvals, $vals, &$i, $type)
    {

        if (isset($thisvals['attributes'])) {
            $tag['ATTRIBUTES'] = $thisvals['attributes'];
        }

        // complete tag, just return it for storage in array
        if ($type === 'complete') {
            $tag['VALUE'] = $thisvals['value'];
        } else {
            // open tag, recurse
            $tag = array_merge((array) $tag, (array) $this->getchildren($vals, $i));
        }
        return $tag;
    }

    // internal function: build an nested array representing children
    function getchildren($vals, &$i)
    {
        $children = array();     // Contains node data
        // Node has CDATA before it's children
        if ($i > -1 && isset($vals[$i]['value'])) {
            $children['VALUE'] = $vals[$i]['value'];
        }

        // Loop through children, until hit close tag or run out of tags
        while (++$i < count($vals)) {

            $type = $vals[$i]['type'];

            // 'cdata':	Node has CDATA after one of it's children
            // 		(Add to cdata found before in this case)
            if ($type === 'cdata')
                $children['VALUE'] .= $vals[$i]['value'];

            // 'complete':	At end of current branch
            // 'open':	Node has children, recurse
            elseif ($type === 'complete' || $type === 'open') {
                $tag = $this->buildtag($vals[$i], $vals, $i, $type);
                if ($this->index_numeric) {
                    $tag['TAG'] = $vals[$i]['tag'];
                    $children[] = $tag;
                } else {
                    $children[$vals[$i]['tag']][] = $tag;
                }
            } elseif ($type === 'close') {
                // 'close:	End of node, return collected data
                //		Do not increment $i or nodes disappear!
                break;
            }
        }
        if ($this->collapse_dups) {
            foreach ($children as $key => $value) {
                if (is_array($value) && (count($value) == 1)) {
                    $children[$key] = $value[0];
                }
            }
        }
        return $children;
    }

}


<?php
/**
 * This file is part of CMSGears Framework. Please view License file distributed
 * with the source code for license details.
 *
 * @link https://www.cmsgears.org/
 * @copyright Copyright (c) 2015 VulpineCode Technologies Pvt. Ltd.
 */

namespace cmsgears\widgets\form;

// Yii Imports
use yii\captcha\Captcha;

// CMG Imports
use cmsgears\core\common\utilities\FormUtil;

/**
 * The BasicFormWidget used to submit form in traditional way must be wrapped by [[yii\widgets\ActiveForm]].
 *
 * @since 1.0.0
 */
class BasicFormWidget extends BaseForm {

	// Variables ---------------------------------------------------

	// Globals -------------------------------

	// Constants --------------

	// Public -----------------

	// Protected --------------

	// Variables -----------------------------

	// Public -----------------

	/**
	 * Active Form to be used to render form.
	 *
	 * @var \yii\widgets\ActiveForm
	 */
	public $activeForm;

	/**
	 * Flag to check whether captcha has to be wrapped.
	 *
	 * @var boolean
	 */
	public $wrapCaptcha	= false;

	/**
	 * Flag to check whether form actions has to be wrapped.
	 *
	 * @var boolean
	 */
	public $wrapActions	= false;

	/**
	 * Flag to check whether form labels and fields need split.
	 *
	 * @var boolean
	 */
	public $split4060 = true;

	/**
	 * The default action to listen for captcha request.
	 *
	 * @var string
	 */
	public $captchaAction = '/forms/form/captcha';

	// Protected --------------

	// Private ----------------

	// Traits ------------------------------------------------------

	// Constructor and Initialisation ------------------------------

	// Instance methods --------------------------------------------

	// Yii interfaces ------------------------

	// Yii parent classes --------------------

	// yii\base\Widget --------

	// CMG interfaces ------------------------

	// CMG parent classes --------------------

	// BasicFormWidget -----------------------

    public function renderWidget( $config = [] ) {

		$fieldsHtml		= null;
		$captchaHtml	= null;

		if( isset( $this->model ) && $this->model->isActive() ) {

			$form		= $this->form;
			$activeForm	= $this->activeForm;
			$fieldsHtml	= FormUtil::getFieldsHtml( $activeForm, $form, [ 'label' => $this->labels ] );

			if( $this->model->captcha ) {

				if( $this->labels ) {

					$captchaHtml = $activeForm->field( $form, 'captcha' )->widget( Captcha::class, [ 'captchaAction' => $this->captchaAction, 'options' => [ 'placeholder' => 'Captcha*', 'class' =>'captcha' ] ] );
				}
				else {

					$captchaHtml = $activeForm->field( $form, 'captcha' )->label( false )->widget( Captcha::class, [ 'captchaAction' => $this->captchaAction, 'options' => [ 'placeholder' => 'Captcha*', 'class' =>'captcha' ] ] );
				}
			}
		}

		$widgetHtml = $this->render( $this->template, [ 'widget' => $this, 'fieldsHtml' => $fieldsHtml, 'captchaHtml' => $captchaHtml ] );

		if( $this->wrap ) {

			return Html::tag( $this->wrapper, $widgetHtml, $this->options );
		}

		return $widgetHtml;
    }

}


<?php
/**
 * OAuth 2.0 Resource Server
 *
 */

namespace OAuth2\Server;

use OAuth2\Server\Entity\AccessTokenEntity;
use OAuth2\Server\Exception\AccessDeniedException;
use OAuth2\Server\Exception\InvalidRequestException;
use OAuth2\Server\Storage\AccessTokenInterface;
use OAuth2\Server\Storage\ClientInterface;
use OAuth2\Server\Storage\ScopeInterface;
use OAuth2\Server\Storage\SessionInterface;
use OAuth2\Server\TokenType\Bearer;
use OAuth2\Server\Request\HandlerInterface;

/**
 * OAuth 2.0 Resource Server
 */
class ResourceServer extends AbstractServer
{
    /**
     * The access token
     *
     * @var \OAuth2\Server\Entity\AccessTokenEntity
     */
    protected $accessToken;

    /**
     * The query string key which is used by clients to present the access token (default: access_token)
     *
     * @var string
     */
    protected $tokenKey = 'access_token';

	/**
	 * The Header key which is used by clients to present the access token (default: Authorization)
	 *
	 * @var string
	 */
	protected $authHeader = 'Authorization';

    /**
     * Initialise the resource server
     *
	 * @param \OAuth2\Server\Request\HandlerInterface     $requestHandler
     * @param \OAuth2\Server\Storage\SessionInterface     $sessionStorage
     * @param \OAuth2\Server\Storage\AccessTokenInterface $accessTokenStorage
     * @param \OAuth2\Server\Storage\ClientInterface      $clientStorage
     * @param \OAuth2\Server\Storage\ScopeInterface       $scopeStorage
     *
     * @return self
     */
    public function __construct(
		HandlerInterface $requestHandler,
        SessionInterface $sessionStorage,
        AccessTokenInterface $accessTokenStorage,
        ClientInterface $clientStorage,
        ScopeInterface $scopeStorage
    ) {
        $this->setSessionStorage($sessionStorage);
        $this->setAccessTokenStorage($accessTokenStorage);
        $this->setClientStorage($clientStorage);
        $this->setScopeStorage($scopeStorage);

        parent::__construct($requestHandler);

        return $this;
    }

    /**
     * Sets the query string key for the access token.
     *
     * @param string $key The new query string key
     *
     * @return self
     */
    public function setIdKey($key)
    {
        $this->tokenKey = $key;

        return $this;
    }
	/**
	 * Sets the Auth Header key for which access token will be passed.
	 *
	 * @param string $authHeader The new authHeader string key
	 *
	 * @return self
	 */
	public function setAuthHeader($authHeader)
	{
		$this->authHeader = $authHeader;

		return $this;
	}

    /**
     * Gets the access token
     *
     * @return \OAuth2\Server\Entity\AccessTokenEntity
     */
    public function getAccessToken()
    {
        return $this->accessToken;
    }

    /**
     * Checks if the access token is valid or not
     *
     * @param bool                                                $headerOnly Limit Access Token to Authorization header
     * @param \OAuth2\Server\Entity\AccessTokenEntity|null $accessToken Access Token
     *
     * @throws \OAuth2\Server\Exception\AccessDeniedException
     * @throws \OAuth2\Server\Exception\InvalidRequestException
     *
     * @return bool
     */
    public function isValidRequest($headerOnly = true, $accessToken = null)
    {
        $accessTokenString = ($accessToken !== null)
                                ? $accessToken
                                : $this->determineAccessToken($headerOnly);

        // Set the access token
        $this->accessToken = $this->getAccessTokenStorage()->get($accessTokenString);

        // Ensure the access token exists
        if (!$this->accessToken instanceof AccessTokenEntity) {
            throw new AccessDeniedException();
        }

        // Check the access token hasn't expired
        // Ensure the auth code hasn't expired
        if ($this->accessToken->isExpired() === true) {
            throw new AccessDeniedException();
        }

        return true;
    }

    /**
     * Reads in the access token from the headers
     *
     * @param bool $headerOnly Limit Access Token to Authorization header
     *
     * @throws \OAuth2\Server\Exception\InvalidRequestException Thrown if there is no access token presented
     *
     * @return string
     */
    public function determineAccessToken($headerOnly = FALSE)
    {
		switch ($headerOnly){
			case FALSE:
				$accessToken = $this->requestHandler->getParam($this->tokenKey);
				if ($accessToken !== null){
					break;
				}
			case TRUE:
				$tokenType = $this->getTokenType();
				if (strrpos(get_class($tokenType),"Bearer") !== FALSE){
					$accessToken = $tokenType->determineAccessTokenInHeader($this->requestHandler,$this->authHeader);
				}else{
					$accessToken = $tokenType->determineAccessTokenInHeader($this->requestHandler);
				}
				break;
		}

        if (empty($accessToken)) {
            throw new InvalidRequestException('access token');
        }

        return $accessToken;
    }
}


<?php

namespace Amcms\Services;

use Amcms\Services\Service;

class GlobalPhsService extends Service
{
    protected $phs = [];

    /**
     * Add/write global placeholder
     *
     * @param string $ph
     * @param mixed $value
     * @return null
     */
    public function set($ph, $value, $namespace = null)
    {
        if ($namespace) {
            $this->phs[$namespace][$ph] = $value;
        } else {
            $this->phs[$ph] = $value;
        }

        if ($this->twig) {
            $this->twig->setGlobal($ph, $value, ['namespace' => $namespace]);
        }

        if ($this->quad) {
            $this->quad->setGlobal($ph, $value);
        }
    }

    /**
     * Get global placeholder
     *
     * @param string $ph
     * @return mixed|null
     */
    public function get($ph)
    {
        if (isset($this->phs[$ph])) {
            return $this->phs[$ph];
        }

        return null;
    }

}


<?php

namespace Environaut;

use Symfony\Component\Finder\Finder;

/**
 * This class compiles all necessary files of Environaut to an executable
 * environaut.phar file that may be executed directly (run standalone).
 */
class PharCompiler
{
    /**
     * Creates a PHP archive file with all files necessary to
     * run Environaut standalone.
     *
     * @param string $phar_path full path to the php archive file to create
     */
    public function create($phar_path = 'environaut.phar')
    {
        if (file_exists($phar_path)) {
            unlink($phar_path);
        }

        $phar = new \Phar($phar_path, 0, 'environaut.phar');

        $phar->setSignatureAlgorithm(\Phar::SHA1);

        $phar->startBuffering();

        $root_dir = dirname(dirname(__DIR__));

        // add environaut files
        $finder = new Finder();

        $finder->files()->notName('PharCompiler.php')->in($root_dir . '/src');

        foreach ($finder as $file) {
            $phar->addFile($file->getRealPath(), 'src/' . $file->getRelativePathname());
        }

        // add vendor files using a whitelist with excludes
        $finder = new Finder();
        $finder->files()
            ->name('*.php')
            ->name('security\.sensiolabs\.org\.crt')
            ->path('/symfony\/console\//')
            ->path('/sensiolabs\/security-checker\//')
            ->notName('SecurityCheckerCommand.php')
            ->notPath('/(\/Tests\/|\/Tester\/)/')
            ->in($root_dir . '/vendor');

        foreach ($finder as $file) {
            $phar->addFile($file->getRealPath(), 'vendor/' . $file->getRelativePathname());
        }

        // add composer vendor autoloading
        $vendor_root_dir = $root_dir . '/vendor/';
        $phar->addFile($vendor_root_dir . 'autoload.php', 'vendor/autoload.php');
        $composer_dir = $vendor_root_dir . 'composer/';
        $phar->addFile($composer_dir . 'autoload_namespaces.php', 'vendor/composer/autoload_namespaces.php');
        $phar->addFile($composer_dir . 'autoload_classmap.php', 'vendor/composer/autoload_classmap.php');
        $phar->addFile($composer_dir . 'autoload_psr4.php', 'vendor/composer/autoload_psr4.php');
        $phar->addFile($composer_dir . 'autoload_real.php', 'vendor/composer/autoload_real.php');
        //$phar->addFile($composer_dir . 'include_paths.php', 'vendor/composer/include_paths.php');
        $phar->addFile($composer_dir . 'ClassLoader.php', 'vendor/composer/ClassLoader.php');

        // environaut executable
        $phar->addFile($root_dir . '/bin/environaut', 'bin/environaut');

        // additional markdown files like README.md or LICENSE.md
        $finder = new Finder();
        $finder->files()->name('*.md')->depth('== 0')->in($root_dir);
        foreach ($finder as $file) {
            $phar->addFile($file->getRealPath(), '/' . $file->getRelativePathname());
        }

        // add startup file
        $phar->setStub($this->getStub());

        $phar->stopBuffering();

        chmod($phar_path, 0755);
    }

    /**
     * @return string initial stub to startup environaut when executing the phar
     */
    protected function getStub()
    {
        $stub = <<<'EOF'
#!/usr/bin/env php
<?php

try {
    Phar::mapPhar('environaut.phar');
    require 'phar://environaut.phar/bin/environaut';
} catch (PharException $e) {
    echo $e->getTraceAsString();
    exit(1);
}

__HALT_COMPILER();
EOF;

        return $stub;
    }
}


<?php

namespace Limber\Router;

use Symfony\Component\HttpFoundation\Request;

abstract class Router
{
    /**
     * @var array
     */
    protected $config = [
        'scheme' => null,
        'host' => null,
        'prefix' => null,
        'namespace' => null,
        'middleware' => [],
    ];

    /**
     * Route path parameter patterns
     *
     * @var array
     */
    protected static $patterns = [
        'alpha' => '[a-z]+',
        'int' => '\d+',
        'alphanumeric' => '[a-z0-9]+',
        'uuid' => '[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}',
        'hex' => '[a-f0-9]+',
    ];

    /**
     * Router constructor.
     * @param array<Route>|null $routes
     */
    abstract public function __construct(array $routes = null);

    /**
     * Add a route
     *
     * @param array $methods
     * @param string $uri
     * @param string|callable $target
     * @return Route
     */
    abstract public function add($methods, string $uri, $target): Route;

    /**
     * Resolve the matching Route.
     *
     * @param Request $request
     * @return Route|null
     */
    abstract public function resolve(Request $request): ?Route;

    /**
     * Return all HTTP methods supported by the endpoint.
     *
     * @param Request $request
     * @return array<string>
     */
    abstract public function getMethodsForUri(Request $request): array;

    /**
     * Create/overwrite a regex pattern
     *
     * @param string $name
     * @param string $regex
     * @return void
     */
    public static function setPattern(string $name, string $regex): void
    {
        static::$patterns[$name] = $regex;
    }

    /**
     * Get a regex pattern by name
     *
     * @param string $name
     * @return string|null
     */
    public static function getPattern(string $name): ?string
    {
        if( array_key_exists($name, static::$patterns) ){
            return static::$patterns[$name];
        }

        return null;
    }

    /**
     * @param string $uri
     * @param string|callable $target
     * @return Route
     */
    public function get($uri, $target): Route
    {
        return $this->add([Request::METHOD_GET], $uri, $target);
    }

    /**
     * @param string $uri
     * @param string|callable $target
     * @return Route
     */
    public function post($uri, $target): Route
    {
        return $this->add([Request::METHOD_POST], $uri, $target);
    }

    /**
     * @param string $uri
     * @param string|callable $target
     * @return Route
     */
    public function put($uri, $target): Route
    {
        return $this->add([Request::METHOD_PUT], $uri, $target);
    }

    /**
     * @param string $uri
     * @param string|callable $target
     * @return Route
     */
    public function patch($uri, $target): Route
    {
        return $this->add([Request::METHOD_PATCH], $uri, $target);
    }

    /**
     * @param string $uri
     * @param string|callable $target
     * @return Route
     */
    public function delete(string $uri, $target): Route
    {
        return $this->add([Request::METHOD_DELETE], $uri, $target);
    }

    /**
     * @param string $uri
     * @param string|callable $target
     * @return Route
     */
    public function head(string $uri, $target): Route
    {
        return $this->add([Request::METHOD_HEAD], $uri, $target);
    }

    /**
     * @param string $uri
     * @param string|callable $target
     * @return Route
     */
    public function options(string $uri, $target): Route
    {
        return $this->add([Request::METHOD_OPTIONS], $uri, $target);
    }

    /**
     * @param array $config
     * @param \Closure $callback
     * @return void
     */
    public function group(array $config, \Closure $callback): void
    {
        // Save current config
        $previousConfig = $this->config;

        // Merge config values
        $this->config = $this->mergeGroupConfig($config);

        // Process routes in closure
        $callback($this);

        // Restore previous config
        $this->config = $previousConfig;
    }

    /**
     * Merge parent route Group configs in with child group.
     *
     * @param array<string> $groupConfig
     * @return array
     */
    protected function mergeGroupConfig(array $groupConfig): array
    {
        $config = $this->config;

        $config['hostname'] = $groupConfig['hostname'] ?? null;
        $config['prefix'] = $groupConfig['prefix'] ?? null;
        $config['namespace'] = $groupConfig['namespace'] ?? null;

        if( array_key_exists('middleware', $groupConfig) ){

            if( array_key_exists('middleware', $config) ){
                $config['middleware'] = array_merge($config['middleware'], $groupConfig['middleware']);
            }

            else {
                $config['middleware'] = $groupConfig['middleware'];
            }
        }

        return $config;
    }
}


<?php

/**
 * Openbizx Framework
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin.data.private
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: BizDataObj_Assoc.php 3975 2011-04-27 15:51:18Z jixian2003 $
 */

namespace Openbizx\Data\Tools;

/**
 * BizDataObj_Assoc class takes care of add and remove record according to
 * data object association
 *
 * @package openbiz.bin.data.private
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @access private
 */
class BizDataObj_Assoc
{

    /**
     * Add a new record to current record set
     *
     * @param BizDataObj $dataObj - the instance of BizDataObj
     * @param array $recArr - the record array to be added in the data object
     * @param boolean &$isParentObjUpdated - flag that indicates if the parent form needs to be updated
     * @return boolean
     */
    public static function addRecord($dataObj, $recArr, &$isParentObjUpdated)
    {
        if ($dataObj->association["Relationship"] == "M-M") {
            $isParentObjUpdated = false;
            return self::_addRecordMtoM($dataObj, $recArr);
        } elseif ($dataObj->association["Relationship"] == "Self-Self") {
            $isParentObjUpdated = false;
            return self::_addRecordSelftoSelf($dataObj, $recArr);
        } elseif ($dataObj->association["Relationship"] == "M-1" || $dataObj->association["Relationship"] == "1-1") {
            $isParentObjUpdated = true;
            return self::_addRecordMto1($dataObj, $recArr);
        } elseif ($dataObj->association["Relationship"] == "1-M") {
            $isParentObjUpdated = false;
            return self::_addRecord1toM($dataObj, $recArr);
        } else {
            throw new Openbizx\Data\Exception("You cannot add a record in dataobj who doesn't have M-M or M-1 or Self-Self relationship with its parent object");
            return false;
        }
    }

    /**
     * Add record many to many (M-M)
     *
     * @param BizDataObj $dataObj
     * @param array $recArr
     * @return boolean
     */
    private static function _addRecordMtoM($dataObj, $recArr)
    {
        // query on this object to get the corresponding record of this object.
        $searchRule = "[Id] = '" . $recArr["Id"] . "'";
        $recordList = $dataObj->directFetch($searchRule, 1);
        if (count($recordList) == 1) {
            return true;
        }

        // insert a record on XTable
        $db = $dataObj->getDBConnection();
        $xDataObj = isset($dataObj->association["XDataObj"]) ? $dataObj->association["XDataObj"] : null;
        $val1 = $dataObj->association["FieldRefVal"];
        $val2 = $recArr["Id"];
        if ($xDataObj) {   // get new record from XDataObj
            $xObj = Openbizx::getObject($xDataObj);
            $newRecArr = $xObj->newRecord();
            // verify the main table of XDataobj is same as the XTable
            if ($xObj->mainTableName != $dataObj->association["XTable"]) {
                throw new Openbizx\Data\Exception("Unable to create a record in intersection table: XDataObj's main table is not same as XTable.");
                //return false;
            }
            $fld1 = $xObj->getFieldNameByColumn($dataObj->association["XColumn1"]);
            $newRecArr[$fld1] = $val1;
            $fld2 = $xObj->getFieldNameByColumn($dataObj->association["XColumn2"]);
            $newRecArr[$fld2] = $val2;
            $ok = $xObj->insertRecord($newRecArr);
            if ($ok === false) {
                throw new Openbizx\Data\Exception($xObj->getErrorMessage());
                //return false;
            }
        } else {
            $sql_col = "(" . $dataObj->association["XColumn1"] . ","
                    . $dataObj->association["XColumn2"] . ")";

            $sql_val = "('" . $val1 . "','" . $val2 . "')";
            $sql = "INSERT INTO " . $dataObj->association["XTable"] . " "
                    . $sql_col . " VALUES " . $sql_val;

            try {
                Openbizx::$app->getLog()->log(LOG_DEBUG, "DATAOBJ", "Associate Insert Sql = $sql");
                $db->query($sql);
            } catch (Exception $e) {
                Openbizx::$app->getLog()->log(LOG_ERR, "DATAOBJ", "Query Error: " . $e->getMessage());
                throw new Openbizx\Data\Exception("Query Error: " . $e->getMessage());
                return false;
            }
        }

        // add the record to object cache. requery on this object to get the corresponding record of this object.
        $searchRule = "[Id] = '" . $recArr["Id"] . "'";
        $recordList = $dataObj->directFetch($searchRule, 1);
        if (count($recordList) == 0)
            return false;
        return true;
    }

    private static function _addRecordSelftoSelf($dataObj, $recArr)
    {
        $result = self::_addRecordMtoM($dataObj, $recArr);
        return true;
    }

    /**
     * Add record Many to One (M-1)
     * @param BizDataObj $dataObj
     * @param array $recArr
     * @return boolean
     */
    private static function _addRecordMto1($dataObj, $recArr)
    {
        // set the $recArr[Id] to the parent table foriegn key column
        // get parent/association dataobj
        $asscObj = Openbizx::getObject($dataObj->association["AsscObjName"]);
        // call parent dataobj's updateRecord
        $updateRecArr["Id"] = $asscObj->getFieldValue("Id");
        $updateRecArr[$dataObj->association["FieldRef"]] = $recArr["Id"];
        $ok = $asscObj->updateRecord($updateRecArr);
        if ($ok == false)
            return false;
        // requery on this object
        $dataObj->association["FieldRefVal"] = $recArr["Id"];
        return $dataObj->runSearch();
    }

    private static function _addRecord1toM($dataObj, $recArr)
    {
        $column = $dataObj->association['Column'];
        $field = $dataObj->getFieldNameByColumn($column);

        $parentRefVal = $dataObj->association["FieldRefVal"];

        $newRecArr["Id"] = $recArr["Id"];
        $newRecArr[$field] = $parentRefVal;

        $column2 = $dataObj->association['Column2'];
        $field2 = $dataObj->getFieldNameByColumn($column2);

        $parentRefVal2 = $dataObj->association["FieldRefVal2"];
        if ($column2) {
            $newRecArr[$field2] = $parentRefVal2;
        }

        $cond_column = $dataObj->association['CondColumn'];
        $cond_value = $dataObj->association['CondValue'];
        if ($cond_column) {
            $cond_field = $dataObj->getFieldNameByColumn($cond_column);
            $newRecArr[$cond_field] = $cond_value;
        }

        $newDO = Openbizx::getObject($dataObj->objectName, 1);
        $ok = $newDO->updateRecord($newRecArr, $recArr);

        if ($ok == false)
            return false;
        // requery on this object
        return true;
    }

    /**
     * Remove a record from current record set of current association relationship
     *
     * @param BizDataObj $dataObj - the instance of BizDataObj
     * @param array $recArr - the record array to be removed from the data object
     * @param boolean &$isParentObjUpdated - flag that indicates if the parent form needs to be updated
     * @return boolean
     */
    public static function removeRecord($dataObj, $recArr, &$isParentObjUpdated)
    {
        if ($dataObj->association["Relationship"] == "M-M") {
            $isParentObjUpdated = false;
            return self::_removeRecordMtoM($dataObj, $recArr);
        } elseif ($dataObj->association["Relationship"] == "Self-Self") {
            $isParentObjUpdated = false;
            return self::_removeRecordSelftoSelf($dataObj, $recArr);
        } elseif ($dataObj->association["Relationship"] == "M-1" || $dataObj->association["Relationship"] == "1-1") {
            $isParentObjUpdated = true;
            return self::_removeRecordMto1($dataObj, $recArr);
        } elseif ($dataObj->association["Relationship"] == "1-M") {
            $isParentObjUpdated = false;
            return self::_removeRecord1toM($dataObj, $recArr);
        } else {
            throw new Openbizx\Data\Exception("You cannot add a record in dataobj who doesn't have M-M or M-1 or Self-Self relationship with its parent object");
            return false;
        }
    }

    /**
     * Remove record many to many
     *
     * @param BizDataObj $dataObj
     * @param array $recArr
     * @return boolean
     */
    private static function _removeRecordMtoM($dataObj, $recArr)
    {
        // delete a record on XTable
        $db = $dataObj->getDBConnection();

        //TODO: delete using XDataObj if XDataObj is defined

        $where = $dataObj->association["XColumn1"] . "='" . $dataObj->association["FieldRefVal"] . "'";
        $where .= " AND " . $dataObj->association["XColumn2"] . "='" . $recArr["Id"] . "'";
        $sql = "DELETE FROM " . $dataObj->association["XTable"] . " WHERE " . $where;

        try {
            Openbizx::$app->getLog()->log(LOG_DEBUG, "DATAOBJ", "Associate Delete Sql = $sql");
            $db->query($sql);
        } catch (Exception $e) {
            Openbizx::$app->getLog()->log(LOG_ERR, "DATAOBJ", "Query Error: " . $e->getMessage());
            throw new Openbizx\Data\Exception("Query Error: " . $e->getMessage());
            return false;
        }
        return true;
    }

    private static function _removeRecordSelftoSelf($dataObj, $recArr)
    {
        // delete a record on XTable
        $db = $dataObj->getDBConnection();

        //TODO: delete using XDataObj if XDataObj is defined

        $where = $dataObj->association["XColumn1"] . "='" . $dataObj->association["FieldRefVal"] . "'";
        $where .= " AND " . $dataObj->association["XColumn2"] . "='" . $recArr["Id"] . "'";
        $sql = "DELETE FROM " . $dataObj->association["XTable"] . " WHERE " . $where;

        $where_2 = $dataObj->association["XColumn2"] . "='" . $dataObj->association["FieldRefVal"] . "'";
        $where_2 .= " AND " . $dataObj->association["XColumn1"] . "='" . $recArr["Id"] . "'";
        $sql_2 = "DELETE FROM " . $dataObj->association["XTable"] . " WHERE " . $where_2;

        try {
            Openbizx::$app->getLog()->log(LOG_DEBUG, "DATAOBJ", "Associate Delete Sql = $sql");
            $db->query($sql);
            $db->query($sql_2);
        } catch (Exception $e) {
            Openbizx::$app->getLog()->log(LOG_ERR, "DATAOBJ", "Query Error: " . $e->getMessage());
            throw new Openbizx\Data\Exception("Query Error: " . $e->getMessage());
            return false;
        }
        return true;
    }

    /**
     * Remove record many to one
     *
     * @global BizSystem $g_BizSystem
     * @param BizDataObj $dataObj
     * @param array $recArr
     * @return boolean
     */
    private static function _removeRecordMto1($dataObj, $recArr)
    {
        // set the $recArr[Id] to the parent table foriegn key column
        // get parent/association dataobj
        $asscObj = Openbizx::getObject($dataObj->association["AsscObjName"]);
        // call parent dataobj's updateRecord
        $updateRecArr["Id"] = $asscObj->getFieldValue("Id");
        $updateRecArr[$dataObj->association["FieldRef"]] = "";
        $ok = $asscObj->updateRecord($updateRecArr);
        if ($ok == false)
            return false;
        // requery on this object
        $dataObj->association["FieldRefVal"] = "";
        return $dataObj->runSearch();
    }

    private static function _removeRecord1toM($dataObj, $recArr)
    {

        $column = $dataObj->association['Column'];
        $field = $dataObj->getFieldNameByColumn($column);

        $column2 = $dataObj->association['Column2'];
        $field2 = $dataObj->getFieldNameByColumn($column2);

        $newRecArr["Id"] = $recArr["Id"];
        $newRecArr[$field] = '';

        if ($field2) {
            $newRecArr[$field2] = '';
        }

        $cond_column = $dataObj->association['CondColumn'];
        $cond_value = $dataObj->association['CondValue'];

        if ($cond_column) {
            $cond_field = $dataObj->getFieldNameByColumn($cond_column);
            $newRecArr[$cond_field] = $cond_value;
        }
        $ok = Openbizx::getObject($dataObj->objectName, 1)->updateRecord($newRecArr, $recArr);
        if ($ok == false)
            return false;
        // requery on this object
        return true;
    }

}


<?php
namespace DdvPhp\DdvUtil\Laravel;

use DdvPhp\DdvUtil\Exception;
use DdvPhp\DdvUtil\Laravel\Proxy\Interfaces\TransactionQuque;
use DdvPhp\DdvUtil\String\Conversion;

/**
 * @mixin \DdvPhp\DdvUtil\Laravel\EloquentBuilder
 * @mixin \DdvPhp\DdvUtil\Laravel\QueryBuilder
 * @mixin \Illuminate\Database\Eloquent\Model
 */
trait Model
{
    protected $ddvSnakeAttributes = null;

    /**
     * Get the model's relationships in array form.
     *
     * @return array
     */
    public function relationsToArray(){
        $snakeAttributes = null;
        if (isset($this->ddvSnakeAttributes)&&is_bool($this->ddvSnakeAttributes)){
            $snakeAttributes = static::$snakeAttributes;
            static::$snakeAttributes = $this->ddvSnakeAttributes;
        }
        $res = parent::relationsToArray();
        is_null($snakeAttributes) || (static::$snakeAttributes = $snakeAttributes);
        return $res;
    }
    /**
     * 小写下滑杠转驼峰
     * @param true|false $isConversionOriginal [是否强制转换源]
     * @return Model $this [请求对象]
     */
    public function toHump($isConversionOriginal = false){
        if ($isConversionOriginal){
            $this->original = Conversion::underlineToHumpByIndexArray($this->original);
        }
        if (!empty($this->relations)){
            if (is_array($this->relations)||is_object($this->relations)){
                foreach ($this->relations as $key => $item){
                    if (empty($item)||!is_object($item)){
                        continue;
                    }
                    if (method_exists($item, 'toHump')){
                        $this->relations[$key] = $item->toHump();
                    }
                }
            }
        }
        $this->ddvSnakeAttributes = false;
        $this->attributes = Conversion::underlineToHumpByIndexArray($this->attributes);
        return $this;
    }
    /**
     * 下滑杠转小写驼峰
     * @param true|false $isConversionOriginal [是否强制转换源]
     * @return Model $this [请求对象]
     */
    public function toUnderline($isConversionOriginal = false){
        if ($isConversionOriginal){
            $this->original = Conversion::humpToUnderlineByIndexArray($this->original);
        }
        if (!empty($this->relations)){
            if (is_array($this->relations)||is_object($this->relations)){
                foreach ($this->relations as $key => $item){
                    if ((!empty($item))&&is_object($item)&&method_exists($item, 'toUnderline')){
                        $this->relations[$key] = $item->toUnderline();
                    }
                }
            }
        }
        $this->ddvSnakeAttributes = true;
        $this->attributes = Conversion::humpToUnderlineByIndexArray($this->attributes);
        return $this;
    }
    /**
     * 返回小写下滑杠转驼峰
     * @param true|false $isConversionOriginal [是否强制转换源]
     * @return array $data [请求数组]
     */
    public function toHumpArray($isConversionOriginal = false){
        return $this->toHump($isConversionOriginal)->toArray();
    }
    /**
     * 设置保存数据 驼峰自动转小写下划线
     * @param array $data [需要保存的数组]
     * @return static|Model|$this [请求对象]
     */
    public function setDataByHumpArray ($data = array()) {
        return $this->setDataByArray(Conversion::humpToUnderlineByArray($data));
    }

    /**
     * 设置保存数据 数组自动遍历保存
     * @param array $data 需要保存的数组
     * @return static|Model|$this
     */
    public function setDataByArray ($data = array()) {
        return $this->setData($data);
    }

    /**
     * @param $model
     * @param null $defaultData
     * @param bool $isInitDefaultData
     * @return static|Model|$this
     * @throws Exception
     */
    public function setDataByModel ($model, $defaultData = null, $isInitDefaultData = true){
        if (is_object($model)&&method_exists($model, 'toArray')){
            $data = $isInitDefaultData ? (empty($defaultData) ? [] : $defaultData) : [];
            return $this->setDataByArray(array_merge($data, $model->toArray()));
        }else{
            if (empty($defaultData)&&!is_array($defaultData)){
                throw new Exception('Model is empty, please set the default data');
            }else{
                return $this->setDataByArray($defaultData);
            }
        }
    }
    /**
     * 设置保存数据 数组自动遍历保存
     * @param array $data [需要保存的数组]
     * @return static|Model|$this [请求对象]
     */
    public function setData ($data = array()) {
        if (method_exists(parent::class, 'setData')){
            call_user_func_array(array(parent::class, 'setData'), func_get_args());
        }elseif (!empty($data)&&(is_array($data)||is_object($data))){
            foreach ($data as $key => $v) {
                $this->setAttribute($key, $v);
            }
        }
        return $this;
    }

    /**
     * 移动资源
     * @param $keyOld
     * @param $keyNew
     * @param null $defaultData
     * @return static|Model|$this [请求对象]
     */
    public function moveRelation($keyOld, $keyNew, $defaultData = null){
        if (empty($this->relations[$keyOld])){
            $this->setAttribute($keyNew, $defaultData);
            @$this->removeAttribute($keyOld);
        }else{
            $this->relations[$keyNew] = $this->relations[$keyOld];
            $this->removeAttribute($keyOld);
        }
        return $this;
    }

    /**
     * 资源复制别名
     * @param $keyOld
     * @param $keyNew
     * @return static|Model|$this [请求对象]
     */
    public function aliasRelation($keyOld, $keyNew){
        if (!empty($this->relations[$keyOld])){
            $this->relations[$keyNew] = &$this->relations[$keyOld];
        }
        return $this;
    }

    /**
     * 插入属性
     *
     * @param  string  $key
     * @param  mixed  $value
     * @return static|Model|$this [请求对象]
     */
    public function pushAttribute($key, $value)
    {
        $array = $this->getAttribute($key);
        $array = is_array($array)?$array:array();
        $array[] = $value;
        $this->setAttribute($key, $array);
        return $this;
    }

    /**
     * 移除一个参数
     * @param $key
     */
    public function removeAttribute($key){
        if(!empty($key)&&is_array($key)){
            array_map([$this, 'removeAttribute'], $key);
            return $this;
        }elseif(strpos($key, ',')!==false){
            $this->removeAttribute(explode(',', $key));
        }
        unset($this->$key);
        return $this;
    }
    /**
     * Create a new Eloquent query builder for the model.
     *
     * @param  \Illuminate\Database\Query\Builder  $query
     * @return EloquentBuilder|static
     */
    public function newEloquentBuilder($query)
    {
        return new EloquentBuilder($query);
    }
    /**
     * Create a new Eloquent Collection instance.
     *
     * @param  array  $models
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function newCollection(array $models = [])
    {
        return new EloquentCollection($models);
    }
    /**
     * Get a new query builder instance for the connection.
     *
     * @return QueryBuilder
     */

    protected function newBaseQueryBuilder()
    {
        $connection = $this->getConnection();

        return new QueryBuilder(
            $connection, $connection->getQueryGrammar(), $connection->getPostProcessor()
        );
    }

    /**
     * 插入事物
     * @param TransactionQuque $quque
     * @return static|Model
     * @throws Exceptions\ProxyExceptions
     */
    public static function pushQuqueTransaction(TransactionQuque $quque){
        $model = new static();
        $quque->pushTransactionModel($model);
        return $model;
    }
}


<?php

/**
 * Openbizx Framework
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id$
 */

namespace Openbizx\Object;

use Openbizx\Openbizx;
use Openbizx\ClassLoader;

/**
 * MetaObject is the base class of all derived metadata-driven classes
 *
 * @package   openbiz.bin
 * @author    Rocky Swen
 * @copyright Copyright (c) 2005-2009, Rocky Swen
 * @access    public
 */
abstract class MetaObject //extends BizObject
{

    /**
     * Name of meta-object
     *
     * @var string
     */
    public $objectName;

    /**
     * Class name of meta-object
     *
     * @var string
     */
    public $className;

    /**
     * Package of meta-object
     *
     * @var string
     */
    public $package;

    /**
     * Description of meta-object
     *
     * @var string
     */
    public $objectDescription;
    public $access;
    public $stateless;

    function __construct(&$config)
    {
    }

    //function __destruct() {}

    /**
     * Read meta data
     *
     * @param array $xmlArr
     * @return void
     */
    protected function readMetadata(&$xmlArr)
    {
        $rootKeys = array_keys($xmlArr);
        $rootKey = $rootKeys[0];
        if ($rootKey != "ATTRIBUTES") {
            $this->objectName = isset($xmlArr[$rootKey]["ATTRIBUTES"]["NAME"]) ? $xmlArr[$rootKey]["ATTRIBUTES"]["NAME"] : null;
            $this->objectDescription = isset($xmlArr[$rootKey]["ATTRIBUTES"]["DESCRIPTION"]) ? $xmlArr[$rootKey]["ATTRIBUTES"]["DESCRIPTION"] : null;
            $this->package = isset($xmlArr[$rootKey]["ATTRIBUTES"]["PACKAGE"]) ? $xmlArr[$rootKey]["ATTRIBUTES"]["PACKAGE"] : null;
            $this->className = isset($xmlArr[$rootKey]["ATTRIBUTES"]["CLASS"]) ? $xmlArr[$rootKey]["ATTRIBUTES"]["CLASS"] : null;
            $this->access = isset($xmlArr[$rootKey]["ATTRIBUTES"]["ACCESS"]) ? $xmlArr[$rootKey]["ATTRIBUTES"]["ACCESS"] : null;
        } else {
            $this->objectName = isset($xmlArr["ATTRIBUTES"]["NAME"]) ? $xmlArr["ATTRIBUTES"]["NAME"] : null;
            $this->objectDescription = isset($xmlArr["ATTRIBUTES"]["DESCRIPTION"]) ? $xmlArr["ATTRIBUTES"]["DESCRIPTION"] : null;
            $this->package = isset($xmlArr["ATTRIBUTES"]["PACKAGE"]) ? $xmlArr["ATTRIBUTES"]["PACKAGE"] : null;
            $this->className = isset($xmlArr["ATTRIBUTES"]["CLASS"]) ? $xmlArr["ATTRIBUTES"]["CLASS"] : null;
            $this->access = isset($xmlArr["ATTRIBUTES"]["ACCESS"]) ? $xmlArr["ATTRIBUTES"]["ACCESS"] : null;
        }
    }

    public function getModuleName($name)
    {
        return substr($name, 0, intval(strpos($name, '.')));
    }

    /**
     * Read metadata collection
     *
     * @param array $xmlArr
     * @param array $metaList
     * @return void
     */
    protected function readMetaCollection(&$xmlArr, &$metaList)
    {
        if (!$xmlArr) {
            $metaList = null;
            return;
        }
        if (isset($xmlArr["ATTRIBUTES"])) {
            $metaList[] = $xmlArr;
        } else {
            $metaList = $xmlArr;
        }
    }

    /**
     * Set Prefix Package
     *
     * @param string $name
     * @return string     *
     * @todo NOTE: this is helper method, need to refactor
     */
    protected function prefixPackage($name)
    {
        // no package prefix as package.object, add it
        if ($name && !strpos($name, ".") && ($this->package)) {
            $name = $this->package . "." . $name;
        }
        return $name;
    }

    /**
     * Get property
     *
     * @param string $propertyName
     * @return mixed
     *
     * @todo Not safe, because can access private and protected variable. Need enhancment or delete
     */
    public function getProperty($propertyName)
    {
        // TODO: really like this?
        if (isset($this->$propertyName)) {
            return $this->$propertyName;
        }
        return null;
    }

    /**
     * Check is allow access?
     *
     * @global BizSystem $g_BizSystem
     * @param <type> $access
     * @return <type>
     */
    public function allowAccess($access = null)
    {
        if (CLI) {
            return OPENBIZ_ALLOW;
        }
        if (!$access) {
            $access = $this->access;
        }
        if ($access) {
            return Openbizx::$app->allowUserAccess($access);
        }
        return OPENBIZ_ALLOW;
    }

    protected function getElementObject(&$config, $defaultClassName, $parentObj = null)
    {
        // find the class attribute
        $className = isset($config["ATTRIBUTES"]['CLASS']) ? $config["ATTRIBUTES"]['CLASS'] : $defaultClassName;
        $obj = new $className($config, $parentObj);
        return $obj;
    }

}


<?php
/**
 * @author    Antoine Hedgecock <antoine.hedgecock@gmail.com>
 *
 * @copyright Interactive Solutions
 */

declare(strict_types = 1);

namespace InteractiveSolutions\Bernard\Factory\Driver;

use Interop\Container\ContainerInterface;
use Redis;
use Bernard\Driver\PhpRedisDriver;
use InteractiveSolutions\Bernard\BernardOptions;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class PhpRedisDriverFactory implements FactoryInterface
{
    /**
     * {@inheritdoc}
     */
    public function createService(ServiceLocatorInterface $serviceLocator):PhpRedisDriver
    {
        return $this->build($serviceLocator);
    }

    public function __invoke(ContainerInterface $container)
    {
        return $this->build($container);
    }

    /**
     * Build the object
     *
     * @param ServiceLocatorInterface|ContainerInterface $container
     *
     * @return PhpRedisDriver
     */
    private function build($container):PhpRedisDriver
    {
        /* @var $options BernardOptions */
        $options = $container->get(BernardOptions::class);

        /* @var $instance Redis */
        $instance = $container->get($options->getRedisInstanceKey());

        return new PhpRedisDriver($instance);
    }
}


<?php

namespace Arseniew\Silex\Application;

/**
 * Idiorm trait.
 *
 * @author Marcin Batkowski <arseniew@gmail.com>
 */

trait IdiormTrait
{
    /**
     * Returns configured Idiorm instance
     *
     * @param string $table      table Name
     * @param string $connection Connection name
     *
     * @return \ORM Idiorm instance
     */
    public function getModel($table, $connection = null)
    {
        if (!$connection) {
            return $this['idiorm.db']->for_table($table);
        } else {
            return $this['idiorm.dbs'][$connection]->for_table($table);
        }
    }
}


<?php
/*
This is part of Wedeto, the WEb DEvelopment TOolkit.
It is published under the MIT Open Source License.

Copyright 2017, Egbert van der Wal

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Wedeto\Resolve;

use Wedeto\Util\LoggerAwareStaticTrait;
use Wedeto\Util\Cache\Cache;

class Resolver
{
    use LoggerAwareStaticTrait;

    /** The cache to store all resolve data */
    protected $cache;

    /** If the modules are sorted on precedence */
    protected $sorted = true;

    /** The modules in use in the manager */
    protected $modules = array();

    /** The resolvers */
    protected $resolvers = array();

    /** The authorative mode */
    protected $authoritive = false;

    /** The name of the main module */
    protected $main_module = "main";

    /**
     * Set up the manager.
     * @param Cache $cache The cache to use for the resolvers.
     */
    public function __construct(Cache $cache = null)
    {
        $this->cache = $cache;
    }

    /**
     * Add a resolver type
     * @param string $type The resolver type to add
     * @param string $path The sub-path this resolver looks in in each module
     * @param string $extension The required extension on resolved elements. If absent from a reference,
     *                          it will be appended
     * @param SubResolver $instance A way to pass in a SubResolver instance. When null, a new one will be
     *                           instantiated. Cannot be used in combination with $extension
     * @return Resolver Provides fluent interface
     */
    public function addResolverType(string $type, string $path, string $extension = "", SubResolver $instance = null)
    {
        // Check argument validity
        if (isset($this->resolvers[$type]))
            throw new \LogicException("Duplicate resolver type: " . $type);

        if ($instance !== null && $extension !== "")
            throw new \LogicException("Cannot set a file extension for a provided instance");

        // Instantiate a new resolver when none has been passed
        if ($instance === null)
            $instance = new SubResolver($type, $extension);

        $this->resolvers[$type] = [
            'path' => $path,
            'resolver' => $instance
        ];

        if ($this->cache)
            $this->resolvers[$type]['resolver']->setCache($this->cache);

        // Register found modules with the new resolver
        foreach ($this->modules as $name => $module_path)
            if (is_dir($module_path . DIRECTORY_SEPARATOR . $path))
                $instance->addToSearchPath($name, $path);

        return $this;
    }

    /**
     * Return a resolver instance
     * @param string $type The resolver type to return
     * @return Resolver The resolver instance
     * @throws InvalidArgumentException When the resolver type is unknown
     */
    public function getResolver(string $type)
    {
        if (!isset($this->resolvers[$type]))
            throw new \InvalidArgumentException("Unknown resolver type: " . $type);
        return $this->resolvers[$type]['resolver'];
    }

    /**
     * Replace a resolver with a custom instance
     * @param string $type The resolver to replace
     * @param SubResolver $resolver The SubResolver instance
     * @return Resolver Provides fluent interface
     */
    public function setResolver(string $type, SubResolver $resolver)
    {
        if (!isset($this->resolvers[$type]))
            throw new \InvalidArgumentException("Unknown resolver type: " . $type);

        if ($this->cache !== null)
            $resolver->setCache($this->cache);

        $this->resolvers[$type]['resolver'] = $resolver;
        return $this;
    }

    /**
     * @return array The list of configured resolvers, with their names as key
     */
    public function getResolvers()
    {
        $res = [];
        foreach ($this->resolvers as $name => $resolver)
            $res[$name] = $resolver['resolver'];

        return $res;
    }

    /**
     * Resolve a reference of a specific type
     * @param string $type The reference type
     * @param string $reference What to resolve
     * @return string The resolved element
     */
    public function resolve(string $type, string $reference)
    {
        if (!isset($this->resolvers[$type]))
            throw new \InvalidArgumentException("Unknown resolver type: " . $type);

        return $this->resolvers[$type]['resolver']->resolve($reference);
    }

    /**
     * Set the authorativeness of the resolvers
     * @param bool $authorative Whether the resolvers are authorative or not: whether
     *                          they trust cached resolve failures or not.
     *                          This improves performance in production but can be inconvenient
     *                          in development.
     */
    public function setAuthorative(bool $authorative)
    {
        foreach ($this->resolvers as $resolver)
            $resolver['resolver']->setAuthorative($authorative);

        $this->authorative = $authorative;
        return $this;
    }

    /**
     * @return bool The authorativeness of the resolvers
     */
    public function getAuthorative()
    {
        return $this->authorative;
    }

    /**
     * Register a module
     *
     * @param string $module The name of the module
     * @param string $path The path where the module stores its data
     * @param int $precedence Determines the order in which the paths are
     *                        searched. Used for templates and assets, to
     *                        make it possible to reliably override others.
     * @return Resolver Provides fluent interface
     */
    public function registerModule(string $module, string $path, int $precedence)
    {
        // Normalize the module name: lowercased, with dots
        $module = strtolower(preg_replace('/([\.\\/\\\\])/', '.', $module));

        $found_elements = array();
        foreach ($this->resolvers as $type => $resolver)
        {
            $type_path = $path . DIRECTORY_SEPARATOR . $resolver['path'];
            if (is_dir($type_path))
            {
                $resolver['resolver']->addToSearchPath($module, $type_path, $precedence);
                $found_elements[] = $type;
            }
        }

        if (!empty($found_elements))
            $this->modules[$module] = ['path' => $path, 'precedence' => $precedence];
        else
            self::getLogger()->debug("No resolvable items found in module: " . $module);

        // No longer sorted, probably
        $this->sorted = false;

        return $this;
    }

    /**
     * Sort the modules on precedence
     */
    protected function sortModules()
    {
        uasort($this->modules, function ($l, $r) {
            if ($l['precedence'] !== $r['precedence'])
                return $l['precedence'] - $r['precedence'];
            return strcmp($l['path'], $r['path']);
        });
        $this->sorted = true;
    }

    /**
     * @return array Associative array of (module_name, path) pairs
     */
    public function getModules()
    {
        if (!$this->sorted)
            $this->sortModules();

        $mods = [];
        foreach ($this->modules as $name => $mod)
            $mods[$name] = $mod['path'];

        return $mods;
    }

    /**
     * Set the precedence for a module on all resolvers.
     * @param string $module The name of the module.
     * @param int $precedence The precedence value, used to order the modules.
     *                        Lower values come first.
     * @return Resolver Provides fluent interface
     */
    public function setPrecedence(string $module, int $precedence)
    {
        foreach ($this->resolvers as $type => $resolver)
        {
            try
            {
                $resolver['resolver']->setPrecedence($module, $precedence);
            }
            catch (\InvalidArgumentException $e)
            {} // Not all resolvers may contain this module
        }

        $this->modules[$module]['precedence'] = $precedence;

        // No longer sorted, probably
        $this->sorted = false;

        return $this;
    }

    /**
     * Discover the module configuration based on the Composer configuration
     *
     * @param string $vendor_dir The Composer vendor path - e.g. MyProject/vendor
     * @return Resolver Provides fluent interface
     */
    public function autoConfigureFromComposer(string $vendor_dir)
    {
        $main_dir = dirname($vendor_dir);

        // Add the main module
        $this->main_module = "main";
        $package = $main_dir . DIRECTORY_SEPARATOR . "composer.json";

        if (file_exists($package))
        {
            // A composer.json file should exist for a composer project,
            // so read the module name from that.
            $json = @file_get_contents($package);
            if ($json)
            {
                $js = @json_decode($json, true);
                if (isset($js['name']))
                    $this->main_module = $js['name'];
            }
        }

        // Register the main module with the highest precedence
        $this->registerModule($this->main_module, $main_dir, 0);

        $modules = $this->findModules($vendor_dir, "", 1);
        ksort($modules);

        $count = 0;
        foreach ($modules as $name => $path)
            $this->registerModule($name, $path, ++$count);

        return $this;
    }

    /**
     * Find modules in the specified path
     *
     * @param string $path string Where to look for the modules
     * @param string $module_name_prefix The prefix for the generated module names
     * @param int $depth The depth at which to look for modules
     */
    public static function findModules(string $path, string $module_name_prefix, int $depth)
    {
        if (!is_dir($path))
            throw new \InvalidArgumentException("Not a path: $path");

        $dirs = dir($path);

        $modules = array();
        while ($dir = $dirs->read())
        {
            if ($dir === ".." || $dir === ".")
                continue;

            $mod_path = $path . DIRECTORY_SEPARATOR . $dir;
            if (!is_dir($mod_path))
                continue;

            $dirname = ucfirst(strtolower($dir));
            $module_name = $module_name_prefix . $dirname;
            if ($depth > 0)
            {
                $sub_modules = self::findModules($mod_path, $module_name . '.', $depth - 1);
                $modules = array_merge($modules, $sub_modules);
            }
            else
            {
                $modules[$module_name] = $mod_path;
            }
        }

        return $modules;
    }
}


<?php

namespace Interpro\QuickStorage\Laravel\FieldProviding;

use Interpro\QuickStorage\Concept\Exception\FieldProvideException;
use Interpro\QuickStorage\Concept\FieldProviding\FieldExtMediator as FieldExtMediatorInterface;
use Interpro\QuickStorage\Concept\FieldProviding\FieldExtractor;
use Interpro\QuickStorage\Concept\Item\Item;

class FieldExtMediator implements FieldExtMediatorInterface
{
    public $list;//Не защищенный (пока не прояснилась вся архитектура), чтобы не усложнять

    public function __construct()
    {
        $this->list = [];
    }

    /**
     * @param string $suffix
     *
     * @return bool
     */
    public function suffixRegistered($suffix)
    {
        return array_key_exists($suffix, $this->list);
    }

    /**
     * @param string $suffix
     *
     * FieldExtractor $extractor
     *
     * @return bool
     */
    public function addSuffix($suffix, FieldExtractor $extractor)
    {
        $this->list[$suffix] = $extractor;
    }

    /**
     * @param string $entity_name
     *
     * @param int $entity_id
     *
     * @return Item $field_item
     */
    public function getField($suffix, $entity_name, $field_name, $entity_id=0)
    {
        if($this->suffixRegistered($suffix))
        {
            $extractor = $this->list[$suffix];
            return $extractor->getField($entity_name, $field_name, $entity_id);
        }else{
            throw new FieldProvideException('Суффикс поля не зарегестрирован ('.$suffix.')');
        }
    }

}


<?php

namespace Modules\Menu\Providers;

use Illuminate\Support\ServiceProvider;
use Modules\Menu\Events\PostMenuSetup;
use Modules\Menu\Services\MenuItemBuilder;

class MenuServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Boot the application events.
     *
     * @return void
     */
    public function boot()
    {
        $langPath = __DIR__.'/../Resources/lang';
        $this->loadTranslationsFrom($langPath, 'menu');

        $viewPath = __DIR__.'/../Resources/views';
        $this->loadViewsFrom($viewPath, 'menu');
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('menu.builder', MenuItemBuilder::class);

        view()->composer('vain::app', function ($view) {
            // delay event trigger to the very
            // last step of menu creation
            $handler = app('menu.frontend');
            $builder = app('menu.builder');
            event(new PostMenuSetup($handler, $builder));
        });
    }
}


<?php
/**
* @author SignpostMarv
*/
declare(strict_types=1);

namespace SignpostMarv\DaftRouter\Router;

use FastRoute\Dispatcher\GroupCountBased as Base;
use SignpostMarv\DaftRouter\DaftRequestInterceptor;
use SignpostMarv\DaftRouter\DaftResponseModifier;
use SignpostMarv\DaftRouter\ResponseException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class Dispatcher extends Base
{
    const INT_ARRAY_INDEX_ROUTE_ARGS = 2;

    /**
    * @param string $httpMethod
    * @param string $uri
    *
    * @return array
    */
    final public function dispatch($httpMethod, $uri)
    {
        $routeInfo = parent::dispatch($httpMethod, $uri);

        if (Dispatcher::NOT_FOUND === $routeInfo[0]) {
            throw new ResponseException('Dispatcher was not able to generate a response!', 404);
        } elseif (Dispatcher::METHOD_NOT_ALLOWED === $routeInfo[0]) {
            throw new ResponseException('Dispatcher was not able to generate a response!', 405);
        }

        return $routeInfo;
    }

    public function handle(Request $request, string $prefix = '') : Response
    {
        $regex = '/^' . preg_quote($prefix, '/') . '/';
        /**
        * @var string
        */
        $path = parse_url($request->getUri(), PHP_URL_PATH);
        $path = preg_replace($regex, '', $path);

        /**
        * @var array{1:array, 2:array<string, string>}
        */
        $routeInfo = $this->dispatch($request->getMethod(), str_replace('//', '/', ('/' . $path)));

        $routeArgs = [];

        if (isset($routeInfo[self::INT_ARRAY_INDEX_ROUTE_ARGS])) {
            $routeArgs = $routeInfo[self::INT_ARRAY_INDEX_ROUTE_ARGS];
        }

        /**
        * @psalm-var \SignpostMarv\DaftRouter\DaftRoute
        */
        $route = array_pop($routeInfo[1]) ?: '';

        /**
        * @psalm-var array<int, class-string<DaftRequestInterceptor>>
        *
        * @var array<int, string>
        */
        $firstPass = $routeInfo[1][DaftRequestInterceptor::class];

        /**
        * @psalm-var array<int, class-string<DaftResponseModifier>>
        *
        * @var array<int, string>
        */
        $secondPass = $routeInfo[1][DaftResponseModifier::class];

        $resp = $this->RunMiddlewareFirstPass($request, ...$firstPass);

        if ( ! ($resp instanceof Response)) {
            /**
            * @var Response
            */
            $resp = $route::DaftRouterHandleRequest(
                $request,
                $routeArgs
            );
        }

        $resp = $this->RunMiddlewareSecondPass($request, $resp, ...$secondPass);

        return $resp;
    }

    /**
    * @psalm-param class-string<DaftRequestInterceptor> ...$middlewares
    */
    private function RunMiddlewareFirstPass(Request $request, string ...$middlewares) : ? Response
    {
        $response = null;

        foreach ($middlewares as $middleware) {
            /**
            * @var Response|null
            */
            $response = $middleware::DaftRouterMiddlewareHandler($request, $response);
        }

        return $response;
    }

    /**
    * @psalm-param class-string<DaftResponseModifier> ...$middlewares
    */
    private function RunMiddlewareSecondPass(
        Request $request,
        Response $response,
        string ...$middlewares
    ) : Response {
        foreach ($middlewares as $middleware) {
            /**
            * @var Response
            */
            $response = $middleware::DaftRouterMiddlewareModifier($request, $response);
        }

        return $response;
    }
}


<?php

/**
 * Openbizx Framework
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin.easy
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: Panel.php 4049 2011-05-01 12:56:06Z jixian2003 $
 */

namespace Openbizx\Easy;

use Openbizx\Openbizx;
use Openbizx\Object\MetaIterator;
use Openbizx\Object\UIControlInterface;

/**
 * Panel class is the base class of Panel that embeded in EasyForm
 *
 * @package openbiz.bin.easy
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @since 1.2
 * @access public
 */
class Panel extends MetaIterator implements UIControlInterface
{

    public $formName;

    public function __construct(&$xmlArr, $childClassName, $parentObj = null)
    {
        parent::__construct($xmlArr, $childClassName, $parentObj);
        $this->formName = $parentObj->objectName;
    }

    protected function getFormObj()
    {
        return Openbizx::getObject($this->formName);
    }

    /**
     * Render the Panel and return array of rendering element (html text)
     *
     * @return string - html text
     */
    public function render()
    {
        $panel = array();

        /* @var $elem Element */
        foreach ($this->varValue as $elem) {
            if ($elem->canDisplayed()) {
                $panel[$elem->objectName]['element'] = $elem->render();
                $panel[$elem->objectName]['type'] = $elem->className;
                $panel[$elem->objectName]['width'] = $elem->width;
                $panel[$elem->objectName]['elementset'] = $elem->elementSet;
                $panel[$elem->objectName]['elementsetcode'] = $elem->elementSetCode;
                $panel[$elem->objectName]['tabset'] = $elem->tabSet;
                $panel[$elem->objectName]['tabsetcode'] = $elem->tabSetCode;
                $panel[$elem->objectName]['extra'] = $elem->extra;
                if (isset($elem->label) && $elem->label !== null)
                    $panel[$elem->objectName]['label'] = $elem->renderLabel();
                if (isset($elem->value) && $elem->value !== null)
                    $panel[$elem->objectName]['value'] = $elem->value;
                if (isset($elem->objectDescription) && $elem->objectDescription !== null)
                    $panel[$elem->objectName]['description'] = $elem->getDescription();
                if (isset($elem->required))
                    $panel[$elem->objectName]['required'] = $elem->required;
                if (isset($elem->columnStyle))
                    $panel[$elem->objectName]['colstyle'] = $elem->columnStyle;
            }
        }

        return $panel;
    }

    /**
     * Render record
     *
     * @param array $recArr
     * @return string - html text
     */
    public function renderRecord(&$recArr)
    {
        if ($recArr)
            $this->setRecordArr($recArr);
        return $this->render();
    }

    /**
     * Render table and return an array with 3 sub arraies (elems, data, ids)
     *
     * @param array $recSet
     * @return array
     */
    public function renderTable(&$recSet)
    {
        $table['elems'] = $this->render();

        $counter = 0;
        while (true) {
            $arr = $recSet[$counter];

            if (!$arr)
                break;

            foreach ($this->varValue as $elem)  // reset the elements
                $elem->reset();
            $this->setRecordArr($arr);
            $table['ids'][] = $arr['Id'];

            /* @var $elem Element */
            foreach ($this->varValue as $elem) {
                if ($elem->canDisplayed())
                    $tableRow[$elem->objectName] = $elem->render();
            }
            $table['data'][] = $tableRow;
            unset($tableRow);
            $counter++;
        }
        return $table;
    }

    /**
     * Set record array
     * TODO: change field=>value to element=>value
     *
     * @param array $recArr
     * @return void
     */
    public function setRecordArr(&$recArr)
    {
        if (!$recArr)
            return;

        foreach ($recArr as $key => $value) {
            $this->getFormObj()->activeRecord[$key] = $recArr[$key];
        }

        // reset elements first to avoid use stale data
        foreach ($this->varValue as $elem)
            $elem->reset();
        /* @var $elem Element */
        $this->getFormObj()->setFormInputs();
        foreach ($this->varValue as $elem) {
            //if (!$recArr)
            //    $elem->setValue("");
            if ( isset($recArr[$elem->fieldName]) ) {
                $elem->setValue($recArr[$elem->fieldName]);
            } else if ( isset($recArr[$elem->objectName]) ) {
                $elem->setValue($recArr[$elem->objectName]);
            }
        }
    }

    /**
     * Get element by field,
     *
     * @param <type> $fieldName
     * @todo change name to getElementByField() or Add new wrapping method
     * @return Element
     */
    public function getByField($fieldName)
    {
        /* @var $elem Element */
        $elems = $this->varValue;
        foreach ($elems as $elem) {
            if ($elem->fieldName == $fieldName && $elem->className != 'RowCheckbox') {
                return $elem;
            }
        }
    }

    public function hasFormElement()
    {
        foreach ($this->varValue as $elem) {
            if ($elem->className == 'FormElement') {
                return true;
            }
        }
        return false;
    }

}

?>


<?PHP
/**
 * Openbizx Framework
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin.easy.element
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: RichText.php 2553 2010-11-21 08:36:48Z mr_a_ton $
 */

namespace Openbizx\Easy\Element;

use Openbizx\Openbizx;
use Openbizx\Easy\Element\InputElement;

/**
 * RichText class is input element for render RichText editor
 *
 * @package openbiz.bin.easy.element
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @access public
 */
class RichText extends InputElement
{

    /**
     * Render, draw the element according to the mode
     *
     * @return string HTML text
     */
    public function render()
    {
        Openbizx::$app->getClientProxy()->includeRTEScripts();

        $elementName = $this->objectName;
        $elementNameAndContainer = $elementName."_container";
        $value = $this->getValue();
        $style = $this->getStyle();
        $width = $this->width ? $this->width : 600;
        $height = $this->height ? $this->height : 300;
        //$func = "onclick=\"editRichText('$elementName', $width, $height);\"";
        if(!strlen($value)>0) // fix suggested by smarques
            $value=" ";
        $sHTML = "
".$value."
\n";
        $sHTML .= "<input type='hidden' id='hdn$elementName' name='$elementName' value=\"".$value."\" />"."\n";
        //$sHTML .= "<textarea rows=2 cols=20 id='hdn$elementName' name='$elementName'>".$value."</textarea>\n";
        $sHTML .= "";
        return $sHTML;
    }

}

?>


<?PHP
/**
 * Openbizx Framework
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: TypeManager.php 2553 2010-11-21 08:36:48Z mr_a_ton $
 */

namespace Openbizx\Core;

use Openbizx\I18n\I18n;

/**
 * A class with help methods to format data to UI and unformat UI input to data.
 *
 * @package   openbiz.bin
 * @author    Rocky Swen <rocky@phpopenbiz.org>
 * @copyright Copyright (c) 2005-2009, Rocky Swen
 * @access    public
 */
class TypeManager
{
    /**
     * the current locale information, see {@link localeconv}
     * @var array
     */
    protected $_localeInfo;

    /**
     * Constructor of TypeManager, set locale with $localCode parameter
     *
     * @param string $localeCode
     * @return void
     **/
    public function __construct ($localeCode = "")
    {
        //try to set correct locale for current language as defined in app.inc section I18n
        $currentLanguage = I18n::getCurrentLangCode();
        $localeCode = $GLOBALS["local"][$currentLanguage];
        setlocale(LC_ALL, $localeCode);
        $this->_localeInfo = localeconv();
        if ($this->_localeInfo['frac_digits'] > 10) {
            $this->_localeInfo = null;
        }
    }

    /**
     * Convert Formatted String To Value
     *
     * @param string $type - field type
     * @param string $format - type format
     * @param string $formattedString - formatted string
     * @return mixed
     **/
    public function formattedStringToValue($type, $format, $formattedString)
    {
        if ($formattedString === null || $formattedString === "") {
            return null;
        }
        switch ($type)
        {
            case "Number": return $this->numberToValue($format, $formattedString);
            case "Text": return $this->textToValue($format, $formattedString);
            case "Date": return $this->dateToValue($format, $formattedString);
            case "Datetime": return $this->datetimeToValue($format, $formattedString);
            case "Currency": return $this->currencyToValue($format, $formattedString);
            case "Phone": return $this->phoneToValue($format, $formattedString);
            default: return $formattedString;
        }
    }

    /**
     * Convert Value To Formatted String
     *
     * @param string $type - field type
     * @param string $format - type format
     * @param string $value - value
     * @return string - formatted string
     **/
    public function valueToFormattedString($type, $format, $value)
    {
        switch ($type)
        {
            case "Number": return $this->valueToNumber($format, $value);
            case "Text": return $this->valueToText($format, $value);
            case "Date": return $this->valueToDate($format, $value);
            case "Datetime": return $this->valueToDatetime($format, $value);
            case "Currency": return $this->valueToCurrency($format, $value);
            case "Phone": return $this->valueToPhone($format, $value);
            default: return $value;
        }
    }

    /**
     * Format value to number
     *
     * @param string $format - type format
     * @param string $value - value
     * @return string formatted number
     */
    protected function valueToNumber($format, $value)
    {
        if ($format[0] == "%") {
            return sprintf($format, $value);
        }
        if (!$this->_localeInfo) {
            return $value;
        }
        $formattedNumber = $value;
        if ($format == "Int") {
            $formattedNumber = number_format($value, 0, $this->_localeInfo['decimal_point'], $this->_localeInfo['thousands_sep']);
        } elseif ($format == "Float") {
            $formattedNumber = number_format($value, $this->_localeInfo['frac_digits'], $this->_localeInfo['decimal_point'], $this->_localeInfo['thousands_sep']);
        }
        return $formattedNumber;
    }

    /**
     * Unformat a number to value
     *
     * @param string $format - type format
     * @param string $formattedValue - formatted string
     * @return mixed
     */
    protected function numberToValue($format, $formattedValue)
    {
        if ($formattedValue === false || $formattedValue === true) {
            return null;
        }
        if ($format[0] == "%") {
            return sscanf($formattedValue, $format);
        }
        if (!$this->_localeInfo) {
            return $formattedValue;
        }
        $tmp = str_replace($this->_localeInfo['thousands_sep'], null, $formattedValue);
        $tmp = str_replace($this->_localeInfo['decimal_point'], ".", $tmp);
        if ($format == "Int") {
            return (int) $tmp;
        }
        return $tmp;
    }

    /**
     * Format value to text
     *
     * @param string $format - type format
     * @param string $value - value
     * @return string formatted string
     */
    protected function valueToText($format, $value)
    {
        return $value;
    }

    /**
     * Unformat a text to value
     *
     * @param string $format - type format
     * @param string $formattedValue - formatted string
     * @return mixed
     */
    protected function textToValue($format, $formattedValue)
    {
        if ($formattedValue === false) {
            $formattedValue = "";
        }
        return $formattedValue;
    }

    /**
     * Format value to date
     *
     * @param string $format - type format
     * @param string $value - value
     * @return string - Empty string or formatted Time/Date
     */
    protected function valueToDate($format, $value)
    {
        // ISO format YYYY-MM-DD as input
        if ($value == "0000-00-00") {
            return "";
        }
        if (!$value) {
            return "";
        }
        if (strlen(trim($value)) < 1) {
            return "";
        }
        $tt = strtotime($value);
        if ($tt != - 1) {
            return strftime($format, strtotime($value));
        }
        return "";
    }

    /**
     * Unformat a date to value
     *
     * @param string $format - type format
     * @param string $formattedValue - formatted string
     * @return mixed $stdFormat - ISO format YYYY-MM-DD
     */
    protected function dateToValue($format, $formattedValue)
    {
        if (!$formattedValue) {
            return '';
        }
        $stdFormat = $this->convertDatetimeFormat($formattedValue, $format, '%Y-%m-%d');
        return $stdFormat;
    }

    /**
     * Format value to date time
     *
     * @param string $fmt - type format
     * @param string $value - value
     * @return string - formatted string
     */
    protected function valueToDatetime ($fmt, $value)
    {
        // ISO format YYYY-MM-DD HH:MM:SS as input
        if ($value == "0000-00-00 00:00:00") {
            return "";
        }
        if ($fmt == null) {
            $fmt = DATETIME_FORMAT;
        }
        return $this->valueToDate($fmt, $value);
    }

    /**
     * Unformat a datetime to value
     *
     * @param string $format - type format
     * @param string $formattedValue - formatted string
     * @return mix $stdFormat - ISO format YYYY-MM-DD HH:MM:SS
     */
    protected function datetimeToValue($format, $formattedValue)
    {
        if (!$formattedValue) {
            return '';
        }
        $stdFormat = $this->convertDatetimeFormat($formattedValue, $format, '%Y-%m-%d %H:%M:%S');
        return $stdFormat;
    }

    /**
     * Format value to currency
     *
     * @param string $format - type format
     * @param string $value - value
     * @return string - formatted string
     */
    protected function valueToCurrency($format, $value)
    {
        if (!$value) {
            return "";
        }
        if (!$this->_localeInfo) {
            return $value;
        }
        $fmtNum = number_format($value, $this->_localeInfo['frac_digits'], $this->_localeInfo['mon_decimal_point'], $this->_localeInfo['mon_thousands_sep']);
        return $this->_localeInfo["currency_symbol"] . $fmtNum;
    }

    /**
     * Unformat a currency to value
     *
     * @param string $format - type format
     * @param string $formattedValue - formatted string value
     * @return mixed - value
     */
    protected function currencyToValue($format, $formattedValue)
    {
        if (!$this->_localeInfo) {
            return $formattedValue;
        }
        $tmp = str_replace($this->_localeInfo["currency_symbol"], null, $formattedValue);
        $tmp = str_replace($this->_localeInfo['thousands_sep'], null, $tmp);
        return (float) $tmp;
    }

    /**
     * Format value to phone number
     *
     * @param string $fmt - type format
     * @param string $value - value
     * @return string - formatted string
     */
    protected function valueToPhone($mask, $value)
    {
        if (substr($value, 0, 1) == "*") { // if phone starts with "*", it's an international number, don't convert it
            return $value;
        }
        if (trim($value) == "") {
            return $value;
        }
        $maskLen = strlen($mask);
        $ph_len = strlen($value);
        $ph_fmt = $mask;
        $j = 0;
        for ($i = 0; $i < $maskLen; $i ++)
        {
            if ($mask[$i] == "#")
            {
                $ph_fmt[$i] = $value[$j];
                $j ++;
                if ($j == $ph_len) {
                    break;
                }
            }
        }
        return substr($ph_fmt, 0, $i + 1);
    }

    /**
     * Unformat a phone to value
     *
     * @param string $fmt - type format
     * @param string $formattedValue - formatted string
     * @return mixed
     */
    protected function phoneToValue($mask, $formattedValue)
    {
        if ($formattedValue[0] == "*") {
            return $formattedValue;
        }
        return ereg_replace("[^0-9]", null, $formattedValue);
    }

    /**
     * Convert a formatted datetime to another format
     *
     * @param $oldFormattedValue - old formated value
     * @param $oldFormat - old format of value
     * @param $newFormat - new format of value
     * @return string new formatted datetime value
     */
    public function convertDatetimeFormat($oldFormattedValue, $oldFormat, $newFormat)
    {
        if ($oldFormat == $newFormat) {
            return $oldFormattedValue;
        }
        $timeStamp = $this->_parseDate($oldFormat, $oldFormattedValue);
        return strftime($newFormat, $timeStamp);
    }

    /**
     * Parse formatted date to time value
     *
     * @param string $fmt type - format
     * @param string $fmtValue - formatted string
     * @return int $timestamp - vallue of time
     */
    private function _parseDate ($fmt, $fmtValue)
    {
        $y = 0;
        $m = 0;
        $d = 0;
        $hr = 0;
        $min = 0;
        $sec = 0;
        $a = preg_split("/\W+/", $fmtValue);
        preg_match_all("/%./", $fmt, $b);
        for ($i = 0; $i < count($a); ++ $i)
        {
            if (!$a[$i]) {
                continue;
            }
            switch ($b[0][$i])
            {
                case "%d": // the day of the month ( 00 .. 31 )
                case "%e": // the day of the month ( 0 .. 31 )
                    $d = intval($a[$i], 10);
                    break;
                case "%m": // month ( 01 .. 12 )
                    $m = intval($a[$i], 10);
                    break;
                case "%Y": // year including the century ( ex. 1979 )
                case "%y": // year without the century ( 00 .. 99 )
                    $y = intval($a[$i], 10);
                    if ($y < 100) {
                        $y += ($y > 29) ? 1900 : 2000;
                    }
                    break;
                case "%H": // hour ( 00 .. 23 )
                case "%I": // hour ( 01 .. 12 )
                case "%k": // hour ( 00 .. 23 )
                case "%l": // hour ( 01 .. 12 )
                    $hr = intval($a[$i], 10);
                    break;
                case "%P": // PM or AM
                case "%p": // pm or am
                    if ($a[$i] == 'pm' && $hr < 12) {
                        $hr += 12;
                    } else
                    if ($a[$i] == 'am' && $hr >= 12) {
                        $hr -= 12;
                    }
                    break;
                case "%M": // minute ( 00 .. 59 )
                    $min = intval($a[$i], 10);
                    break;
                case "%S": // second ( 00 .. 59 )
                    $sec = intval($a[$i], 10);
                    break;
                //default:
            }
        }
        $timeStamp = mktime($hr, $min, $sec, $m, $d, $y);
        return $timeStamp;
    }

    public function setLocaleInfo($localeInfo)
    {
        $this->_localeInfo = $localeInfo;
    }
}