<?php
/**
 * Annotation
 *
 * @package     Chrisguitarguy\Annotation
 * @copyright   Christopher Davis <http://christopherdavis.me>
 * @license     http://opensource.org/licenses/MIT MIT
 */

namespace Chrisguitarguy\Annotation;

/**
 * The default parser.
 *
 * @since   0.1
 * @author  Christopher Davis <http://christopherdavis.me>
 */
class Parser implements ParserInterface
{
    /**
     * The lexer.
     *
     * @since   0.1
     * @access  protected
     * @var     LexerInterface
     */
    protected $lexer;

    /**
     * Used in a few places when we parse "values"
     *
     * @since   0.1
     * @access  private
     * @var     string[]
     */
    protected $literals = array(
        Tokens::T_INT,
        Tokens::T_FLOAT,
        Tokens::T_STRING,
        Tokens::T_TRUE,
        Tokens::T_FALSE,
        Tokens::T_NULL,
        Tokens::T_OPEN_BRACE, // signals that we need to parse a dict
        Tokens::T_OPEN_BRACKET, // singles that we need to parse a list
    );

    /**
     * Construct. Set up the lexer.
     *
     * @since   0.1
     * @access  public
     * @param   LexerInterface $lexer
     * @return  void
     */
    public function __construct(LexerInterface $lexer=null)
    {
        $this->lexer = $lexer ?: new Lexer();
    }

    /**
     * {@inheritdoc}
     */
    public function parse($input)
    {
        $stream = $this->lexer->lex($input);

        $annotations = array();
        while ($stream->valid()) {
            if (!$stream->skipUntil(Tokens::T_AT)) {
                break;
            }

            if (!$stream->peek()->test(Tokens::T_IDENTIFIER)) {
                $stream->next(); // move along
                continue;
            }

            if (!$stream->peek(2)->test(Tokens::T_OPEN_PAREN)) {
                $stream->next(); // move along
                continue;
            }

            $annotations[] = $this->parseAnnotation($stream);
        }

        return $annotations;
    }

    protected function parseAnnotation(TokenStreamInterface $stream)
    {
        // disgard the @ sign
        $stream->expect(Tokens::T_AT);
        $stream->next();

        // get the annotation name
        $stream->expect(Tokens::T_IDENTIFIER);
        $annotation_name = $stream->current()->value;

        // next we should expect an open parenthesis
        $stream->next();
        $stream->expect(Tokens::T_OPEN_PAREN);

        list($positionalArgs, $namedArgs) = $this->parseArguments($stream);

        $stream->expect(Tokens::T_CLOSE_PAREN);
        $stream->next();

        return array($annotation_name, $positionalArgs, $namedArgs);
    }

    protected function parseArguments(TokenStreamInterface $stream)
    {
        // discard the opening paren
        $stream->next();

        $positionalArguments = $this->parsePositionalArguments($stream);
        $namedArguments = $this->parseNamedArguments($stream);

        return array($positionalArguments, $namedArguments);
    }

    protected function parsePositionalArguments(TokenStreamInterface $stream)
    {
        $arguments = array();
        while ($stream->valid()) {
            $this->consumeWhitespace($stream);

            // we want to parse until we reach a closing paren or an identifier
            // An identifier signals that we've reached keyword arguments
            if ($stream->current()->test(array(Tokens::T_CLOSE_PAREN, Tokens::T_IDENTIFIER))) {
                break;
            }

            $arguments[] = $this->parseValue($stream);

            $this->consumeWhitespace($stream);

            $stream->expect(array(Tokens::T_COMMA, Tokens::T_CLOSE_PAREN));

            if ($stream->current()->test(Tokens::T_COMMA)) {
                $stream->next();
            }
        }

        return $arguments;
    }

    protected function parseNamedArguments(TokenStreamInterface $stream)
    {
        $arguments = array();
        while ($stream->valid()) {
            $this->consumeWhitespace($stream);

            // when we reach the closing paren, bail
            if ($stream->current()->test(Tokens::T_CLOSE_PAREN)) {
                break;
            }

            list($identifier, $value) = $this->parseNamedArgument($stream);
            $arguments[$identifier] = $value;

            $this->consumeWhitespace($stream);

            $stream->expect(array(Tokens::T_COMMA, Tokens::T_CLOSE_PAREN));

            // if we did get a comma, move to the next
            if ($stream->current()->test(Tokens::T_COMMA)) {
                $stream->next();
            }
        }

        return $arguments;
    }

    protected function parseNamedArgument(TokenStreamInterface $stream)
    {
        $stream->expect(Tokens::T_IDENTIFIER);
        $identifier = $stream->current()->value;
        $stream->next();

        $this->consumeWhitespace($stream);

        // we expect an equal since, look for it then discard it
        $stream->expect(Tokens::T_EQUALS);
        $stream->next();

        $this->consumeWhitespace($stream);

        $value = $this->parseValue($stream);

        return array($identifier, $value);
    }

    protected function consumeWhitespace(TokenStreamInterface $stream)
    {
        while($stream->valid()) {
            if (!$stream->current()->test(Tokens::T_WHITESPACE)) {
                break;
            }

            $stream->next();
        }
    }

    protected function parseValue(TokenStream $stream)
    {
        // if we're here we expect a literal
        $stream->expect($this->literals);

        $token = $stream->current();

        switch ($token->name) {
            case Tokens::T_INT:
                $value = intval($token->value);
                break;
            case Tokens::T_FLOAT:
                $value = floatval($token->value);
                break;
            case Tokens::T_STRING:
                $value = $this->cleanString($token->value);
                break;
            case Tokens::T_OPEN_BRACKET:
                $value = $this->parseList($stream);
                break;
            case Tokens::T_OPEN_BRACE:
                $value = $this->parseDict($stream);
                break;
            case Tokens::T_TRUE:
                $value = true;
                break;
            case Tokens::T_FALSE:
                $value = false;
                break;
            case Tokens::T_NULL:
            default:
                $value = null;
                break;
        }

        $stream->next();

        return $value;
    }

    protected function parseList(TokenStream $stream)
    {
        // expect and discard the open brace
        $stream->expect(Tokens::T_OPEN_BRACKET);
        $stream->next();

        $values = array();
        while ($stream->valid()) {
            $this->consumeWhitespace($stream);

            if ($stream->current()->test(Tokens::T_CLOSE_BRACKET)) {
                break;
            }

            $values[] = $this->parseValue($stream);

            $this->consumeWhitespace($stream);

            // we expect a comma or the close of the opening bracket
            $stream->expect(array(
                Tokens::T_COMMA,
                Tokens::T_CLOSE_BRACKET,
            ));

            // discard the comma if we have it
            if ($stream->current()->test(Tokens::T_COMMA)) {
                $stream->next();
            }
        }

        // we expect a closing bracket, look for it and discard it
        $stream->expect(Tokens::T_CLOSE_BRACKET);

        return $values;
    }

    protected function parseDict(TokenStream $stream)
    {
        // expect and discard the openig brace
        $stream->expect(Tokens::T_OPEN_BRACE);
        $stream->next();

        $values = array();
        while ($stream->valid()) {
            $this->consumeWhitespace($stream);

            if ($stream->current()->test(Tokens::T_CLOSE_BRACE)) {
                break;
            }

            $key = $this->parseDictKey($stream);

            $this->consumeWhitespace($stream);

            $stream->expect(Tokens::T_COLON);
            $stream->next();

            $this->consumeWhitespace($stream);

            $values[$key] = $this->parseValue($stream);

            $this->consumeWhitespace($stream);

            $stream->expect(array(
                Tokens::T_COMMA,
                Tokens::T_CLOSE_BRACE,
            ));

            if ($stream->current()->test(Tokens::T_COMMA)) {
                $stream->next();
            }
        }

        $stream->expect(Tokens::T_CLOSE_BRACE);

        return $values;
    }

    protected function parseDictKey(TokenStream $stream)
    {
        $stream->expect(array(
            Tokens::T_IDENTIFIER,
            Tokens::T_STRING,
        ));

        $token = $stream->current();
        switch ($token->name) {
            case Tokens::T_STRING:
                $key = $this->cleanString($token->value);
                break;
            case Tokens::T_IDENTIFIER:
            default:
                $key = $token->value;
                break;
        }

        $stream->next();

        return $key;
    }

    protected function cleanString($str)
    {
        $stripped = substr($str, 1, strlen($str) - 2);
        return str_replace(array("\\'", '\\"'), array("'", '"'), $stripped);
    }
}


<?php

namespace Limber\Router;

class Route
{
    /**
     * The full URI.
     *
     * @var string
     */
    protected $uri;

    /**
     * Respond to HTTP methods.
     *
     * @var array<string>
     */
    protected $methods = [];

    /**
     * Route action
     *
     * @var string|callable
     */
    protected $action;

    /**
     * Request scheme (http or https)
     *
     * @var array<string>
     */
    protected $schemes = [];

    /**
     * Request hostname
     *
     * @var array<string>
     */
    protected $hostnames = [];

    /**
     * Controller namespace prefix
     *
     * @var string
     */
    protected $namespace;

    /**
     * Request prefix
     *
     * @var string
     */
    protected $prefix;

    /**
     * Route middlware to apply.
     *
     * @var array
     */
    protected $middleware = [];

    /**
     * Pattern parts
     *
     * @var array<string>
     */
    protected $patternParts = [];

    /**
     * Named URI params in route eg: "id" in books/{id}/authors
     *
     * @var array<string>
     */
    private $namedPathParameters = [];

    /**
     * Route constructor.
     *
     * @param string|array $methods
     * @param string $uri
     * @param string|callable $action
     * @param array $config Additional config data (usually passed in from group settings)
     *
     */
    public function __construct($methods, string $uri, $action, array $config = [])
    {
        // Required bits
        $this->methods = array_map('strtoupper', is_string($methods) ? [$methods] : $methods);
        $this->action = $action;
        $this->uri = $this->stripLeadingAndTrailingSlash($uri);

        // Optional
        $this->setSchemes($config['scheme'] ?? []);
        $this->setHostnames($config['hostname'] ?? []);
        $this->setMiddleware($config['middleware'] ?? []);
        $this->setPrefix($config['prefix'] ?? '');
        $this->setNamespace($config['namespace'] ?? '');

        foreach( explode("/", $this->getUri()) as $part ){

            if( preg_match('/{([a-z0-9_]+)(?:\:([a-z0-9_]+))?}/i', $part, $match) ){

                if( in_array($match[1], $this->namedPathParameters) ){
                    throw new \Exception("Path parameter \"{$match[1]}\" already defined for route {$match[0]}");
                }

                // Predefined pattern
                if( isset($match[2]) ){

                    if( ($part = Router::getPattern($match[2])) === null ){
                        throw new \Exception("Router pattern not found: {$match[2]}");
                    }
                }

                // Match anything
                else {

                    $part = '[^\/]+';
                }

                $part = "({$part})";

                // Save the named path param
                $this->namedPathParameters[] = $match[1];
            }

            $this->patternParts[] = $part;
        }
    }

    /**
     *
     * SETters
     */

    /**
     * @param string|array $schemes
     * @return Route
     */
    public function setSchemes($schemes): Route
    {
        if( !is_array($schemes) ){
            $schemes = [$schemes];
        }

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

    /**
     * @param string|array $hostnames
     * @return Route
     */
    public function setHostnames($hostnames): Route
    {
        if( !is_array($hostnames) ){
            $hostnames = [$hostnames];
        }

        $this->hostnames = $hostnames;

        return $this;
    }

    /**
     * @param string $prefix
     * @return Route
     */
    public function setPrefix(string $prefix): Route
    {
        $this->prefix = $this->stripLeadingAndTrailingSlash($prefix);

        return $this;
    }

    /**
     * Apply middleware to this route
     *
     * @param string|array $middleware
     * @return Route
     */
    public function setMiddleware($middleware): Route
    {
        if( !is_array($middleware) ){
            $middleware = [$middleware];
        }

        $this->middleware = array_merge($this->middleware, $middleware);

        return $this;
    }

    /**
     * Set the controller namespace.
     *
     * @param string $namespace
     * @return Route
     */
    public function setNamespace(string $namespace): Route
    {
        $this->namespace = $namespace;
        return $this;
    }

    /**
     *
     * GETters
     *
     */

     /**
      * Get the full URI.
      *
      * @return string
      */
     public function getUri(): string
     {
         if( $this->prefix ){
             return "{$this->prefix}/{$this->uri}";
         }

         return $this->uri;
     }

    /**
     * Get all schemes this route responds to.
     *
     * @return array
     */
    public function getSchemes(): array
    {
        return $this->schemes;
    }

    /**
     * Get all hostnames this route responds to.
     *
     * @return array
     */
    public function getHostnames(): array
    {
        return $this->hostnames;
    }

    /**
     * Get all methods this route respondes to.
     *
     * @return array<string>
     */
    public function getMethods(): array
    {
        return $this->methods;
    }

    /**
     * Get route action.
     *
     * @return string|callable
     */
    public function getAction()
    {
        if( is_string($this->action) &&
            $this->namespace ){
            return trim($this->namespace, '\\') . '\\' . $this->action;
        }

        return $this->action;
    }

    /**
     * Get the URI prefix.
     *
     * @return string
     */
    public function getPrefix(): ?string
    {
        return $this->prefix;
    }

    /**
     * Get all middleware this route should apply.
     *
     * @return array<string>
     */
    public function getMiddleware(): array
    {
        return $this->middleware;
    }

    /**
     * Get namespace of route
     *
     * @return string
     */
    public function getNamespace(): ?string
    {
        return $this->namespace;
    }

    /**
     * Get the regex pattern used to match this route.
     *
     * @return array<string>
     */
    public function getPatternParts(): array
    {
        return $this->patternParts;
    }

    /**
     * Extract the path parameters for the given URI.
     *
     * Makes a key => value pair of path part names and their value.
     *
     * Eg.
     *
     * The route "books/{id}" with an actual URI of "books/1234"
     * will return:
     *
     * [
     *      "id" => "1234",
     * ]
     *
     * These named path params are used during Dependency Injection resolution
     * in the Kernel to pass off to the matched method parameter.
     *
     * @param string $path
     * @return array<string, string>
     */
    public function getPathParams(string $path): array
    {
        $pathParams = [];

        // Build out the regex
        $pattern = implode("\/", $this->getPatternParts());

        if( preg_match("/^{$pattern}$/", $path, $parts) ){

            // Grab all but the first match, because that will always be the full string.
            foreach( array_slice($parts, 1, count($parts) - 1) as $i => $param ) {
                $pathParams[$this->namedPathParameters[$i]] = $param;
            }

        }

        return $pathParams;
    }

    /**
     *
     * MATCHing
     *
     */

    /**
     * Does the given scheme match this route's scheme?
     *
     * @param string $scheme
     * @return bool
     */
    public function matchScheme($scheme): bool
    {
        if( empty($this->schemes) ){
            return true;
        }

        return array_search(strtolower($scheme), array_map('strtolower', $this->schemes)) !== false;
    }

    /**
     * Does the given hostname match the route's hostname?
     *
     * @param string $hostnames
     * @return bool
     */
    public function matchHostname(string $hostnames): bool
    {
        if( empty($this->hostnames) ){
            return true;
        }

        return array_search(strtolower($hostnames), array_map('strtolower', $this->hostnames)) !== false;
    }

    /**
     * Does the given method match the route's set of methods?
     *
     * @param string $method
     * @return bool
     */
    public function matchMethod(string $method): bool
    {
        return in_array(strtoupper($method), $this->methods);
    }

    /**
     * Does the given URI match the route's URI?
     *
     * @param string $uri
     * @return bool
     */
    public function matchUri(string $uri): bool
    {
        $pattern = implode("\/", $this->patternParts);
        return preg_match("/^{$pattern}$/i", $this->stripLeadingAndTrailingSlash($uri)) != false;
    }

    /**
     * Normalize URIs by stripping off leading and trailing slashes.
     *
     * @param string $uri
     * @return string
     */
    private function stripLeadingAndTrailingSlash(string $uri): string
    {
        return trim($uri, '/');
    }
}


<?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
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: BizDataTree.php 2585 2010-11-23 18:58:17Z jixian2003 $
 */

namespace Openbizx\Data;

use Openbizx\Data\BizDataObj;
use Openbizx\Data\NodeRecord;

/**
 * BizDataTree class provide query for tree structured records
 *
 * @package openbiz.bin.data
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @access public
 */
class BizDataTree extends BizDataObj {

    protected $rootNodes;

    /**
     * Deep of tree
     * @var int
     */
    protected $depth;

    /**
     * Global search rule
     * @var string
     */
    protected $globalSearchRule;

    /**
     * Fetch records in tree structure
     *
     * @return <type>
     */
    public function fetchTree($rootSearchRule, $depth, $globalSearchRule = "") {
        $this->depth = $depth;
        $this->globalSearchRule = $globalSearchRule;

        // query on given search rule
        $searchRule = "(" . $rootSearchRule . ")";
        if ($globalSearchRule != "")
            $searchRule .= " AND (" . $globalSearchRule . ")";
        $recordList = $this->directFetch($searchRule);
        if (!$recordList) {
            $this->rootNodes = array();
            return;
        }
        foreach ($recordList as $rec) {
            $this->rootNodes[] = new NodeRecord($rec);
        }
        if ($this->depth <= 1)
            return $this->rootNodes;
        if (is_array($this->rootNodes)) {
            foreach ($this->rootNodes as $node) {
                $this->_getChildrenNodes($node, 1);
            }
        }
        return $this->rootNodes;
    }

    /**
     * Fetch node path
     *
     * @param string $nodeSearchRule
     * @param array $pathArray
     * @return <type>
     */
    public function fetchNodePath($nodeSearchRule, &$pathArray) {
        $recordList = $this->directFetch($nodeSearchRule);
        if (count($recordList) >= 1) {

            if ($recordList[0]['PId'] != '0') {
                $searchRule = "[Id]='" . $recordList[0]['PId'] . "'";
                $this->fetchNodePath($searchRule, $pathArray);
            }
            $nodes = new \NodeRecord($recordList[0]);
            array_push($pathArray, $nodes);
            return $pathArray;
        }
    }

    /**
     * List all children records of a given record
     *
     * @return void
     */
    private function _getChildrenNodes(&$node, $depth) {
        $pid = $node->recordId;

        $searchRule = "[PId]='$pid'";
        if ($this->globalSearchRule != "")
            $searchRule .= " AND " . $this->globalSearchRule;
        $recordList = $this->directFetch($searchRule);

        foreach ($recordList as $rec) {
            $node->childNodes[] = new NodeRecord($rec);
        }

        // reach leave node
        if ($node->childNodes == null) {
            return;
        }

        $depth++;
        // reach given depth
        if ($depth >= $this->depth) {
            return;
        } else {
            foreach ($node->childNodes as $node_c) {
                $this->_getChildrenNodes($node_c, $depth);
            }
        }
    }

}


<?php

/**
 * Nameless framework
 *
 * @package Nameless framework
 * @author  Corpsee <poisoncorpsee@gmail.com>
 * @license https://github.com/corpsee/nameless-source/blob/master/LICENSE
 * @link    https://github.com/corpsee/nameless-source
 */

namespace Nameless\Core;

use Psr\Log\LogLevel;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request as BaseRequest;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\EventListener\ExceptionListener;
use Symfony\Component\Routing\Route;
use Symfony\Component\HttpKernel\Event\PostResponseEvent;
use Symfony\Component\Debug\ErrorHandler;
use Symfony\Component\Debug\ExceptionHandler;
use Symfony\Component\HttpKernel\EventListener\ResponseListener;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\EventDispatcher\EventDispatcher;

/**
 * Application class
 *
 * @author Corpsee <poisoncorpsee@gmail.com>
 */
class Application extends HttpKernel
{
    /**
     * @var array
     */
    protected $modules = [];

    /**
     * @var Container
     */
    protected $container;

    public function __construct()
    {
        $this->container = new Container();

        $this->initConfigs();

        $this->container->init($this);

        $this->initRoutes();
        $this->initModules();
        $this->initEnvironment();
        $this->initTimezone();
        $this->initUnicode();

        $this->container['kernel'] = $this;

        parent::__construct($this->container['dispatcher'], $this->container['resolver']);
    }

    /**
     * @return array
     */
    protected function getConfigsFromFiles()
    {
        $app_config = [];
        if (file_exists(CONFIG_PATH . 'config.php')) {
            $app_config = include_once APPLICATION_PATH . 'configs/config.php';
        }
        $config = include_once dirname(__DIR__) . '/Core/configs/config.php';
        $config = array_replace_recursive($config, $app_config);

        if (!isset($config['modules'])) {
            return $config;
        }
        foreach ($config['modules'] as $module) {
            $module_config = include_once(dirname(__DIR__) . '/Modules/' . ucfirst($module) . '/configs/config.php');
            $config = array_replace_recursive($module_config, $config);
        }

        return $config;
    }

    protected function initConfigs()
    {
        $config = $this->getConfigsFromFiles();
        foreach ($config as $option => $value) {
            $this->container[$option] = $value;
        }
    }

    protected function initRoutes()
    {
        foreach ($this->container['routes'] as $route_name => $route_value) {
            $defaults = isset($route_value['defaults'])
                ? $route_value['defaults']
                : [];
            $requirements = isset($route_value['requirements'])
                ? $route_value['requirements']
                : [];
            $options = isset($route_value['options'])
                ? $route_value['options']
                : [];

            /** @var RouteCollection $collection */
            $collection = $this->container['routes-collection'];
            $collection->add($route_name, new Route($route_value['path'], $defaults, $requirements, $options));
        }
    }

    protected function initModules()
    {
        if (isset($this->container['modules'])) {
            foreach ($this->container['modules'] as $module) {
                $module_provider_name = 'Nameless\\Modules\\' . $module . '\\ModuleProvider';
                $module_provider = new $module_provider_name($this->container);

                if (!$module_provider instanceof ModuleProvider) {
                    throw new \RuntimeException($module_provider_name . ' must be instance of ModuleProvider');
                }

                $this->modules[$module] = $module_provider;
                $module_provider->register($this->container);
            }
        }
    }

    /**
     * @return ModuleProvider[]
     */
    public function getModuleProviders()
    {
        return $this->modules;
    }

    /**
     * @param string $module
     *
     * @return ModuleProvider
     */
    public function getModuleProvider($module)
    {
        return $this->modules[$module];
    }

    protected function initTimezone()
    {
        if (isset($this->container['timezone'])) {
            date_default_timezone_set($this->container['timezone']);
        }
    }

    /**
     * @throws \RuntimeException
     */
    protected function initUnicode()
    {
        /** @var EventDispatcher $dispatcher */
        $dispatcher = $this->container['dispatcher'];
        $dispatcher->addSubscriber(new ResponseListener('UTF-8'));

        if (!extension_loaded('mbstring')) {
            throw new \RuntimeException('mbstring extension must be enabled!');
        }
        mb_internal_encoding('UTF-8');
    }

    protected function initEnvironment()
    {
        error_reporting(-1);

        if ($this->container['environment'] === 'debug') {
            ExceptionHandler::register();
        } else {
            if ($this->container['environment'] === 'production') {
                error_reporting(E_ALL ^ (E_STRICT | E_NOTICE | E_DEPRECATED));
                ini_set('display_errors', 0);
            }
            $listener = new ExceptionListener($this->container['error_controller']);
            $this->container['dispatcher']->addSubscriber($listener);
        };

        $handler = ErrorHandler::register(null, true);
        $handler->setDefaultLogger($this->container['logger.logger']);
    }

    /**
     * @param BaseRequest $request
     * @param integer $type
     * @param boolean $catch
     *
     * @return Response
     */
    public function handle(BaseRequest $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
    {
        $this->container['request'] = $request;
        return parent::handle($request, $type, $catch);
    }

    /**
     * @param string $route
     * @param array $attributes
     * @param array $query
     *
     * @return Response
     */
    public function forward($route, array $attributes = [], array $query = [])
    {
        $defaults = $this->container['routes-collection']->get($route)->getDefaults();
        $attributes['_controller'] = $defaults['_controller'];
        $attributes['_route']      = $route;

        $subRequest = $this->container['request']->duplicate($query, null, $attributes);
        return $this->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
    }

    /**
     * @param Request $request
     */
    public function run(Request $request = null)
    {
        if (is_null($request)) {
            $request = Request::createFromGlobals();
        }
        $response = $this->handle($request);
        $response->send();
        $this->terminate($request, $response);
    }

    /**
     * @param BaseRequest $request
     * @param Response $response
     */
    public function terminate(BaseRequest $request, Response $response)
    {
        $this->dispatcher->dispatch(KernelEvents::TERMINATE, new PostResponseEvent($this, $request, $response));
    }

    /**
     * @return Container
     */
    public function getContainer()
    {
        return $this->container;
    }
}


<?php

/**
 * MIT License
 * For full license information, please view the LICENSE file that was distributed with this source code.
 */

namespace Spryker\Zed\SalesOrderThresholdDataImport\Business\Model\DataImportStep;

use Generated\Shared\Transfer\CurrencyTransfer;
use Generated\Shared\Transfer\SalesOrderThresholdTransfer;
use Generated\Shared\Transfer\SalesOrderThresholdTypeTransfer;
use Generated\Shared\Transfer\SalesOrderThresholdValueTransfer;
use Generated\Shared\Transfer\StoreTransfer;
use Spryker\Zed\DataImport\Business\Exception\EntityNotFoundException;
use Spryker\Zed\DataImport\Business\Model\DataImportStep\DataImportStepInterface;
use Spryker\Zed\DataImport\Business\Model\DataSet\DataSetInterface;
use Spryker\Zed\SalesOrderThresholdDataImport\Business\Model\DataSet\SalesOrderThresholdDataSetInterface;
use Spryker\Zed\SalesOrderThresholdDataImport\Dependency\Facade\SalesOrderThresholdDataImportToCurrencyFacadeInterface;
use Spryker\Zed\SalesOrderThresholdDataImport\Dependency\Facade\SalesOrderThresholdDataImportToSalesOrderThresholdFacadeInterface;
use Spryker\Zed\SalesOrderThresholdDataImport\Dependency\Facade\SalesOrderThresholdDataImportToStoreFacadeInterface;
use Throwable;

class SalesOrderThresholdWriterStep implements DataImportStepInterface
{
    /**
     * @var \Spryker\Zed\SalesOrderThresholdDataImport\Dependency\Facade\SalesOrderThresholdDataImportToSalesOrderThresholdFacadeInterface
     */
    protected $salesOrderThresholdFacade;

    /**
     * @var \Spryker\Zed\SalesOrderThresholdDataImport\Dependency\Facade\SalesOrderThresholdDataImportToStoreFacadeInterface
     */
    protected $storeFacade;

    /**
     * @var \Spryker\Zed\SalesOrderThresholdDataImport\Dependency\Facade\SalesOrderThresholdDataImportToCurrencyFacadeInterface
     */
    protected $currencyFacade;

    /**
     * @var \Generated\Shared\Transfer\StoreTransfer[] Keys are store names.
     */
    protected $storesHeap = [];

    /**
     * @var \Generated\Shared\Transfer\CurrencyTransfer[] Keys are currency codes.
     */
    protected $currenciesHeap = [];

    /**
     * @param \Spryker\Zed\SalesOrderThresholdDataImport\Dependency\Facade\SalesOrderThresholdDataImportToSalesOrderThresholdFacadeInterface $salesOrderThresholdFacade
     * @param \Spryker\Zed\SalesOrderThresholdDataImport\Dependency\Facade\SalesOrderThresholdDataImportToStoreFacadeInterface $storeFacade
     * @param \Spryker\Zed\SalesOrderThresholdDataImport\Dependency\Facade\SalesOrderThresholdDataImportToCurrencyFacadeInterface $currencyFacade
     */
    public function __construct(
        SalesOrderThresholdDataImportToSalesOrderThresholdFacadeInterface $salesOrderThresholdFacade,
        SalesOrderThresholdDataImportToStoreFacadeInterface $storeFacade,
        SalesOrderThresholdDataImportToCurrencyFacadeInterface $currencyFacade
    ) {
        $this->salesOrderThresholdFacade = $salesOrderThresholdFacade;
        $this->storeFacade = $storeFacade;
        $this->currencyFacade = $currencyFacade;
    }

    /**
     * @param \Spryker\Zed\DataImport\Business\Model\DataSet\DataSetInterface $dataSet
     *
     * @return void
     */
    public function execute(DataSetInterface $dataSet): void
    {
        $storeTransfer = $this->getStoreByName($dataSet[SalesOrderThresholdDataSetInterface::COLUMN_STORE]);
        $currencyTransfer = $this->getCurrencyByCode($dataSet[SalesOrderThresholdDataSetInterface::COLUMN_CURRENCY]);

        if ($dataSet[SalesOrderThresholdDataSetInterface::COLUMN_SALES_ORDER_THRESHOLD_TYPE_KEY] && $dataSet[SalesOrderThresholdDataSetInterface::COLUMN_THRESHOLD]) {
            $salesOrderThresholdTransfer = $this->createSalesOrderThresholdTransfer(
                $dataSet[SalesOrderThresholdDataSetInterface::COLUMN_SALES_ORDER_THRESHOLD_TYPE_KEY],
                $storeTransfer,
                $currencyTransfer,
                (int)$dataSet[SalesOrderThresholdDataSetInterface::COLUMN_THRESHOLD],
                (int)$dataSet[SalesOrderThresholdDataSetInterface::COLUMN_FEE],
                $dataSet[SalesOrderThresholdDataSetInterface::COLUMN_MESSAGE_GLOSSARY_KEY]
            );

            $this->salesOrderThresholdFacade->saveSalesOrderThreshold($salesOrderThresholdTransfer);
        }
    }

    /**
     * @param string $salesOrderThresholdTypeKey
     * @param \Generated\Shared\Transfer\StoreTransfer $storeTransfer
     * @param \Generated\Shared\Transfer\CurrencyTransfer $currencyTransfer
     * @param int $thresholdValue
     * @param int|null $fee
     * @param string|null $glossaryKey
     *
     * @return \Generated\Shared\Transfer\SalesOrderThresholdTransfer
     */
    protected function createSalesOrderThresholdTransfer(
        string $salesOrderThresholdTypeKey,
        StoreTransfer $storeTransfer,
        CurrencyTransfer $currencyTransfer,
        int $thresholdValue,
        ?int $fee = null,
        ?string $glossaryKey = null
    ): SalesOrderThresholdTransfer {
        return (new SalesOrderThresholdTransfer())
            ->setStore($storeTransfer)
            ->setCurrency($currencyTransfer)
            ->setSalesOrderThresholdValue(
                (new SalesOrderThresholdValueTransfer())
                    ->setThreshold($thresholdValue)
                    ->setFee($fee)
                    ->setMessageGlossaryKey($glossaryKey)
                    ->setSalesOrderThresholdType(
                        (new SalesOrderThresholdTypeTransfer())
                            ->setKey($salesOrderThresholdTypeKey)
                    )
            );
    }

    /**
     * @param string $storeName
     *
     * @throws \Pyz\Zed\DataImport\Business\Exception\EntityNotFoundException
     *
     * @return \Generated\Shared\Transfer\StoreTransfer
     */
    protected function getStoreByName(string $storeName): StoreTransfer
    {
        if (!isset($this->storesHeap[$storeName])) {
            try {
                $storeTransfer = $this->storeFacade->getStoreByName($storeName);

                $this->storesHeap[$storeName] = $storeTransfer;
            } catch (Throwable $t) {
                throw new EntityNotFoundException(sprintf('Store not found: %s', $storeName));
            }
        }

        return $this->storesHeap[$storeName];
    }

    /**
     * @param string $isoCode
     *
     * @throws \Pyz\Zed\DataImport\Business\Exception\EntityNotFoundException
     *
     * @return \Generated\Shared\Transfer\CurrencyTransfer
     */
    protected function getCurrencyByCode(string $isoCode): CurrencyTransfer
    {
        if (!isset($this->currenciesHeap[$isoCode])) {
            try {
                $currencyTransfer = $this->currencyFacade->fromIsoCode($isoCode);

                $this->currenciesHeap[$isoCode] = $currencyTransfer;
            } catch (Throwable $throwable) {
                throw new EntityNotFoundException(sprintf('Currency not found: %s', $isoCode));
            }
        }

        return $this->currenciesHeap[$isoCode];
    }
}


<?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: ioService.php 2553 2010-11-21 08:36:48Z mr_a_ton $
 */

namespace Openbizx\Service;

/**
 * ioService class is the plug-in service of handling file import/export
 *
 * @package   openbiz.bin.service
 * @author    Rocky Swen
 * @copyright Copyright (c) 2005-2009, Rocky Swen
 * @access    public
 */
class ioService
{

    /**
     * Initialize ioService with xml array metadata
     *
     * @param array $xmlArr
     * @return void
     */
    public function __construct(&$xmlArr)
    {

    }

    /**
     * Export to XML format (print to browser)
     *
     * @param string $objName
     * @return void
     */
    public function exportXML($objName)
    {
        // get the current UI bizobj
        /* @var $bizForm EasyForm */
        $bizForm = Openbizx::getObject($objName);    // get the existing bizform object
        $bizObj = $bizForm->getDataObj();

        $recList = array();
        $bizObj->fetchRecords("", $recList, -1, -1, false);

        $xmlString = "<?xml version='1.0' standalone='yes'?>\n";
        $xmlString .= "<BizDataObj Name=\"" . $bizObj->objectName . "\">\n";
        foreach ($recList as $rec) {
            $xmlRecord = "\t<Record>\n";
            foreach ($rec as $fld => $val) {
                $xmlRecord .= "\t\t<Field Name=\"$fld\" Value=\"$val\" />\n";
            }
            $xmlRecord .= "\t</Record>\n";
            $xmlString .= $xmlRecord;
        }
        $xmlString .= "</BizDataObj>";

        // output variables
        $name = str_replace(".", "_", $bizObj->objectName) . ".xml";
        $size = strlen($xmlString);
        $type = "text/plain";

        ob_clean();

        header("Cache-Control: "); // leave blank to avoid IE errors
        header("Pragma: "); // leave blank to avoid IE errors
        header("Content-Disposition: attachment; filename=\"$name\"");
        header("Content-length: $size");
        header("Content-type: $type");

        echo $xmlString;

        exit;
    }

    /**
     * Import from XML file, the file read from client (uploaded by user)
     *
     * @param string $objName
     * @return void
     */
    public function importXML($objName)
    {
        // read in file from $_FILE
        // read in file data and attributes
        foreach ($_FILES as $file) {
            $error = $file['error'];
            if ($error != 0) {
                $this->reportError($error);
                return;
            }

            $tmpName = $file['tmp_name'];
            $xml = simplexml_load_file($tmpName);
            if (!$xml) {
                $errorMsg = "Invalid input data format, could not create xml object.";
                Openbizx::$app->getClientProxy()->showErrorMessage($errorMsg);
                return;
            }
            // only read the first one
            break;
        }

        // get the current UI bizobj
        /* @var $form EasyForm */
        $form = Openbizx::getObject($objName);    // get the existing bizform object
        /* @var $parentForm EasyForm */
        $parentForm = Openbizx::getObject($form->GetParentForm());
        /* @var $dataObj BizDataObj */
        $dataObj = $parentForm->getDataObj();

        //$oldCacheMode = $dataObj->GetCacheMode();
        //$dataObj->SetCacheMode(0);    // turn off cache mode, not affect the current cache
        // check if BizDataObj name matches
        $dataObjName = $xml['Name'];
        if ($dataObj->objectName != $$dataObjName) {
            $errorMsg = "Invalid input data. Input data object is not same as the current data object.";
            Openbizx::$app->getClientProxy()->showErrorMessage($errorMsg);
            return;
        }

        // read records
        foreach ($xml->Record as $record) {
            // insert record
            // todo: check if there's same user keys in the table
            $recArray = null;
            $recArray = $dataObj->newRecord();
            foreach ($record as $field) {
                $value = "";
                foreach ($field->attributes() as $attributeName => $attributeValue) {
                    if ($attributeName == 'Name') {
                        $name = $attributeValue . "";
                    } else if ($attributeName == 'Value') {
                        $value = $attributeValue . "";
                    }
                }
                if ($name != "Id") {
                    $recArray[$name] = $value;
                }
            }

            if (!$dataObj->insertRecord($recArray)) {
                $errorMsg = $dataObj->getErrorMessage();
                Openbizx::$app->getClientProxy()->showErrorMessage($errorMsg);
                return;
            }
        }
        $form->setFormState(1); // indicate the import is done
    }

    /**
     * Report Error
     *
     * @param number $error Error code
     * @return void
     */
    protected function reportError($error)
    {
        if ($error == 1) {
            $errorStr = "The uploaded file exceeds the upload_max_filesize directive in php.ini";
        } else if ($error == 2) {
            $errorStr = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
        } else if ($error == 3) {
            $errorStr = "The uploaded file was only partially uploaded";
        } else if ($error == 4) {
            $errorStr = "No file was uploaded";
        } else if ($error == 6) {
            $errorStr = "Missing a temporary folder";
        } else if ($error == 7) {
            $errorStr = "Failed to write file to disk";
        } else {
            $errorStr = "Error in file upload";
        }

        Openbizx::$app->getClientProxy()->showErrorMessage($errorStr);
    }

}

?>


<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license. For more information, see
 * <http://www.doctrine-project.org>.
 */
namespace DoctrineModule\Service\Authentication;

use DoctrineModule\Authentication\Storage\ObjectRepository;
use DoctrineModule\Service\AbstractFactory;
use Zend\Authentication\Storage\Session as SessionStorage;
use Zend\ServiceManager\ServiceLocatorInterface;

/**
 * Factory to create authentication storage object.
 *
 * @license MIT
 * @link    http://www.doctrine-project.org/
 * @since   0.1.0
 * @author  Tim Roediger <superdweebie@gmail.com>
 */
class StorageFactory extends AbstractFactory
{
    /**
     * {@inheritDoc}
     *
     * @return \DoctrineModule\Authentication\Storage\ObjectRepository
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        /* @var $options \DoctrineModule\Options\Authentication */
        $options = $this->getOptions($serviceLocator, 'authentication');

        if (is_string($objectManager = $options->getObjectManager())) {
            $options->setObjectManager($serviceLocator->get($objectManager));
        }

        if (is_string($storage = $options->getStorage())) {
            $options->setStorage($serviceLocator->get($storage));
        }

        return new ObjectRepository($options);
    }

    /**
     * {@inheritDoc}
     */
    public function getOptionsClass()
    {
        return 'DoctrineModule\Options\Authentication';
    }
}


<?php

namespace Environaut\Report;

use Environaut\Report\Results\IResult;
use Environaut\Report\Results\Result;
use Environaut\Config\Parameters;

/**
 * Default class that holds results from checks.
 */
class Report implements IReport
{
    /**
     * Holds the results of all checks.
     *
     * @var array for results of processed checks
     */
    protected $results = array();

    /**
     * @var Parameters runtime parameters
     */
    protected $parameters;

    /**
     * Creates a new Report instance.
     *
     * @param array $results array of IResult instances to prefill the instance
     * @param array $parameters array of runtime parameters
     */
    public function __construct(array $results = array(), array $parameters = array())
    {
        $this->results = $results;
        $this->parameters = new Parameters($parameters);
    }

    /**
     * Adds the given result to this report.
     *
     * @param \Environaut\Report\Results\IResult $result result to add to this report
     *
     * @return Report this instance for fluent API support
     */
    public function addResult(IResult $result)
    {
        $this->results[] = $result;

        return $this;
    }

    /**
     * Replaces the current results with the given IResult instances.
     *
     * @param array $results array of IResult instances
     *
     * @return Report this instance for fluent API support
     */
    public function setResults(array $results)
    {
        $this->results = $results;

        return $this;
    }

    /**
     * Returns all results of the already processed checks.
     *
     * @return array of IResult instances
     */
    public function getResults()
    {
        return $this->results;
    }

    /**
     * Returns an array of ISetting instances that match the given criterias
     * from the successful results of this report.
     *
     * @param mixed $groups string or array of group names settings should match, the default null matches always
     * @param integer $flag type of settings to get
     *
     * @return array of ISetting instances
     */
    public function getSettings($groups = null, $flag = null)
    {
        $settings = array();

        foreach ($this->results as $result) {
            if (IResult::SUCCESS === $result->getStatus()) {
                $settings = array_merge($settings, $result->getSettings($groups, $flag));
            }
        }

        return $settings;
    }

    /**
     * Returns an array of cachable ISetting instances that match the given criterias
     * from the successful results of this report.
     *
     * @param mixed $groups string or array of group names settings should match, the default null matches always
     * @param integer $flag type of settings to get
     *
     * @return array of ISetting instances
     */
    public function getCachableSettings($groups = null, $flag = null)
    {
        $settings = array();

        foreach ($this->results as $result) {
            if (IResult::SUCCESS === $result->getStatus()) {
                $settings = array_merge($settings, $result->getCachableSettings($groups, $flag));
            }
        }

        return $settings;
    }

    /**
     * Returns an array of associative arrays for each ISetting instance
     * that matches the given criterias (from the successful results of this report).
     *
     * @param mixed $groups string or array of group names settings should match, the default null matches always
     * @param integer $flag type of settings to get
     *
     * @return array of associative arrays for each ISetting instance that matched
     */
    public function getSettingsAsArray($groups = null, $flag = null)
    {
        $settings = array();

        foreach ($this->results as $result) {
            if (IResult::SUCCESS === $result->getStatus()) {
                $new_settings = $result->getSettingsAsArray($groups, $flag);
                foreach ($new_settings as $s) {
                    $settings[] = $s;
                }
            }
        }

        return $settings;
    }

    /**
     * Returns an array of associative arrays for each cachable ISetting instance
     * that matches the given criterias (from the successful results of this report).
     *
     * @param mixed $groups string or array of group names settings should match, the default null matches always
     * @param integer $flag type of settings to get
     *
     * @return array of associative arrays for each ISetting instance that matched
     */
    public function getCachableSettingsAsArray($groups = null, $flag = null)
    {
        $settings = array();

        foreach ($this->results as $result) {
            if (IResult::SUCCESS === $result->getStatus()) {
                $settings[] = array_merge($settings, $result->getCachableSettingsAsArray($groups, $flag));
            }
        }

        return $settings;
    }

    /**
     * Runtime parameters to configure the report behaviour.
     *
     * @param Parameters $parameters runtime parameters to use
     *
     * @return Report this instance for fluent API support
     */
    public function setParameters(Parameters $parameters)
    {
        $this->parameters = $parameters;

        return $this;
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: hua
 * Date: 2018/9/25
 * Time: 下午12:31
 */

namespace DdvPhp\DdvUtil\Laravel\Proxy\Traits;

use Closure;
use DdvPhp\DdvUtil\Laravel\Proxy\Libs\LogicProxy;
use ReflectionMethod;
use ReflectionParameter;
use ReflectionException;
use Illuminate\Http\Request as HttpRequest;
use DdvPhp\DdvUtil\Laravel\Exceptions\ProxyExceptions;
use DdvPhp\DdvUtil\Laravel\Proxy\Libs\Parameters;
use DdvPhp\DdvUtil\Laravel\Proxy\Interfaces\Parameters as ParametersInterface;

trait Proxy
{
    // 使用请求模块
    use Request;
    // 使用属性模块
    use Prototype;
    // 使用事物队列模块
    use TransactionQuque;

    /**
     * @var LogicProxy[] $cacheLogicProxy
     */
    protected $cacheLogicProxy = [];
    /**
     * @var array
     */
    protected $cacheObjCall = [];

    /**
     * 调用
     * @param array|callable|Closure|string $handler
     * @param array|ParametersInterface $arguments
     * @param ParametersInterface $parameters
     * @param string|null $callCalssName
     * @return mixed
     * @throws ProxyExceptions
     * @throws ReflectionException
     */
    public function call($handler, $arguments = null, $parameters = null, $callCalssName = null){
        /**
         * 字符串类调用强转数组
         * 'AA\BB::bb' 转为 ['AA\BB', 'cc']
         */
        if (is_string($handler) && strpos($handler, '::') !== false) {
            // 拆分数组
            list($className, $method) = explode('::', $handler, 2);
            // 如果是可以调用的回调
            if (is_callable(array($className, $method)) || method_exists($className, $method)) {
                // 重写回调
                $handler = array($className, $method);
            }
            // 释放内存
            unset($className, $method);
        }
        /**
         * 试图提取调用的类名
         */
        $className = is_array($handler) && isset($handler[0]) ? $handler[0] : null;
        /**
         * 判断类名是否存在
         */
        if ($className && is_string($className) && class_exists($className)) {
            /**
             * 试图反射方式
             */
            $reflectionMethod = new ReflectionMethod($className, $handler[1]);
            /**
             * 判断是否为静态方法
             * 是的话不需要实例化
             */
            if (!$reflectionMethod->isStatic()) {

                if (!(isset($this->cacheObjCall[$className]) && $this->cacheObjCall[$className] instanceof $className)){
                    $carguments = array();
                    $cparameters = new Parameters([$className, '__construct'], $carguments);
                    $this->argumentsInitByReflectionParameter($carguments, $cparameters);
                    $this->cacheObjCall[$className] = new $className(...$cparameters->getParameters());
                    unset($carguments, $cparameters);
                }
                // 实例化
                $handler = array($this->cacheObjCall[$className], $handler[1]);
            }
            unset($reflectionMethod);
        }
        /**
         * 调用类作用域
         * @var string $newClassScope
         */
        $newClassScope = empty($callCalssName)? get_called_class() : $callCalssName;
        /**
         * 如果第二个参数传入了第三个参数的内容，交换内容
         */
        if (is_object($arguments) && $arguments instanceof ParametersInterface){
            $t = &$parameters;
            unset($parameters);
            $parameters = &$arguments;
            unset($arguments);
            if (is_array($t)){
                $arguments = &$t;
            }else{
                $arguments = $parameters->getParameters();
            }
            unset($t);
        }
        /**
         * 确保第二个参数是一个数组
         */
        if (!is_array($arguments)){
            $arguments = array();
        }
        /**
         * 必须有一个解析参数的参数
         */
        if (!(isset($parameters)&&$parameters instanceof ParametersInterface)){
            $parameters = new Parameters($handler, $arguments);
        }
        $this->argumentsInitByReflectionParameter($arguments, $parameters);
        return call_user_func_array(
            Closure::bind(
                function ($handler, $arguments){
                    return call_user_func_array($handler, $arguments);
                },
                null,
                $newClassScope),
            [$handler, $arguments]
        );
    }

    /**
     * @param $parameters
     * @param $arguments
     * @throws ProxyExceptions
     */
    protected function argumentsInitByReflectionParameter(&$arguments, ParametersInterface $parameters){

        /**
         * 请求输入数据
         * @var array $input
         */
        $input = $this->getRequest()->input();
        /**
         * 遍历空参数，试图从请求输入中获取
         */
        $parameters->mapNullParameters(function (&$value, $name, $index, ReflectionParameter $parameter) use (&$input) {
            $isHas = false;
            if (!empty($name) && isset($input[$name])) {
                // 试图获取输入值
                $data = &$input[$name];
                // 反射类
                $reflectionClass = $parameter->getClass();
                // 判断是否为数组
                if ($parameter->isArray()) {
                    // 传入的值要求是数组，所以强转数组
                    $value = is_array($data) ? $data : array($data);
                    $isHas = true;
                } elseif (empty($reflectionClass)) {
                    // 不转换
                    $value = $data;
                    $isHas = true;
                } elseif (is_object($data) && $reflectionClass->isInstance($data)){
                    $value = $data;
                    $isHas = true;
                }
                unset($data);
            }
            unset($name, $value, $input, $parameter);
            return $isHas;
        });

        unset($input);

        /**
         * 通过反射类
         * 类名获取
         */
        $parameters->mapNullParameters(function (&$value, $name, $index, ReflectionParameter $parameter) {
            // 反射类
            $reflectionClass = $parameter->getClass();
            if (!empty($reflectionClass)) {
                /**
                 * 判断是否期待的类是 自己 代理本身
                 */
                if ($reflectionClass->isInstance($this)) {
                    // 返回代理
                    $value = $this;
                } elseif ($reflectionClass->isInstance($this->getRequest())) {
                    // 请求对象
                    $value = $this->getRequest();
                } else {
                    $value = app($reflectionClass->getName());
                }
            }
            unset($value, $name, $index, $parameter);
            return !empty($reflectionClass);
        });
        /**
         * 赋予默认值
         */
        $parameters->mapNullParameters(function (&$value, $name, $index, ReflectionParameter $parameter) {
            if ($parameter->isDefaultValueAvailable()){
                $value = $parameter->getDefaultValue();
            }
            unset($name, $value, $index, $parameter);
        });

        /**
         * 通过检测
         */
        $parameters->mapParameters(function (&$value, $name, $index, ReflectionParameter $parameter) {
            $className = $parameter->getClass();
            if (empty($className)) {
                if (method_exists($parameter, 'hasType') && method_exists($parameter, 'getType')) {
                    $type = $parameter->getType();
                    if ($parameter->hasType() && $type->isBuiltin()) {
                        switch ($type->getName()) {
                            case 'int':
                                $value = is_numeric($value) ? (int)$value : 0;
                                break;
                            case 'float':
                                $value = is_numeric($value) ? (float)$value : 0;
                                break;
                            case 'bool':
                                $value = (bool)$value;
                                break;
                            case 'string':
                                $value = (is_string($value) || is_numeric($value)) ? (string)$value : '';
                                break;
                            case 'array':
                                $value = isset($value) ? (is_array($value) ? $value : array($value)) : array();
                                break;
                        }
                    }
                }
            }
        });
        $arguments = $parameters->getParameters();
        unset($arguments, $parameters);
    }

    /**
     * @param $callClass
     * @return LogicProxy
     * @throws ProxyExceptions
     */
    public function getLogicProxyCallClass($callClass){
        if (!(isset($this->cacheLogicProxy[$callClass]) && $this->cacheLogicProxy[$callClass] instanceof LogicProxy)){
            $this->cacheLogicProxy[$callClass] = new LogicProxy($callClass, $this);
        }
        return $this->cacheLogicProxy[$callClass];
    }

    public function destroy()
    {
        $this->cacheLogicProxy = $this->cacheObjCall = [];
    }
}


<?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: LabelList.php 543 2009-10-03 08:50:00Z mr_a_ton$
 */

namespace Openbizx\Easy\Element;

use Openbizx\Core\Expression;
use Openbizx\Easy\Element\Element;

/**
 * LebelText - class LabelText is element that view value who binds
 * with a BizField
 *
 * @package openbiz.bin.easy.element
 * @author Rocky Swen
 * @copyright Copyright (c) 2009
 * @version 1.0
 * @access public
 */
class HTMLPreview extends Element
{
    public $fieldName;
    public $label;
    public $displayFormat;
    public $text;
    public $link;
    public $target;
    public $maxLength;
    public $percent;
    /**
     * Read array meta data, and store to meta object
     *
     * @param array $xmlArr
     * @return void
     */
    protected function readMetaData(&$xmlArr)
    {
        parent::readMetaData($xmlArr);
        $this->fieldName = isset($xmlArr["ATTRIBUTES"]["FIELDNAME"]) ? $xmlArr["ATTRIBUTES"]["FIELDNAME"] : null;
        $this->label = isset($xmlArr["ATTRIBUTES"]["LABEL"]) ? $xmlArr["ATTRIBUTES"]["LABEL"] : null;
        $this->text = isset($xmlArr["ATTRIBUTES"]["TEXT"]) ? $xmlArr["ATTRIBUTES"]["TEXT"] : null;
        $this->link = isset($xmlArr["ATTRIBUTES"]["LINK"]) ? $xmlArr["ATTRIBUTES"]["LINK"] : null;
        $this->target = isset($xmlArr["ATTRIBUTES"]["TARGET"]) ? $xmlArr["ATTRIBUTES"]["TARGET"] : null;
        $this->maxLength = isset($xmlArr["ATTRIBUTES"]["MAXLENGHT"]) ? $xmlArr["ATTRIBUTES"]["MAXLENGHT"] : null;
        $this->maxLength = isset($xmlArr["ATTRIBUTES"]["MAXLENGTH"]) ? $xmlArr["ATTRIBUTES"]["MAXLENGTH"] : null;
        $this->percent = isset($xmlArr["ATTRIBUTES"]["PERCENT"]) ? $xmlArr["ATTRIBUTES"]["PERCENT"] : "N";
        $this->displayFormat = isset($xmlArr["ATTRIBUTES"]["DISPLAYFORMAT"]) ? $xmlArr["ATTRIBUTES"]["DISPLAYFORMAT"] : null;
    }

    /**
     * Get target of link
     * ...
     *
     * @return string
     */
    protected function getTarget()
    {
        if ($this->target == null)
            return null;

        return "target='" . $this->target ."'";
        ;
    }

    /**
     * Get link of LabelText
     *
     * @return string
     */
    protected function getLink()
    {
        if ($this->link == null)
            return null;
        $formobj = $this->getFormObj();
        return Expression::evaluateExpression($this->link, $formobj);
    }

    /**
     * Get text of label
     *
     * @return string
     */
    protected function getText()
    {
        if ($this->text == null)
            return null;
        $formObj = $this->getFormObj();
        return Expression::evaluateExpression($this->text, $formObj);
    }

    /**
     * Render label
     *
     * @return string HTML text
     */
    public function renderLabel()
    {
        return $this->label;
    }

    /**
     * Render, draw the element according to the mode
     *
     * @return string HTML text
     */
    public function render()
    {
        $value = $this->text ? $this->getText() : $this->value;

        if ($value == null || $value =="")
            return "";

        $style = $this->getStyle();
        $id = $this->objectName;
        $func = $this->getFunction();

        if ($this->translatable == 'Y')
            $value = $this->translateString($value);
        $value_org = strip_tags($value);
        if((int)$this->maxLength>0){
	        if(function_exists('mb_strlen') && function_exists('mb_substr')){
	        	if(mb_strlen($value,'UTF8') > (int)$this->maxLength){
	        		$value = mb_substr($value,0,(int)$this->maxLength,'UTF8').'...';
	        	}
	        }else{
	        	if(strlen($value) > (int)$this->maxLength){
	        		$value = substr($value,0,(int)$this->maxLength).'...';
	        	}
	        }
        }
        if($this->height)
        {
        	$height = $this->height.'px';
        }
        if ($value!=null)
        {
        	$header = "
        	<link href=\"".OPENBIZ_JS_URL."/ckeditor/contents.css\" rel=\"stylesheet\" type=\"text/css\">
        	";
           $sHTML = "

           			";

        }

        return $sHTML;
    }

}

?>


<?php

namespace Purethink\CMSBundle\Entity;

use A2lix\I18nDoctrineBundle\Doctrine\ORM\Util\Translatable;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\SoftDeleteable\SoftDeleteable;
use Gedmo\SoftDeleteable\Traits\SoftDeleteableEntity;
use Gedmo\Timestampable\Traits\TimestampableEntity;
use Purethink\CoreBundle\Entity\Media;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Table(name="component")
 * @ORM\Entity()
 * @Gedmo\SoftDeleteable(fieldName="deletedAt")
 */
class Component implements SoftDeleteable
{
    use Translatable;
    use TimestampableEntity;
    use SoftDeleteableEntity;

    /**
     * @var integer
     *
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $id;

    /**
     * @Gedmo\Slug(fields={"id"})
     * @ORM\Column(length=255, unique=true)
     */
    protected $slug;

    /**
     * @var Media
     *
     * @ORM\ManyToOne(targetEntity="Purethink\CoreBundle\Entity\Media", cascade={"persist"})
     * @ORM\JoinColumn(nullable=true)
     */
    protected $media;

    /**
     * @ORM\Column(type="boolean")
     */
    protected $enabled = true;

    /**
     * @ORM\ManyToOne(targetEntity="Extension", inversedBy="components")
     * @ORM\JoinColumn(onDelete="CASCADE", nullable=false)
     * @Assert\NotNull()
     */
    protected $extension;

    /**
     * @ORM\OneToMany(targetEntity="ComponentHasElement", mappedBy="component", cascade={"persist"}, orphanRemoval=true)
     */
    protected $elements;

    protected $translations;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        if ($this->getCurrentTranslation()) {
            return $this->getCurrentTranslation()->getName();
        }

        return null;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        if ($this->getCurrentTranslation()) {
            return $this->getCurrentTranslation()->getDescription();
        }

        return null;
    }

    public function __toString()
    {
        if ($this->translations && $this->translations->count()) {
            return (string)$this->getName();
        }
        return '';
    }

    /**
     * Set slug
     *
     * @param string $slug
     * @return Component
     */
    public function setSlug($slug)
    {
        $this->slug = $slug;

        return $this;
    }

    /**
     * Get slug
     *
     * @return string
     */
    public function getSlug()
    {
        return $this->slug;
    }

    /**
     * Set extension
     *
     * @param Extension $extension
     * @return Component
     */
    public function setExtension(Extension $extension)
    {
        $this->extension = $extension;

        return $this;
    }

    /**
     * Get extension
     *
     * @return Extension
     */
    public function getExtension()
    {
        return $this->extension;
    }

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->translations = new ArrayCollection();
        $this->elements = new ArrayCollection();
    }

    /**
     * Add elements
     *
     * @param ComponentHasElement $elements
     * @return Component
     */
    public function addElement(ComponentHasElement $elements)
    {
        $elements->setComponent($this);
        $this->elements[] = $elements;

        return $this;
    }

    /**
     * Remove elements
     *
     * @param ComponentHasElement $elements
     */
    public function removeElement(ComponentHasElement $elements)
    {
        $this->elements->removeElement($elements);
    }

    /**
     * Get elements
     *
     * @return Collection
     */
    public function getElements()
    {
        return $this->elements;
    }

    /**
     * Set enabled
     *
     * @param boolean $enabled
     * @return Component
     */
    public function setEnabled($enabled)
    {
        $this->enabled = $enabled;

        return $this;
    }

    /**
     * Get enabled
     *
     * @return boolean
     */
    public function getEnabled()
    {
        return $this->enabled;
    }

    /**
     * @return mixed
     */
    public function getMedia()
    {
        return $this->media;
    }

    /**
     * @param mixed $media
     * @return Component
     */
    public function setMedia($media)
    {
        $this->media = $media;
        return $this;
    }
}


<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license. For more information, see
 * <http://www.doctrine-project.org>.
 */

namespace DoctrineModule\Service;

use RuntimeException;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Cache\Storage\StorageInterface;
use DoctrineModule\Cache\ZendStorageCache;

/**
 * ZendStorageCache ServiceManager factory
 *
 * @license MIT
 * @link    http://www.doctrine-project.org/
 * @author  Marco Pivetta <ocramius@gmail.com>
 */
class ZendStorageCacheFactory extends CacheFactory
{
    /**
     * {@inheritDoc}
     * @return ZendStorageCache
     * @throws RuntimeException
     */
    public function createService(ServiceLocatorInterface $sl)
    {
        /** @var $options \DoctrineModule\Options\Cache */
        $options  = $this->getOptions($sl, 'cache');
        $instance = $options->getInstance();

        if (!$instance) {
            // @todo move this validation to the options class
            throw new RuntimeException('ZendStorageCache must have a referenced cache instance');
        }

        $cache = $sl->get($instance);

        if (!$cache instanceof StorageInterface) {
            throw new RuntimeException(
                sprintf(
                    'Retrieved storage "%s" is not a Zend\Cache\Storage\StorageInterface instance, %s found',
                    $instance,
                    is_object($cache) ? get_class($cache) : getType($cache)
                )
            );
        }

        return new ZendStorageCache($cache);
    }
}


<?php

/**
 * NewForm class
 *
 * @package
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @access public
 */

namespace Openbizx\View;

use Openbizx\Data\DataRecord;
use Openbizx\View\InputForm;

/*
 * public methods: fetchData, insertRecord,
 */

class NewForm extends InputForm
{

    //list of method that can directly from browser
    protected $directMethodList = array('insertrecord', 'switchform');
    public $recordId;
    public $activeRecord;

    /**
     * Fetch single record
     *
     * @return array one record array
     */
    public function fetchData()
    {
        return $this->getNewRecord();
    }

    /**
     * Insert new record
     *
     * @return mixed
     */
    public function insertRecord()
    {
        $recArr = $this->readInputRecord();
        //$this->setActiveRecord($recArr);
        if (count($recArr) == 0)
            return;

        try {
            $this->validateForm();
        } catch (Openbizx\Validation\Exception $e) {
            $this->processFormObjError($e->errors);
            return;
        }

        $this->_doInsert($recArr);

        //$this->commitFormElements(); // commit change in FormElement
        // in case of popup form, close it, then rerender the parent form
        /* if ($this->parentFormName)
          {
          $this->close();

          $this->renderParent();
          } */

        $this->formHelper->processPostAction();
    }

    /**
     * Do insert record
     *
     * @param array $inputRecord
     * @return void
     */
    protected function _doInsert($inputRecord)
    {

        $dataRec = new DataRecord(null, $this->getDataObj());

        // $inputRecord['Id'] = null; // comment it out for name PK case
        foreach ($inputRecord as $k => $v)
            $dataRec[$k] = $v; // or $dataRec->$k = $v;

        try {
            $dataRec->save();
        } catch (Openbizx\Validation\Exception $e) {
            $errElements = $this->getErrorElements($e->errors);
            if (count($e->errors) == count($errElements)) {
                $this->formHelper->processFormObjError($errElements);
            } else {
                $errmsg = implode("<br />", $e->errors);
                Openbizx::$app->getClientProxy()->showErrorMessage($errmsg);
            }
            return;
        } catch (Openbizx\Data\Exception $e) {
            $this->processDataException($e);
            return;
        }
        $this->activeRecord = null;
        $this->getActiveRecord($dataRec["Id"]);

        //$this->runEventLog();
        return $dataRec["Id"];
    }

    /**
     * Get new record
     *
     * @return array
     */
    protected function getNewRecord()
    {
        if ($this->getDataObj()) {
            $recArr = $this->getDataObj()->newRecord();
        }
        if (!$recArr)
            return null;
        // load default values if new record value is empty
        $defaultRecArr = array();
        foreach ($this->dataPanel as $element) {
            if ($element->fieldName) {
                $defaultRecArr[$element->fieldName] = $element->getDefaultValue();
            }
        }
        foreach ($recArr as $field => $val) {
            if ($val == "" && $defaultRecArr[$field] != "") {
                $recArr[$field] = $defaultRecArr[$field];
            }
        }
        return $recArr;
    }

}

?>


<?php
declare(strict_types = 1);

namespace Innmind\Rest\Client\Server\Capabilities;

use Innmind\Rest\Client\{
    Server\Capabilities as CapabilitiesInterface,
    Definition\HttpResource,
    Serializer\Decode,
    Serializer\Encode,
    Serializer\Denormalizer\DenormalizeCapabilitiesNames,
    Serializer\Denormalizer\DenormalizeDefinition,
    Serializer\Normalizer\NormalizeDefinition,
};
use Innmind\Filesystem\{
    Adapter,
    File,
    Directory,
    Exception\FileNotFound,
};
use Innmind\Url\UrlInterface;
use Innmind\Immutable\{
    SetInterface,
    Set,
    MapInterface,
    Map,
};

final class CacheCapabilities implements CapabilitiesInterface
{
    private $capabilities;
    private $filesystem;
    private $decode;
    private $encode;
    private $denormalizeNames;
    private $denormalizeDefinition;
    private $normalizeDefinition;
    private $directory;
    private $names;
    private $definitions;

    public function __construct(
        CapabilitiesInterface $capabilities,
        Adapter $filesystem,
        Decode $decode,
        Encode $encode,
        DenormalizeCapabilitiesNames $denormalizeNames,
        DenormalizeDefinition $denormalizeDefinition,
        NormalizeDefinition $normalizeDefinition,
        UrlInterface $host
    ) {
        $this->capabilities = $capabilities;
        $this->filesystem = $filesystem;
        $this->decode = $decode;
        $this->encode = $encode;
        $this->denormalizeNames = $denormalizeNames;
        $this->denormalizeDefinition = $denormalizeDefinition;
        $this->normalizeDefinition = $normalizeDefinition;
        $this->directory = \md5((string) $host);
        $this->definitions = new Map('string', HttpResource::class);
    }

    /**
     * {@inheritdoc}
     */
    public function names(): SetInterface
    {
        if ($this->names instanceof SetInterface) {
            return $this->names;
        }

        try {
            $file = $this->load('.names');
            return $this->names = ($this->denormalizeNames)(
                ($this->decode)('json', $file->content())
            );
        } catch (FileNotFound $e) {
            $this->names = $this->capabilities->names();
            $this->persist('.names', $this->names->toPrimitive());

            return $this->names;
        }
    }

    public function get(string $name): HttpResource
    {
        if ($this->definitions->contains($name)) {
            return $this->definitions->get($name);
        }

        try {
            $file = $this->load($name);
            $definition = ($this->denormalizeDefinition)(
                ($this->decode)('json', $file->content()),
                $name
            );
        } catch (FileNotFound $e) {
            $definition = $this->capabilities->get($name);
            $this->persist(
                $name,
                ($this->normalizeDefinition)($definition)
            );
        }

        $this->definitions = $this->definitions->put(
            $name,
            $definition
        );

        return $definition;
    }

    /**
     * {@inheritdoc}
     */
    public function definitions(): MapInterface
    {
        $this->names()->foreach(function(string $name) {
            $this->get($name);
        });

        return $this->definitions;
    }

    /**
     * {@inheritdoc}
     */
    public function refresh(): CapabilitiesInterface
    {
        $this->names = null;
        $this->definitions = $this->definitions->clear();
        $this->filesystem->remove($this->directory);
        $this->capabilities->refresh();

        return $this;
    }

    private function load(string $file): File
    {
        $file .= '.json';

        if (!$this->filesystem->has($this->directory)) {
            throw new FileNotFound;
        }

        $directory = $this->filesystem->get($this->directory);

        if (!$directory instanceof Directory) {
            throw new FileNotFound;
        }

        if (!$directory->has($file)) {
            throw new FileNotFound;
        }

        return $directory->get($file);
    }

    private function persist(string $name, array $data): self
    {
        if ($this->filesystem->has($this->directory)) {
            $directory = $this->filesystem->get($this->directory);
        } else {
            $directory = new Directory\Directory($this->directory);
        }

        $directory = $directory->add(
            new File\File(
                $name.'.json',
                ($this->encode)($data)
            )
        );
        $this->filesystem->add($directory);

        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.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: ImageUploader.php 2825 2010-12-08 19:22:02Z jixian2003 $
 */

namespace Openbizx\Easy\Element;

use Openbizx\Openbizx;
use Openbizx\Easy\Element\FileUploader;

/**
 * File class is the element for Upload Image
 *
 * @package openbiz.bin.easy.element
 * @author jixian2003
 * @copyright Copyright (c) 2005-2009
 * @access public
 */
class ImageUploader extends FileUploader
{

    public $picWidth;
    public $picHeight;
    public $thumbWidth;
    public $thumbHeight;
    public $thumbFolder;
    public $preview;
    public $picQuality;
    public $thumbQuality;

    /**
     * Initialize Element with xml array
     *
     * @param array $xmlArr
     * @return void
     */
    function __construct(&$xmlArr, $formObj)
    {
        parent::__construct($xmlArr, $formObj);
        $this->readMetaData($xmlArr);
        $this->translate();
    }

    /**
     * Read array meta data, and store to meta object
     *
     * @param array $xmlArr
     * @return void
     */
    protected function readMetaData(&$xmlArr)
    {
        parent::readMetaData($xmlArr);
        $this->picWidth = isset($xmlArr["ATTRIBUTES"]["PICWIDTH"]) ? $xmlArr["ATTRIBUTES"]["PICWIDTH"] : null;
        $this->picHeight = isset($xmlArr["ATTRIBUTES"]["PICHEIGHT"]) ? $xmlArr["ATTRIBUTES"]["PICHEIGHT"] : null;
        $this->picQuality = isset($xmlArr["ATTRIBUTES"]["PICQUALITY"]) ? $xmlArr["ATTRIBUTES"]["PICQUALITY"] : 80;
        $this->thumbWidth = isset($xmlArr["ATTRIBUTES"]["THUMBWIDTH"]) ? $xmlArr["ATTRIBUTES"]["THUMBWIDTH"] : null;
        $this->thumbHeight = isset($xmlArr["ATTRIBUTES"]["THUMBHEIGHT"]) ? $xmlArr["ATTRIBUTES"]["THUMBHEIGHT"] : null;
        $this->thumbQuality = isset($xmlArr["ATTRIBUTES"]["THUMBQUALITY"]) ? $xmlArr["ATTRIBUTES"]["THUMBQUALITY"] : 50;
        $this->thumbFolder = isset($xmlArr["ATTRIBUTES"]["THUMBFOLDER"]) ? $xmlArr["ATTRIBUTES"]["THUMBFOLDER"] : null;
        $this->preview = isset($xmlArr["ATTRIBUTES"]["PREVIEW"]) ? $xmlArr["ATTRIBUTES"]["PREVIEW"] : false;
    }

    /**
     * Set value of element
     *
     * @param mixed $value
     * @return mixed
     */
    function setValue($value)
    {
        if ($this->deleteable == 'N') {

        } else {
            $delete_user_opt = Openbizx::$app->getClientProxy()->getFormInputs($this->objectName . "_DELETE");
            if ($delete_user_opt) {
                $this->value = "";
                return;
            } else {
                if (count($_FILES) > 0) {

                } else {
                    $this->value = $value;
                }
            }
        }

        if (count($_FILES) > 0) {
            if (!$this->uploaded && $_FILES[$this->objectName]["size"] > 0) {
                $picFileName = parent::setValue($value);
                if ((int) $this->picWidth > 0 || (int) $this->picHeight > 0) {
                    //resize picture size
                    $fileName = $this->uploadRoot . $picFileName;
                    $width = $this->picWidth;
                    $height = $this->picHeight;
                    $quality = $this->picQuality;

                    $this->resizeImage($fileName, $fileName, $width, $height, $quality);
                }
                if (
                        ((int) $this->thumbWidth > 0 || (int) $this->thumbHeight > 0) &&
                        $this->thumbFolder != ""
                ) {
                    //generate thumbs picture
                    if (!is_dir($this->uploadRoot . $this->thumbFolder)) {
                        mkdir($this->uploadRoot . $this->thumbFolder, 0777, true);
                    }
                    $file = $_FILES[$this->objectName];
                    $thumbPath = $this->thumbFolder . "/thumbs-" . date("YmdHis") . "-" . urlencode($file['name']);
                    $thumbFileName = $this->uploadRoot . $thumbPath;
                    $width = $this->thumbWidth;
                    $height = $this->thumbHeight;
                    $quality = $this->thumbQuality;

                    $this->resizeImage($fileName, $thumbFileName, $width, $height, $quality);

                    $result = array('picture' => $this->uploadRootURL . $picFileName, 'thumbpic' => $this->uploadRootURL . $thumbPath);
                    $this->value = serialize($result);
                }
            }
        } else {
            $this->value = $value;
        }
    }

    /**
     * Resize the image     *
     *
     * @param string $sourceFileName
     * @param string $destFileName
     * @param number $width
     * @param number $height
     * @param int    $quality

     * quality is optional, and ranges from 0 (worst
     * quality, smaller file) to 100 (best quality, biggest file). The
     * default is the default IJG quality value (about 75).
     *

     * @return boolean true is success
     */
    protected function resizeImage($sourceFileName, $destFileName, $width, $height, $quality)
    {
        if (!function_exists("imagejpeg")) {
            return;
        }
        if ($width == 0) {
            $width = $height;
        }

        if ($height == 0) {
            $height = $width;
        }

        list($origWidth, $origHeight) = getimagesize($sourceFileName);

        $origRatio = $origWidth / $origHeight;

        if (($width / $height) > $origRatio) {
            $width = $height * $origRatio;
        } else {
            $height = $width / $origRatio;
        }

        $image_p = imagecreatetruecolor($width, $height);
        try {
            $image = @imagecreatefromjpeg($sourceFileName);
        } catch (Exception $e) {

        }
        try {
            if (!$image) {
                $image = @imagecreatefrompng($sourceFileName);
            }
        } catch (Exception $e) {

        }
        try {
            if (!$image) {
                $image = @imagecreatefromgif($sourceFileName);
            }
        } catch (Exception $e) {

        }
        try {
            if (!$image) {
                $image = @imagecreatefromwbmp($sourceFileName);
            }
        } catch (Exception $e) {

        }

        try {
            if (!$image) {
                $image = @imagecreatefromxbm($sourceFileName);
            }
        } catch (Exception $e) {

        }

        try {
            if (!$image) {
                $image = @imagecreatefromxpm($sourceFileName);
            }
        } catch (Exception $e) {

        }

        if (!$image) {
            return;
        }
        imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $origWidth, $origHeight);

        return imagejpeg($image_p, $destFileName, $quality);
    }

    public function render()
    {
        $disabledStr = ($this->getEnabled() == "N") ? "disabled=\"true\"" : "";
        $style = $this->getStyle();
        $func = $this->getFunction();
        $value = $this->getValue();
        if ($this->preview) {
            if ($value) {
                $preview = "objectName . "_preview\" src=\"$value\" class=\"image_preview\" />";
            }
        }
        if ($this->deleteable == "Y") {
            $delete_opt = "<input type=\"checkbox\" name=\"" . $this->objectName . "_DELETE\" id=\"" . $this->objectName . "_DELETE\" >Delete";
        } else {
            $delete_opt = "";
        }
        $sHTML .= "
        $preview
        <input type=\"file\" onchange=\"Openbizx.ImageUploader.updatePreview('" . $this->objectName . "')\" name=\"$this->objectName\" id=\"" . $this->objectName . "\" value=\"$this->value\" $disabledStr $this->htmlAttr $style $func>
        $delete_opt
        ";
        return $sHTML;
    }

}

?>


<?php
namespace DdvPhp\DdvUtil\Laravel;
use \DdvPhp\DdvUtil\String\Conversion;

trait Controller
{
    public $verifyObj;   //验证类
    public $verifyData;    //验证成功后的数据
    /**
     * 验证
     * @param array $rule [验证规则]
     * @param array|string $data [验证数据源]
     * @throws ApiException
     */
    public function verify(array $rule, $data = 'GET')
    {
        if (empty($verifyObj)) {
            $this->verifyObj = new \JiaLeo\Laravel\Verify\Verify();
        }

        $result = $this->verifyObj->check($rule, $data);
        $this->verifyData = $this->verifyObj->data;

        return $result;
    }
}


<?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: ColorPicker.php 2912 2010-12-17 18:30:31Z jixian2003 $
 */

namespace Openbizx\Easy\Element;

use Openbizx\Openbizx;

//include_once("InputElement.php");
class ColorPicker extends InputText {
	public $config;
	public $mode;
    /**
     * Read array meta data, and store to meta object
     *
     * @param array $xmlArr
     * @return void
     */
    protected function readMetaData(&$xmlArr)
    {
        parent::readMetaData($xmlArr);
        $this->cssClass = isset($xmlArr["ATTRIBUTES"]["CSSCLASS"]) ? $xmlArr["ATTRIBUTES"]["CSSCLASS"] : "input_text_s";
		$this->cssErrorClass = isset($xmlArr["ATTRIBUTES"]["CSSERRORCLASS"]) ? $xmlArr["ATTRIBUTES"]["CSSERRORCLASS"] : $this->cssClass."_error";
		$this->cssFocusClass = isset($xmlArr["ATTRIBUTES"]["CSSFOCUSCLASS"]) ? $xmlArr["ATTRIBUTES"]["CSSFOCUSCLASS"] : $this->cssClass."_focus";
        $this->mode = isset($xmlArr["ATTRIBUTES"]["MODE"]) ? $xmlArr["ATTRIBUTES"]["MODE"] : null;
        $this->config = isset($xmlArr["ATTRIBUTES"]["CONFIG"]) ? $xmlArr["ATTRIBUTES"]["CONFIG"] : null;
    }

	public function render(){
		Openbizx::$app->getClientProxy()->includeColorPickerScripts();
		if($this->value!=null){
    		$value = $this->value;
    	}else{
    		$value = $this->getText();
    	}

        $disabledStr = ($this->getEnabled() == "N") ? "READONLY=\"true\"" : "";
        $style = $this->getStyle();
        $func = $this->getFunction();
        $func_org = $func;
        $formobj = $this->GetFormObj();
    	if($formobj->errors[$this->objectName]){
			$func .= "onchange=\"this.className='$this->cssClass'\"";
		}else{
			$func .= "onfocus=\"this.className='$this->cssFocusClass'\" onblur=\"this.className='$this->cssClass'\"";
		}
        $elementName = $this->objectName;
        $elementTrigger=array();

		if($value){
			$default_color = "color: '#$value',";
		}else{
			$default_color = "";
			$value=$this->getDefaultValue() ? $this->getDefaultValue() : "";
		}
		switch(strtolower($this->mode)){
			case "viewonly":
				$sHTML .= "";
				$elementTrigger = array();
				break;
			case "widget":
				$config = "
							onShow: function (colpkr) {
								if(\$j(colpkr).css('display')=='none'){
									\$j(colpkr).fadeIn(300);
								}
								return false;
							},
							onHide: function (colpkr) {
								\$j(colpkr).fadeOut(300);
								return false;
							},
							onSubmit: function(hsb, hex, rgb, el) {
								$('$this->objectName').value=hex;
								\$j('#colorpreview_$this->objectName').css('backgroundColor', '#' + hex);
							},
							onChange: function (hsb, hex, rgb) {
								$('$this->objectName').value=hex;
								\$j('#colorpreview_$this->objectName').css('backgroundColor', '#' + hex);
							}
							";
				$sHTML .= "";
				$sHTML .= "<INPUT NAME=\"" . $this->objectName . "\" ID=\"" . $this->objectName ."\" VALUE=\"" . $value . "\" type=\"hidden\" />";
				$elementTrigger = array("colorpreview_$elementName");
				break;

			case "flat":
				$config = "flat: true,
							onSubmit: function(hsb, hex, rgb, el) {
								$('$this->objectName').value=hex;
								\$j('#colorpreview_$this->objectName').css('backgroundColor', '#' + hex);
							},
							onChange: function (hsb, hex, rgb) {
								$('$this->objectName').value=hex;
								\$j('#colorpreview_$this->objectName').css('backgroundColor', '#' + hex);

							}
				";
				$sHTML .= "";
				$sHTML .= "<INPUT NAME=\"" . $this->objectName . "\" ID=\"" . $this->objectName ."\" VALUE=\"" . $value . "\" $disabledStr $this->htmlAttr $style $func />";
				$sHTML .= "

";
				$elementTrigger = array("colorpicker_".$elementName);
				break;

			default:
				$config = "
							onShow: function (colpkr) {
								if(\$j(colpkr).css('display')=='none'){
									\$j(colpkr).fadeIn(300);
								}
								return false;
							},
							onHide: function (colpkr) {
								\$j(colpkr).fadeOut(300);
								return false;
							},
							onSubmit: function(hsb, hex, rgb, el) {
								$('$this->objectName').value=hex;
								\$j('#colorpreview_$this->objectName').css('backgroundColor', '#' + hex);
							},
							onChange: function (hsb, hex, rgb) {
								$('$this->objectName').value=hex;
								\$j('#colorpreview_$this->objectName').css('backgroundColor', '#' + hex);
							}
							";
				$sHTML .= "";
				$sHTML .= "<INPUT NAME=\"" . $this->objectName . "\" ID=\"" . $this->objectName ."\" VALUE=\"" . $value . "\" $disabledStr $this->htmlAttr $style $func />";
				$elementTrigger = array($elementName,"colorpreview_$elementName");
				break;
		}

		if($this->config){
			$config .= ",".$this->config;
		}
		$config = "{".$default_color.$config."}";
		foreach($elementTrigger as $trigger){
			$sHTML .= "\n";
		}

        return $sHTML;
	}

	public function getFunctionByEvent($event_name){
        $name = $this->objectName;
        // loop through the event handlers
        $func = "";

        if ($this->eventHandlers == null)
            return null;
        $formobj = $this->getFormObj();

        foreach($this->eventHandlers as $eventHandler){
        	if($eventHandler->event==$event_name){
        		break;
        	}
        }

        $ehName = $eventHandler->objectName;
        $event = $eventHandler->event;
        $type = $eventHandler->functionType;
        if (!$event) return;
        if($events[$event]!=""){
           $events[$event]=array_merge(array($events[$event]),array($eventHandler->getFormedFunction()));
        }else{
           $events[$event]=$eventHandler->getFormedFunction();
        }

		foreach ($events as $event=>$function){
			if(is_array($function)){
				foreach($function as $f){
					$function_str.=$f.";";
				}
				$func .= $function_str;
			}else{
				$func .= $function;
			}
		}
        return $func;
	}
}
?>


<?php
/**
 * Created by PhpStorm.
 * User: Stefan
 * Date: 26.09.2014
 * Time: 11:04
 */

namespace D4rk4ng3l\Oxid\CodeGenerator\Php;

use D4rk4ng3l\Oxid\CodeGenerator\GeneratorInterface;

class PhpUse implements GeneratorInterface
{
    private $use = array();

    /**
     * @param $className
     */
    public function addUse($className)
    {
        $this->use[$className] = "usage" . count($this->use);
    }

    /**
     * @param $className
     *
     * @return mixed
     */
    public function getClassAlias($className)
    {
        if (false === strpos($className, '\\')) {
            return $className;
        }

        $this->addUse($className);

        return $this->use[$className];
    }

    /**
     * @return string
     */
    public function generate()
    {
        $code = "";

        foreach ($this->use as $use => $alias) {
            $code .= "use $use as $alias\n";
        }

        return $code;
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: gnat
 * Date: 13/05/16
 * Time: 9:12 AM
 */

namespace NS\AceSonataDoctrineORMAdminBundle\Model;

use NS\SecurityBundle\Doctrine\SecuredEntityRepository;
use Sonata\DoctrineORMAdminBundle\Model\ModelManager as BaseModelManager;
use Sonata\DoctrineORMAdminBundle\Datagrid\ProxyQuery;

class ModelManager extends BaseModelManager
{
    /**
     * {@inheritdoc}
     */
    public function createQuery($class, $alias = 'o')
    {
        $repository = $this->getEntityManager($class)->getRepository($class);

        if ($repository instanceof SecuredEntityRepository) {
            return new ProxyQuery($repository->createSecuredQueryBuilder($alias));
        }

        return new ProxyQuery($repository->createQueryBuilder($alias));
    }
}