<?php
/**
 * This file is part of the Autarky package.
 *
 * (c) Andreas Lutro <anlutro@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Autarky\Container;

use Autarky\Container\Factory\Definition;
use Autarky\Container\Factory\FactoryInterface;

use ReflectionClass;
use ReflectionException;
use ReflectionFunction;
use ReflectionFunctionAbstract;
use ReflectionMethod;
use ReflectionParameter;

/**
 * Default implementation of the container.
 */
class Container implements ContainerInterface
{
	/**
	 * Resolved instances.
	 *
	 * @var array
	 */
	protected $instances = [];

	/**
	 * Factories.
	 *
	 * @var array
	 */
	protected $factories = [];

	/**
	 * Classes that should be shared instances.
	 *
	 * @var array
	 */
	protected $shared = [];

	/**
	 * Aliases.
	 *
	 * @var array
	 */
	protected $aliases = [];

	/**
	 * Parameter specifications.
	 *
	 * @var array
	 */
	protected $params = [];

	/**
	 * Resolving callbacks.
	 *
	 * @var array
	 */
	protected $resolvingCallbacks = [];

	/**
	 * More resolving callbacks.
	 *
	 * @var array
	 */
	protected $resolvingAnyCallbacks = [];

	/**
	 * Internal classes.
	 *
	 * @var array
	 */
	protected $internals = [];

	/**
	 * Whether internal classes should be protected from resolving or not.
	 *
	 * @var boolean
	 */
	protected $protectInternals = true;

	/**
	 * Whether to "autowire" classes or not.
	 *
	 * @var boolean
	 */
	protected $autowire = true;

	/**
	 * Create a new instance of the container.
	 *
	 * On instantiation, the container instance will bind itself onto itself,
	 * and alias the ContainerInterface to the class name.
	 */
	public function __construct()
	{
		$this->instance('Autarky\Container\Container', $this);
		$this->alias('Autarky\Container\Container', 'Autarky\Container\ContainerInterface');
		$this->alias('Autarky\Container\Container', 'Autarky\Container\ClassResolverInterface');
		$this->alias('Autarky\Container\Container', 'Autarky\Container\CallableInvokerInterface');
	}

	/**
	 * {@inheritdoc}
	 */
	public function define($class, $factory, array $params = array())
	{
		if ($params) {
			$this->params($class, $params);
		}

		if (!$factory instanceof FactoryInterface) {
			$factory = Definition::getDefaultForCallable($factory);
		}

		return $this->factories[$class] = $factory;
	}

	/**
	 * {@inheritdoc}
	 */
	public function invoke($callable, array $params = array())
	{
		// if $callable is a string, assume it's a class name with the method
		// "invoke" defined
		if (is_string($callable) && !is_callable($callable)) {
			$callable = [$callable, 'invoke'];
		}

		// if $callable is a static method-like string, convert it to an array
		if (is_string($callable) && strpos($callable, '::') !== false) {
			$callable = explode('::', $callable);
		}

		$class = null;
		$object = null;

		if (is_array($callable)) {
			$class = $callable[0];
			$method = $callable[1];

			if (is_object($class)) {
				$object = $class;
				$class = get_class($object);
			} else {
				$object = $this->resolve($class);
			}

			$reflFunc = new ReflectionMethod($object, $method);

			if ($reflFunc->isStatic()) {
				$object = null;
			}

			$callableString = $class.'::'.$method;
			if (isset($this->params[$callableString])) {
				$params = array_replace($this->params[$callableString], $params);
			}
		} else if (is_callable($callable)) {
			$reflFunc = new ReflectionFunction($callable);
		} else {
			$type = is_object($callable) ? get_class($callable) : gettype($callable);
			throw new \InvalidArgumentException("Callable must be a callable or array, $type given");
		}

		$args = $this->getFunctionArguments($reflFunc, $params);

		if ($class) {
			return $reflFunc->invokeArgs($object, $args);
		}

		return $reflFunc->invokeArgs($args);
	}

	/**
	 * {@inheritdoc}
	 */
	public function resolve($class, array $params = array())
	{
		$alias = null;

		if (isset($this->aliases[$class])) {
			$alias = $class;
			$class = $this->aliases[$class];
		}

		// will throw an exception if the class or alias is protected
		$this->checkProtected($class, $alias);

		// if the class is shared, an instance may already exist
		if (isset($this->instances[$class])) {
			return $this->instances[$class];
		}

		if (isset($this->params[$class])) {
			$params = array_replace($this->params[$class], $params);
		}

		// internal classes don't need to be protected when resolving
		// dependencies. save the previous protectInternals value, it will be
		// reset after resolving dependencies
		$previousState = $this->protectInternals;
		$this->protectInternals = false;

		// if no factory is defined for the class, create one
		if (!isset($this->factories[$class]) && $this->autowire) {
			$this->factories[$class] = Definition::getDefaultForClass($class);
		}

		if (!isset($this->factories[$class])) {
			if ($alias) {
				$class = "$class (via $alias)";
			}
			throw new Exception\ResolvingException("No factory defined for $class");
		}

		$object = $this->callFactory($this->factories[$class], $params);

		$this->protectInternals = $previousState;

		if ($object instanceof ContainerAwareInterface) {
			$object->setContainer($this);
		}

		if ($alias) {
			$this->callResolvingCallbacks($alias, $object);
		}
		$this->callResolvingCallbacks($class, $object);

		if ($this->isShared($class)) {
			$this->instances[$class] = $object;
		}

		return $object;
	}

	/**
	 * Call a factory.
	 *
	 * @param  Factory\FactoryInterface  $factory
	 * @param  array  $params
	 *
	 * @return object
	 */
	protected function callFactory(Factory\FactoryInterface $factory, array $params = array())
	{
		return $factory->invoke($this, $params);
	}

	/**
	 * Make a new factory definition for a class.
	 *
	 * @param  callable $callable
	 * @param  boolean  $reflect  Optional, default false - Whether to use reflection to find the arguments to the callable. If false, you will need to add arguments to the definition object yourself
	 *
	 * @return Definition
	 */
	public function makeFactory($callable, $reflect = false)
	{
		if ($reflect) {
			return Definition::getFromReflection($callable, null);
		}

		return new Definition($callable);
	}

	/**
	 * Get the existing factory for a class. If a factory is not already defined
	 * a default one will be created via reflection.
	 *
	 * @param  string $class  Name of the class
	 * @param  array  $params Optional
	 *
	 * @return FactoryInterface
	 */
	public function getFactory($class, array $params = array())
	{
		if (!isset($this->factories[$class]) && $this->autowire) {
			$this->factories[$class] = Definition::getDefaultForClass($class);
		}

		$factory = $this->factories[$class];

		// if $params is defined, we need to either make a copy of the existing
		// Factory or make the Definition create a new factory with the params
		if ($params) {
			$factory = $factory->getFactory($params);
		}

		return $factory;
	}

	/**
	 * Get an array of arguments to a function, resolving type-hinted arguments
	 * automatically on the way.
	 *
	 * @param  ReflectionFunctionAbstract $func
	 * @param  array                      $params
	 *
	 * @return array
	 *
	 * @throws Exception\UnresolvableArgumentException If any of the arguments are not type-hinted, does not have a default value and is not specified in $params
	 */
	protected function getFunctionArguments(ReflectionFunctionAbstract $func, array $params = array())
	{
		$args = [];

		foreach ($func->getParameters() as $param) {
			$class = $param->getClass();

			if ($class) {
				$args[] = $this->resolveClassArg($class, $param, $params);
			} else {
				$args[] = $this->resolveNonClassArg($param, $params, $func);
			}
		}

		return $args;
	}

	/**
	 * Resolve a class type-hinted argument for a funtion.
	 *
	 * @param  ReflectionClass     $class
	 * @param  ReflectionParameter $param
	 * @param  array               $params
	 *
	 * @return object|null
	 */
	protected function resolveClassArg(ReflectionClass $class, ReflectionParameter $param, array $params)
	{
		$name = '$'.$param->getName();
		$class = $class->getName();

		// loop to prevent code repetition. executes once trying to find the
		// parameter name in the $params array, then once more trying to find
		// the class name (typehint) of the parameter.
		while ($name !== null) {
			if ($params && array_key_exists($name, $params)) {
				$class = $params[$name];
			}

			if ($class instanceof Factory\FactoryInterface) {
				return $class->invoke($this);
			}

			if (is_object($class)) {
				return $class;
			}

			$name = ($name != $class) ? $class : null;
		}

		try {
			return $this->resolve($class);
		} catch (ReflectionException $exception) {
			if ($param->isOptional()) {
				return null;
			}

			throw $exception;
		}
	}

	/**
	 * Resolve a non-class function argument.
	 *
	 * @param  ReflectionParameter        $param
	 * @param  array                      $params
	 * @param  ReflectionFunctionAbstract $func
	 *
	 * @return mixed
	 */
	protected function resolveNonClassArg(ReflectionParameter $param, array $params, ReflectionFunctionAbstract $func)
	{
		$name = '$'.$param->getName();

		if ($params && array_key_exists($name, $params)) {
			$argument = $params[$name];

			if (is_array($argument) && isset($this->factories[$argument[0]])) {
				$argument = $this->callFactory($argument[0], $argument[1]);
			}

			return $argument;
		}

		if ($param->isDefaultValueAvailable()) {
			return $param->getDefaultValue();
		}

		throw Exception\UnresolvableArgumentException::fromReflectionParam($param, $func);
	}

	/**
	 * {@inheritdoc}
	 */
	public function resolving($classOrClasses, callable $callback)
	{
		foreach ((array) $classOrClasses as $class) {
			$this->resolvingCallbacks[$class][] = $callback;
		}
	}

	/**
	 * {@inheritdoc}
	 */
	public function resolvingAny(callable $callback)
	{
		$this->resolvingAnyCallbacks[] = $callback;
	}

	/**
	 * Call resolving callbacks for an object.
	 *
	 * @param  string $key    Container key - usually the class name
	 * @param  object $object
	 *
	 * @return void
	 */
	protected function callResolvingCallbacks($key, $object)
	{
		foreach ($this->resolvingAnyCallbacks as $callback) {
			call_user_func($callback, $object, $this);
		}

		if (isset($this->resolvingCallbacks[$key])) {
			foreach ($this->resolvingCallbacks[$key] as $callback) {
				call_user_func($callback, $object, $this);
			}
		}
	}

	/**
	 * Enable or disable autowiring.
	 *
	 * @param boolean $autowire
	 */
	public function setAutowire($autowire)
	{
		$this->autowire = (bool) $autowire;
	}

	/**
	 * {@inheritdoc}
	 */
	public function isBound($class)
	{
		if (isset($this->aliases[$class])) {
			$class = $this->aliases[$class];
		}

		return isset($this->instances[$class])
			|| isset($this->factories[$class])
			|| isset($this->shared[$class]);
	}

	/**
	 * {@inheritdoc}
	 */
	public function instance($class, $instance)
	{
		$this->shared[$class] = true;
		$this->instances[$class] = $instance;
	}

	/**
	 * {@inheritdoc}
	 */
	public function share($classOrClasses)
	{
		foreach ((array) $classOrClasses as $class) {
			$this->shared[$class] = true;
		}
	}

	/**
	 * {@inheritdoc}
	 */
	public function internal($classOrClasses)
	{
		foreach ((array) $classOrClasses as $class) {
			$this->internals[$class] = true;
		}
	}

	/**
	 * {@inheritdoc}
	 */
	public function alias($original, $aliasOrAliases)
	{
		foreach ((array) $aliasOrAliases as $alias) {
			$this->aliases[$alias] = $original;
		}
	}

	/**
	 * {@inheritdoc}
	 */
	public function params($keys, array $params)
	{
		foreach ((array) $keys as $key) {
			if (is_array($key)) {
				$key = $key[0].'::'.$key[1];
			}

			if (!isset($this->params[$key])) {
				$this->params[$key] = $params;
			} else {
				$this->params[$key] = array_replace($this->params[$key], $params);
			}
		}
	}

	/**
	 * Determine if a class is shared or not.
	 *
	 * @param  string  $class
	 *
	 * @return boolean
	 */
	protected function isShared($class)
	{
		return isset($this->shared[$class]) && $this->shared[$class];
	}

	/**
	 * Check if a class and its alias (optionally) are protected, and throw an
	 * exception if they are.
	 *
	 * @param  string $class
	 * @param  string|null $alias
	 *
	 * @return void
	 *
	 * @throws Exception\ResolvingInternalException If class or alias is internal
	 */
	protected function checkProtected($class, $alias)
	{
		if (!$this->protectInternals) {
			return;
		}

		if ($this->isProtected($class) || ($alias && $this->isProtected($alias))) {
			if ($alias) {
				$class = "$class (via alias $alias)";
			}
			$msg = "Class $class is internal and cannot be resolved.";
			throw new Exception\ResolvingInternalException($msg);
		}
	}

	/**
	 * Determine if a class is protected or not.
	 *
	 * @param  string  $class
	 *
	 * @return boolean
	 */
	protected function isProtected($class)
	{
		return isset($this->internals[$class]) && $this->internals[$class];
	}
}


<?php

namespace nadir2\core;

/**
 * This is facade class for working with session.
 * @author Leonid Selikhov
 */
class Session implements ArrayCollectionInterface
{

    /**
     * @ignore.
     */
    public function __construct()
    {
        // Nothing here...
    }

    /**
     * It returns the current ident of session.
     * @return string The session id.
     */
    public function getId(): string
    {
        return session_id();
    }

    /**
     * It checks if the session was started.
     * @return boolean
     */
    public function isStarted(): bool
    {
        return $this->getId() !== '';
    }

    /**
     * It sets the ident of current session.
     * @param string $sessionId
     * @return void
     */
    public function setId(string $sessionId): void
    {
        @session_id($sessionId);
    }

    /**
     * It returns the name of current session.
     * @return string
     */
    public function getName(): string
    {
        return session_name();
    }

    /**
     * The method sets the name of current session.
     * @param string $name By default it's PHPSESSID.
     * @return void
     * @throws Exception It's thrown if passed name consists digits only or is empty.
     */
    public function setName(string $name): void
    {
        if (!empty($name)) {
            if (!is_numeric($name)) {
                @session_name($name);
            } else {
                throw new Exception('The session name can\'t consist only of digits, '
                .'at least one letter must be presented.');
            }
        } else {
            throw new Exception('Empty session name value was passed.');
        }
    }

    /**
     * It inits the data of new session or continues the current session.
     * @param string $name The optional name of session, it has higher priority
     * than the $iSess parameter.
     * @param string $sessionId The optional session ident. It ignored if the $sSessName
     * parameter was passed.
     * @return string The id of current session.
     */
    public function start(?string $name = null, ?string $sessionId = null): string
    {
        if (!$this->isStarted()) {
            if (!is_null($name)) {
                $this->setName($name);
            }
            @session_start($sessionId);
        };
        return $this->getId();
    }

    /**
     * It commits the data of session and closes it.
     * @return void
     */
    public function commit(): void
    {
        if ($this->isStarted()) {
            session_commit();
        }
    }

    /**
     * It destroys the session data.
     * @return boolean|null The result of destruction.
     */
    public function destroy(): ?bool
    {
        if ($this->isStarted()) {
            @session_unset();
            return session_destroy();
        }
        return null;
    }

    /**
     * It complitly destroys session with cookie.
     * @return boolean|null The result.
     */
    public function destroyWithCookie(): ?bool
    {
        if ($this->isStarted()) {
            $this->destroy();
            return setcookie($this->getName(), '', time() - 1, '/');
        }
        return null;
    }

    /**
     * It adds the variable to the session.
     * @param string $key The name of variable.
     * @param mixed $value The value of it.
     * @return void.
     */
    public function add(string $key, $value): void
    {
        $_SESSION[$key] = $value;
    }

    /**
     * It adds the array of variables (the key-value pairs) to the session.
     * @param array $pairs
     * @return void
     */
    public function addAll(array $pairs): void
    {
        foreach ($pairs as $key => $value) {
            $this->add($key, $value);
        }
    }

    /**
     * It returns TRUE if the variable with passed key contains into the session.
     * @param string $key
     * @return boolean
     */
    public function contains(string $key): bool
    {
        return isset($_SESSION[$key]);
    }

    /**
     * It returns true if the session is empty.
     * @return boolean
     */
    public function isEmpty(): bool
    {
        return empty($_SESSION);
    }

    /**
     * It returns the variable of session value by passed key.
     * @param string $key
     * @return mixed|null.
     */
    public function get(string $key)
    {
        return $this->contains($key) ? $_SESSION[$key] : null;
    }

    /**
     * It returns the list of session variables.
     * @return string[]
     */
    public function getKeys(): array
    {
        return array_keys($_SESSION);
    }

    /**
     * It returns all session variables as associative array.
     * @return mixed[]
     */
    public function getAll(): array
    {
        $res = [];
        foreach ($this->getKeys() as $key) {
            $res[$key] = $this->get($key);
        }
        return $res;
    }

    /**
     * It removes the variable of session by passed key.
     * @param string $key
     * @return mixed|null The removed variable value.
     */
    public function remove(string $key)
    {
        if ($this->contains($key)) {
            $res = $_SESSION[$key];
            unset($_SESSION[$key]);
            return $res;
        } else {
            return null;
        }
    }

    /**
     * It clears the session by removing all stored variables.
     * @return mixed[] The array of removed vars.
     */
    public function removeAll(): array
    {
        $res = [];
        foreach ($this->getKeys() as $key) {
            $res[$key] = $this->remove($key);
        }
        return $res;
    }

    /**
     * It returns the count of variables contained into the session.
     * @return integer
     */
    public function size(): int
    {
        return count($this->getKeys());
    }
}


<?php

namespace Infotech\DocumentGenerator\Util;

use InvalidArgumentException;
use ReflectionObject;

class PropertyAccess
{
    /**
     * @param object|array $objectOrArray
     * @param string       $propertyName
     *
     * @return mixed
     * @throws InvalidArgumentException
     */
    public function get($objectOrArray, $propertyName)
    {
        if (is_array($objectOrArray)) {
            return $objectOrArray[$propertyName];
        } elseif (is_object($objectOrArray)) {
            $refObject = new ReflectionObject($objectOrArray);
            if ($refObject->hasProperty($propertyName)
                    and $refProp = $refObject->getProperty($propertyName)
                    and $refProp->isPublic()) {
                return $refProp->getValue($objectOrArray);
            }
            $getter = 'get' . $propertyName;
            if ($refObject->hasMethod($getter)) {
                return $refObject->getMethod($getter)->invoke($objectOrArray);
            }
        }

        throw new InvalidArgumentException(
            sprintf('Can not read property "%s"', $propertyName)
        );
    }
}


<?php
/**
 * This file is part of the RedKite CMS Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <info@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */

namespace RedKiteCms\Bridge\Monolog;

use Psr\Log\LoggerInterface;

/**
 * This object statically handles the MonoLogger logger
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Bridge\Monolog
 */
class DataLogger
{
    const INFO = "info";
    const DEBUG = "debug";
    const NOTICE = "notice";
    const WARNING = "warning";
    const ERROR = "error";
    const CRITICAL = "critical";
    const ALERT = "alert";
    const EMERGENCY = "emergency";

    /**
     * @type \Psr\Log\LoggerInterface
     */
    private static $logger = null;

    /**
     * Injects the logger
     *
     * @param null|LoggerInterface $logger
     */
    public static function init(LoggerInterface $logger = null)
    {
        self::$logger = $logger;
    }

    /**
     * Logs the given message
     *
     * @param        $message
     * @param string $type
     */
    public static function log($message, $type = DataLogger::INFO)
    {
        if (null === self::$logger) {
            return;
        }

        if (!method_exists(self::$logger, $type)) {
            $exceptionMessage = sprintf('Logger does not support the %s method.', $type);

            throw new \InvalidArgumentException($exceptionMessage);
        }

        self::$logger->$type($message);
    }
}


<?php

namespace Dhii\Output\Exception;

use ArrayAccess;
use Dhii\Data\Container\NormalizeContainerCapableTrait;
use Exception as RootException;
use Dhii\Util\String\StringableInterface as Stringable;
use Psr\Container\ContainerInterface;
use Dhii\Output\TemplateInterface;
use Dhii\Output\RendererAwareTrait;
use Dhii\Output\ContextAwareTrait;
use Dhii\I18n\StringTranslatingTrait;
use Dhii\Exception\CreateInvalidArgumentExceptionCapableTrait;
use stdClass;

/**
 * An exception that occurs when a template cannot produce output.
 *
 * @since [*next-version*]
 */
class TemplateRenderException extends RootException implements TemplateRenderExceptionInterface
{
    /*
     * Adds internal renderer awareness.
     *
     * @since [*next-version*]
     */
    use RendererAwareTrait {
        RendererAwareTrait::_setRenderer as _setRendererOriginal;
    }

    /*
     * Adds internal context awareness.
     *
     * @since [*next-version*]
     */
    use ContextAwareTrait;

    /*
     * Adds internal i18n capabilities.
     *
     * @since [*next-version*]
     */
    use StringTranslatingTrait;

    /*
     * Adds internal factory for creating invalid argument exceptions.
     *
     * @since [*next-version*]
     */
    use CreateInvalidArgumentExceptionCapableTrait;

    /*
     * Adds container normalization capabilities.
     *
     * @since [*next-version*]
     */
    use NormalizeContainerCapableTrait;

    /**
     * Constructor.
     *
     * @since [*next-version*]
     *
     * @param string|Stringable|null                             $message  The error message, if any.
     * @param int|null                                           $code     The error code, if any.
     * @param RootException|null                                 $previous The inner exception, if any.
     * @param TemplateInterface|null                             $renderer The associated renderer, if any.
     * @param array|ArrayAccess|stdClass|ContainerInterface|null $context  The associated context, if any.
     */
    public function __construct($message = null, $code = null, RootException $previous = null, TemplateInterface $renderer = null, $context = null)
    {
        parent::__construct((string) $message, (int) $code, $previous);
        $this->_setRenderer($renderer);
        $this->_setContext($context);
    }

    /**
     * {@inheritdoc}
     *
     * @since [*next-version*]
     */
    public function getRenderer()
    {
        return $this->_getRenderer();
    }

    /**
     * {@inheritdoc}
     *
     * @since [*next-version*]
     */
    public function getContext()
    {
        return $this->_getContext();
    }

    /**
     * {@inheritdoc}
     *
     * The renderer must be a template.
     *
     * @since [*next-version*]
     */
    protected function _setRenderer($renderer)
    {
        if ($renderer !== null && !($renderer instanceof TemplateInterface)) {
            throw $this->_createInvalidArgumentException(
                $this->__('Invalid template'),
                null,
                null,
                $renderer
            );
        }

        $this->_setRendererOriginal($renderer);
    }
}


<?php
/**
 * This file is part of the RedKite CMS Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <info@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */

namespace Controller\PageCollection;

use RedKiteCms\Rendering\Controller\PageCollection\ShowPageCollectionController as BaseShowPageCollectionController;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * This object implements the Silex controller to show the page collection dashboard interface
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package Controller\Page
 */
class ShowPageCollectionController extends BaseShowPageCollectionController
{
    /**
     * Show page collection dashboard interface action
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param \Silex\Application                        $app
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function showAction(Request $request, Application $app)
    {
        $options = array(
            "request" => $request,
            "configuration_handler" => $app["red_kite_cms.configuration_handler"],
            "page_collection_manager" => $app["red_kite_cms.page_collection_manager"],
            'form_factory' => $app["form.factory"],
            "pages_collection_parser" => $app["red_kite_cms.pages_collection_parser"],
            "username" => $this->fetchUsername($app["security"], $app["red_kite_cms.configuration_handler"]),
            'theme' => $app["red_kite_cms.theme"],
            'template_assets' => $app["red_kite_cms.template_assets"],
            'twig' => $app["twig"],
        );

        return parent::show($options);
    }

    /**
     * {@inheritdoc}
     */
    protected function configureOptions(OptionsResolver $resolver)
    {
        parent::configureOptions($resolver);

        $resolver->setRequired(
            array(
                'username',
            )
        );

        $resolver->setAllowedTypes(
            array(
                'username' => array(
                    'null',
                    'string',
                ),
            )
        );
    }
}


<?php
/**
 * Calculate load time of pages or scripts.
 *
 * @author    Josantonius <hello@josantonius.com>
 * @copyright 2017 - 2018 (c) Josantonius - PHP-LoadTime
 * @license   https://opensource.org/licenses/MIT - The MIT License (MIT)
 * @link      https://github.com/Josantonius/PHP-LoadTime
 * @since     1.0.0
 */
namespace Josantonius\LoadTime;

/**
 * Load time handler.
 */
class LoadTime
{
    /**
     * Save initial status time.
     *
     * @var float
     */
    public static $startTime = false;

    /**
     * Set initial time.
     *
     * @return float → microtime
     */
    public static function start()
    {
        return self::$startTime = microtime(true);
    }

    /**
     * Set end time.
     *
     * @return float → seconds
     */
    public static function end()
    {
        if (self::$startTime) {
            $time = round((microtime(true) - self::$startTime), 4);
            self::$startTime = false;
        }

        return (isset($time)) ? $time : false;
    }

    /**
     * Check if the timer has been started.
     *
     * @since 1.1.2
     *
     * @return boolean
     */
    public static function isActive()
    {
        return (self::$startTime) ? true : false;
    }
}


<?php

/**
 * The Benri_Db_Table class is an object-oriented interface to
 * database tables. It provides methods for many common operations on tables.
 *
 * @link http://framework.zend.com/manual/1.12/en/zend.db.table.html Zend_Db_Table
 */
class Benri_Db_Table extends Zend_Db_Table
{
    /**
     * The configuration entry to use when `multidb` is registered.
     *
     * @var string
     */
    protected $_connection = 'default';

    /**
     * The primary key column or columns.
     *
     * A compound key should be declared as an array. You may declare a
     * single-column primary key as a string. Prefer arrays.
     *
     * @var mixed
     */
    protected $_primary = ['id'];

    /**
     * Classname for row.
     *
     * @var string
     * @see Benri_Db_Table_Row
     */
    protected $_rowClass = 'Benri_Db_Table_Row';

    /**
     * Classname for rowset.
     *
     * @var string
     */
    protected $_rowsetClass = 'Benri_Db_Table_Rowset';

    /**
     * Fetches all rows.
     *
     * @param int $pageNumber An SQL LIMIT offset
     * @param int $pageSize An SQL LIMIT count
     * @param string|array $order An SQL ORDER clause
     * @return Benri_Db_Table_Row The row results
     */
    public static function all($pageNumber = 0, $pageSize = 10, $order = null)
    {
        return (new static())
            ->fetchAll(null, $order, $pageSize, $pageNumber);
    }

    /**
     * Fetches a new blank row (not from the database).
     *
     * @param array $data Data to populate in the new row
     * @return Benri_Db_Table_Row
     */
    public static function create($data = [])
    {
        $table = new static();

        return $table->createRow((array) $data);
    }

    /**
     * Fetches one row in an object of type Benri_Db_Table_Row, or returns
     * null if no row matches the specified criteria.
     *
     * @param string $column The sql `where` clause
     * @param mixed $value The value to use against the `where` clause
     * @return Benri_Db_Table_Row or null The row results, or null if no row
     *  found
     */
    public static function locate($column, $value)
    {
        $table  = new static();
        $select = $table->select()
            ->where("{$table->getAdapter()->quoteIdentifier($column)} = ?", $value)
            ->limit(1);

        return $table->fetchRow($select);
    }

    /**
     * Create table rows in bulk mode.
     *
     * @param array $batch and array of column-value pairs.
     * @return int The number of affected rows.
     * @throws Zend_Db_Adapter_Exception
     */
    public static function bulkInsert(array $batch)
    {
        $table = new static();

        if (1 === sizeof($batch)) {
            return $table->insert(array_shift($batch));
        }

        $adapter    = $table->getAdapter();
        $counter    = 0;
        $sqlBinds   = [];
        $values     = [];

        //
        // Do some voodoo here...
        foreach ($batch as $i => $row) {
            $placeholders = [];

            foreach ($row as $column => $value) {
                ++$counter;

                if ($adapter->supportsParameters('positional')) {
                    $placeholders[] = '?';
                    $values[]       = $value;
                } elseif ($adapter->supportsParameters('named')) {
                    $name           = ":col{$i}{$counter}";
                    $placeholders[] = $name;
                    $values[$name]  = $value;
                } else {
                    throw new Zend_Db_Adapter_Exception(sprintf(
                            '%s doesn\'t support positional or named binding',
                            get_class($table)
                        ));
                }
            }

            //
            // and more blacky magic over here...
            $sqlBinds[] = '(' . implode(',', $placeholders) . ')';
        }

        //
        // extract column names...
        $columns = array_keys($row);

        //
        // and quoteIdentifier() them.
        array_walk($columns, function (&$index) use ($adapter) {
                $index = $adapter->quoteIdentifier($index, true);
            });

        //
        // Shit, shit, shit! F U ZF.
        $spec = $adapter->quoteIdentifier(
                ($table->_schema ? "{$table->_schema}." : '') . $table->_name
            );

        //
        // Build the SQL using the placeholders...
        $sql = sprintf(
                'INSERT INTO %s (%s) VALUES %s',
                $spec,                  // fully table name
                implode(',', $columns), // column names
                implode(',', $sqlBinds) // placeholders
            );

        // Ready?
        $stmt = $adapter->prepare($sql);

        //
        // Fight!
        $stmt->execute($values);

        //
        // aaaaaaand voilá!
        return $stmt->rowCount();
    }

    /**
     * Returns an instance of a Zend_Db_Table_Select object.
     *
     * @param bool $withFromPart Whether or not to include the from part of
     *  the select based on the table
     * @return Zend_Db_Table_Select
     * @see http://framework.zend.com/manual/1.12/en/zend.db.select.html Zend_Db_Select
     */
    public function select($withFromPart = parent::SELECT_WITHOUT_FROM_PART)
    {
        return parent::select($withFromPart)
            ->setIntegrityCheck(false);
    }

    /**
     * Convert this object to a JSON string.
     *
     * @return string
     */
    public function toJson()
    {
        return json_encode($this->toArray(), JSON_FORCE_OBJECT | JSON_NUMERIC_CHECK);
    }

    /**
     * Create dynamic finders.
     *
     * Dynamic finders ease your life in a way to do queries quickly without
     * having to eventually instantiate a `Benri_Db_Table` class.
     *
     * <code>
     * // `where name = ?, "douggr"`
     * Person::whereNameEq('douggr');
     *
     * // `where phone IS NULL`
     * Person::wherePhoneIsNull();
     *
     * // `where id IN (?), $values`
     * SomeModel::whereIdIn(1, 2, 3, 4);
     * </code>
     *
     * @internal
     * @return Benri_Db_Table_Rowset
     * @throws Zend_Db_Table_Exception if invalid query
     */
    public static function __callStatic($method, array $args = [])
    {
        preg_match('/where(?P<column>[a-zA-Z]+)(?P<operator>Lt|Le|Gt|Ge|Eq|Ne|In|IsNull|IsNotNull)+/', $method, $matches);

        if (!$matches) {
            throw new Zend_Db_Table_Exception(sprintf(
                'Call to undefined method %s::%s()', get_called_class(), $method
            ));
        }

        //
        // PHP's black magic
        extract($matches);

        $table   = new static();
        $select  = $table->select();
        $options = [];
        $column  = $table->getAdapter()
            ->quoteIdentifier(Benri_Util_String::dasherize($column));

        foreach ($args as $key => $arg) {
            if (is_array($arg)) {
                $options = $arg;
                unset($args[$key]);
            }
        }

        foreach ($options as $method => $value) {
            call_user_func_array([$select, $method], (array) $value);
        }

        if ('IsNull' === $operator) {
            return $table->fetchAll($select->where("{$column} IS NULL"));
        }

        if ('IsNotNull' === $operator) {
            return $table->fetchAll($select->where("{$column} IS NOT NULL"));
        }

        switch ($operator) {
            case 'Lt':
                $operator = '< ?';
                break;

            case 'Le':
                $operator = '<= ?';
                break;

            case 'Gt':
                $operator = '> ?';
                break;

            case 'Ge':
                $operator = '>= ?';
                break;

            case 'Eq':
                $operator = '= ?';
                break;

            case 'Ne':
                $operator = '<> ?';
                break;

            case 'In':
                $operator = 'IN (?)';
                break;
        }

        return $table->fetchAll($select->where("{$column} {$operator}", $args));
    }

    /**
     * Initialize database adapter.
     *
     * @throws Zend_Db_Table_Exception
     */
    protected function _setupDatabaseAdapter()
    {
        if (Zend_Registry::isRegistered('multidb')) {
            return $this->_setAdapter(Zend_Registry::get('multidb')->getDb($this->_connection));
        }

        return parent::_setupDatabaseAdapter();
    }
}


<?php
/**
 * Weave Aura DIC Adaptor.
 */
namespace Weave\Container\Aura;

use Aura\Di\ContainerBuilder;

/**
 * Weave Aura DIC Adaptor.
 */
trait Aura
{
	use \Weave\Container\Container;

	/**
	 * The Container instance.
	 *
	 * @var \Aura\Di\Container
	 */
	protected $container;

	/**
	 * Setup the Dependency Injection Container
	 *
	 * @param array  $config      Optional config array as provided from loadConfig().
	 * @param string $environment Optional indication of the runtime environment.
	 *
	 * @return callable A callable that can instantiate instances of classes from the DIC.
	 */
	protected function loadContainer(array $config = [], $environment = null)
	{
		$containerConfigs = $this->provideContainerConfigs($config, $environment);
		array_unshift(
			$containerConfigs,
			new WeaveConfig(
				function ($pipelineName) {
					return $this->provideMiddlewarePipeline($pipelineName);
				},
				function ($router) {
					return $this->provideRouteConfiguration($router);
				}
			)
		);
		$this->container = (new ContainerBuilder)->newConfiguredInstance(
			$containerConfigs,
			ContainerBuilder::AUTO_RESOLVE
		);
		return $this->container->get('instantiator');
	}

	/**
	 * Returns an array of class strings and class instances for configuring the Aura DIC.
	 *
	 * @param array  $config      Optional config array as provided from loadConfig().
	 * @param string $environment Optional indication of the runtime environment.
	 *
	 * @return array
	 */
	abstract protected function provideContainerConfigs(array $config = [], $environment = null);
}


<?php
/**
 * Windwork
 *
 * 一个用于快速开发高并发Web应用的轻量级PHP框架
 *
 * @copyright Copyright (c) 2008-2017 Windwork Team. (http://www.windwork.org)
 * @license   http://opensource.org/licenses/MIT
 */
namespace wf\route\adapter;

/**
 * Windwork简单路由实现
 *
 * @package     wf.route.adapter
 * @author      cm <cmpan@qq.com>
 * @link        http://docs.windwork.org/manual/wf.route.html
 * @since       0.1.0
 */
class Simple extends \wf\route\RouteAbstract
{

    /**
     * 初始化路由实体
     */
    protected function initRoutArg()
    {
        // 启用模块则设置默认模块
        if ($this->cfg['useModule']) {
            $this->mod = $this->cfg['defaultMod'];
        }

        // 设置默认控制器
        $this->ctl = $this->cfg['defaultCtl'];

        // 设置默认操作
        $this->act = $this->cfg['defaultAct'];
    }

    /**
     * 分析站内URL
     *
     * 取得链接应该映射到哪个模块、控制器、动作，并且传什么参数到动作方法中。
     *
     * @param string $uri
     * @return \wf\route\RouteAbstract
     */
    public function parse($uri)
    {
        $this->initRoutArg();
        $opts = &$this->cfg;

        // 取得index.php?及后面部分
        // 去掉域名
        $uri = preg_replace("/((http|https)\\:\\/\\/.*?\\/)/", '', $uri);
        $uri = trim($uri, '/');

        // 去掉站点根目录路径.
        $basePath = trim($opts['basePath'], '/');
        if($basePath && $basePath === substr($uri, 0, strlen($basePath))){
            $uri = substr($uri, strlen($basePath));
            $uri = trim($uri, '/');
        }

        // no rewrite: {$opts['scriptName']}?$mod.$ctl.$act/$act_params/$key1:$val1/$key2:$val2[/...].$ext&$query#$fragment
        // rewrite: $mod.$ctl.$act/$act_params/$key1:$val1/$key2:$val2[/...].$ext?$query#$fragment

        // 去掉index.php?或index.php/
        if($uri && $opts['scriptName'] === substr($uri, 0, strlen($opts['scriptName']))){
            $uri = substr($uri, strlen($opts['scriptName']));
        }
        $uri = trim($uri, './?');

        if (!$uri) {
            // 首页
            $this->buildCtlClass();
            return $this;
        }

        // 将uri统一为：$mod.$ctl.$act/$act_params/$key1:$val1/$key2:$val2[/...].$ext&$query#fragment
        $uri && $uri = str_replace('?', '&', $uri);

        // 提取锚，并把锚串从uri中去掉
        if(false !== $pos = strpos($uri, '#')) {
            $this->anchor = substr($uri, $pos + 1);
            $uri = substr($uri, 0, $pos);
        }

        // 提取常规查询串参数，并把查询串从uri中去掉
        if (false !== $pos = strpos($uri, '&')) {
            $this->query = substr($uri, $pos + 1);
            $uri = substr($uri, 0, $pos);
        }

        // 去掉伪静态后缀
        if($opts['rewriteExt'] && $opts['rewriteExt'] === substr($uri,  - strlen($opts['rewriteExt']))) {
            $uri = substr($uri, 0,  - strlen($opts['rewriteExt']));
        }

        // URI解码
        if ($opts['encode'] && preg_match("/q_(.+)/", $uri, $mat)) {
            // base64编码的变体，+/字符使用方便URL中传输的-_字符
            $uri = base64_decode(strtr($mat[1], '-_', '+/'));
        }

        // /name:value 键值对变量
        if(preg_match_all("#/([^/&]+?\\:([^/&\\?]|$)*)#", $uri, $match)) {
            // 提取变量
            $attrStr = str_replace(':', '=', implode('&', $match[1]));
            parse_str($attrStr, $attributes);

            $this->attributes = $attributes;

            $uri = preg_replace("#/[^/&]+?\\:([^/&\\?]|$)*#", '', $uri);
        }

        // 请求参数
        $actArgs = explode("/", $uri);

        // 提取mod,ctl,act
        // 如果第一个/前只包含字母、数字、下划线和点符号，则是合法的路由ID
        if (!preg_match("/[^a-z0-9_\\.]+/i", $actArgs[0])) {
            $routeId = array_shift($actArgs);

            // $routeId没有.则可能是简化URL后的$route
            if (false === strpos($routeId, '.')) {
                // 简短url还原
                $routeKey = strtolower($routeId);
                if(array_key_exists($routeKey, $opts['alias'])) {
                    $routeId = $opts['alias'][$routeKey];
                    // $routeId中有 / 则需要重新取得$actArgs、$routeId参数
                    if (false !== stripos($routeId, '/')) {
                        array_unshift($actArgs, $routeId);
                        $actArgs = explode("/", implode('/', $actArgs));
                        $routeId = array_shift($actArgs);
                    }
                }
            }

            $routeArr = explode('.', $routeId);

            // 如果启用模块则提取模块，则提取第一个点号前面的模块名
            if ($opts['useModule']) {
                $this->mod = strtolower(array_shift($routeArr));
            }

            // 如果acttion不为空，则取最后一个点号后面的action名
            if(isset($routeArr[1])) {
                //
                $this->act = strtolower(array_pop($routeArr)); // else = defaultAct
            }

            // 取控制器类标识
            if ($routeArr) {
                $this->ctl = strtolower(join('.', $routeArr)); // else = defaultCtl
            }
        } // else mod = defaultMod

        // action参数
        $this->actParams = $actArgs;

        $this->buildCtlClass();

        return $this;
    }

    /**
     * {@inheritDoc}
     * @see \wf\route\RouteAbstract::toUrl()
     */
    public function toUrl($fullUrl = false)
    {
        $uri = trim("{$this->mod}.{$this->ctl}.{$this->act}", '.');
        if ($this->actParams) {
            $uri .= '/' . implode('/', $this->actParams);
        }
        $url = $this->buildUrL($uri, $this->attributes, $this->query, $this->anchor, $fullUrl);
        return $url;
    }

    /**
     * 生成URL
     * @param string $uri $mod.$ctl.$act/$act_params/$key1:$val1/$key2:$val2[/...]?$query#$fragment
     * @param array $vars = [] 是否生成完整URL，包含域名和根目录路径
     * @param bool $fullUrl = false 是否生成完整URL，包含域名和根目录路径
     * @return string
     */
    public function createUrl($uri, array $vars = [], $fullUrl = false)
    {
        // 构造URL： $mod.$ctl.$act/$act_params/$key1:$val1/$key2:$val2[/...].$ext?$query#$fragment
        $query = '';
        $fragment = '';

        // 提取锚，并把url中的锚去掉，构造好url后再添加上
        if(false !== $pos = strpos($uri, '#')) {
            $fragment = substr($uri, $pos + 1);
            $uri = substr($uri, 0, $pos);
        }

        // 提取查询串参数
        if(false !== $pos = strpos($uri, '?')) {
            $query = substr($uri, $pos + 1);
            $uri = substr($uri, 0, $pos);
        }

        $url = $this->buildUrL($uri, $vars, $query, $fragment, $fullUrl);

        return $url;
    }

    /**
     * 生成URL
     * @param string $uri  $mod.$ctl.$act/$act_params/$key1:$val1/$key2:$val2[/...]
     * @param array $vars = []  参数
     * @param string $query = '' 查询串
     * @param string $fragment = ''  锚点
     * @param bool $fullUrl = false 是否生成完整URL，包含域名和根目录路径
     * @return string
     */
    private function buildUrL($uri, array $vars = [], $query = '', $fragment = '', $fullUrl = false)
    {
        // 构造URL： $mod.$ctl.$act/$act_params/$key1:$val1/$key2:$val2[/...].$ext?$query#$fragment
        $url = trim($uri, '/');

        // URL简短化前从URL中获取mod,ctl
        $mod = '';
        $ctl = '';
        if (preg_match("/(.+?)\\.(.+)\\.(.+?)/", strtolower($url), $mat)) {
            $mod = $mat[1];
            $ctl = $mat[2];
        } elseif (preg_match("/(.+?)\\.(.+)/", strtolower($url), $mat)) {
            $ctl = $mat[1];
        }

        // URL简短化
        foreach ($this->cfg['alias'] as $shortTag => $rule) {
            $rule = trim($rule, '/');
            if (stripos($url.'/', $rule.'/') === 0) {
                $url = $shortTag . substr($url, strlen($rule));
                break;
            }
        }

        // 增加变量
        if (!empty($vars)) {
            $url .= '/' . str_replace("=", ':', http_build_query($vars, '', '/'));
        }

        // 对URL进行编码
        if ($this->cfg['encode']) {
            $url = 'q_' . strtr(base64_encode($url), '+/', '-_');
            $url = rtrim($url, '=');
        }

        // 加上伪静态后缀（不论是否启用URL Rewrite）
        $url && $url .= $this->cfg['rewriteExt'];

        // 未启用url重写，补充base url
        if(!$this->cfg['rewrite']) {
            $url = "{$this->cfg['scriptName']}?{$url}";
        }

        $modAndCtl = trim("{$mod}.{$ctl}", '.');

        if ($modAndCtl && isset($this->cfg['domain'][$modAndCtl])) {
            // 控制器指定域名
            $url = rtrim($this->cfg['basePath'], '/') . '/' . trim($url, '/');
            $url = rtrim($this->cfg['domain'][$modAndCtl], '/') . '/' . trim($url, '/');
        } elseif ($mod && isset($this->cfg['domain'][$mod])) {
            // 模块指定域名
            $url = rtrim($this->cfg['basePath'], '/') . '/' . trim($url, '/');
            $url = rtrim($this->cfg['domain'][$mod], '/') . '/' . trim($url, '/');
        } elseif ($fullUrl || $this->cfg['fullUrl']) {
            // 带域名的完整URL
            if ($this->cfg['siteUrl']) {
                $url = rtrim($this->cfg['siteUrl'], '/') . '/' . trim($url, '/');
            } else {
                $url = rtrim($this->cfg['basePath'], '/') . '/' . trim($url, '/');
                $url = rtrim($this->cfg['hostInfo'], '/') . '/' . trim($url, '/');
            }
        }

        // 查询串
        if (!empty($query)) {
            $url .= (strpos($url, '?') ? '&' : '?') . $query;
        }

        // 还原锚
        if (!empty($fragment)) {
            $url .= '#' . $fragment;
        }

        return $url;
    }

    /**
     * 根据mod、ctl属性生成控制器类名属性 ctlClass
     * 控制器类名命名规范：首字母大写，后面加上Controller，其它字母都是小写
     * @return string
     */
    protected function buildCtlClass()
    {
        $mod = $this->mod;
        $ctl = $this->ctl;

        if(empty($mod)) {
            // 不启用模块
            $ns = "\\app\\controller";
        } else {
            // 启用模块
            $ns = "\\app\\{$mod}\\controller";
        }

        if (strpos($ctl, '.')) {
            // 控制器类放在controller文件夹的子文件夹
            $name = substr($ctl, strrpos($ctl, '.') + 1);
            $subNS = substr($ctl, 0, strrpos($ctl, '.'));
            $ns .= '\\' . strtr($subNS, '.', '\\');
        } else {
            // 控制器类放在controller文件夹
            $name = $ctl;
        }

        $this->ctlClass = $ns . '\\' . ucfirst($name) . 'Controller';
    }

}


<?php

namespace BlogBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use BlogBundle\Entity\Comment;
use BlogBundle\Form\CommentType;
use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * Comment controller.
 *
 * @Route("/admin/post/comment")
 */
class CommentController extends Controller
{
    /**
     * Lists all Comment entities.
     *
     * @Route("/")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $comments = $em->getRepository('BlogBundle:Comment')->findAll();

        return array();
    }

    /**
     * Returns a list of Comment entities in JSON format.
     *
     * @return JsonResponse
     *
     * @Route("/list.{_format}", requirements={ "_format" = "json" }, defaults={ "_format" = "json" })
     * @Method("GET")
     */
    public function listJsonAction()
    {
        $em = $this->getDoctrine()->getManager();

        /** @var \Kitchenit\AdminBundle\Services\DataTables\JsonList $jsonList */
        $jsonList = $this->get('json_list');
        $jsonList->setRepository($em->getRepository('BlogBundle:Comment'));
        $response = $jsonList->get();

        return new JsonResponse($response);
    }

    /**
     * Creates a new Comment entity.
     *
     * @Route("/new")
     * @Method({"GET", "POST"})
     * @Template()
     */
    public function newAction(Request $request)
    {
        $comment = new Comment();
        $form = $this->createForm('BlogBundle\Form\CommentType', $comment);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($comment);
            $em->flush();

            $this->get('session')->getFlashBag()->add('success', 'comment.created');

            return $this->redirectToRoute('blog_comment_show', array('id' => $comment->getId()));
        }

        return array(
            'entity' => $comment,
            'form' => $form->createView(),
        );
    }

    /**
     * Finds and displays a Comment entity.
     *
     * @Route("/{id}")
     * @Method("GET")
     * @Template()
     */
    public function showAction(Comment $comment)
    {
        $deleteForm = $this->createDeleteForm($comment);

        return array(
            'entity' => $comment,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to edit an existing Comment entity.
     *
     * @Route("/{id}/edit")
     * @Method({"GET", "POST"})
     * @Template()
     */
    public function editAction(Request $request, Comment $comment)
    {
        $deleteForm = $this->createDeleteForm($comment);
        $editForm = $this->createForm('BlogBundle\Form\CommentType', $comment);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($comment);
            $em->flush();

            $this->get('session')->getFlashBag()->add('success', 'comment.edited');

            return $this->redirectToRoute('blog_comment_show', array('id' => $comment->getId()));
        }

        return array(
            'entity' => $comment,
            'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Deletes a Comment entity.
     *
     * @Route("/{id}")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, Comment $comment)
    {
        $form = $this->createDeleteForm($comment);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($comment);
            $em->flush();

            $this->get('session')->getFlashBag()->add('info', 'comment.deleted');
        }

        return $this->redirectToRoute('blog_comment_index');
    }

    /**
     * Creates a form to delete a Comment entity.
     *
     * @param Comment $comment The Comment entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(Comment $comment)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('blog_comment_delete', array('id' => $comment->getId())))
            ->setMethod('DELETE')
            ->getForm()
        ;
    }
}


<?php

/*
 * This file is part of the Predis package.
 *
 * (c) Daniele Alessandri <suppakilla@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Predis\Cluster;

/**
 * Slot map for redis-cluster.
 */
class SlotMap implements \ArrayAccess, \IteratorAggregate, \Countable
{
    private $slots = array();

    /**
     * Checks if the given slot is valid.
     *
     * @param int $first Slot index.
     *
     * @return bool
     */
    public static function isValid($slot)
    {
        return $slot >= 0x0000 && $slot <= 0x3FFF;
    }

    /**
     * Checks if the given slot range is valid.
     *
     * @param int $first Initial slot of the range.
     * @param int $last  Last slot of the range.
     *
     * @return bool
     */
    public static function isValidRange($first, $last)
    {
        return $first >= 0x0000 && $first <= 0x3FFF && $last >= 0x0000 && $last <= 0x3FFF && $first <= $last;
    }

    /**
     * Resets the slot map.
     */
    public function reset()
    {
        $this->slots = array();
    }

    /**
     * Checks if the slot map is empty.
     *
     * @return bool
     */
    public function isEmpty()
    {
        return empty($this->slots);
    }

    /**
     * Returns the current slot map as a dictionary of $slot => $node.
     *
     * The order of the slots in the dictionary is not guaranteed.
     *
     * @return array
     */
    public function toArray()
    {
        return $this->slots;
    }

    /**
     * Returns the list of unique nodes in the slot map.
     *
     * @return array
     */
    public function getNodes()
    {
        return array_keys(array_flip($this->slots));
    }

    /**
     * Assigns the specified slot range to a node.
     *
     * @param int                            $first      Initial slot of the range.
     * @param int                            $last       Last slot of the range.
     * @param NodeConnectionInterface|string $connection ID or connection instance.
     *
     * @throws \OutOfBoundsException
     */
    public function setSlots($first, $last, $connection)
    {
        if (!static::isValidRange($first, $last)) {
            throw new \OutOfBoundsException("Invalid slot range $first-$last for `$connection`");
        }

        $this->slots += array_fill($first, $last - $first + 1, (string) $connection);
    }

    /**
     * Returns the specified slot range.
     *
     * @param int $first Initial slot of the range.
     * @param int $last  Last slot of the range.
     *
     * @return array
     */
    public function getSlots($first, $last)
    {
        if (!static::isValidRange($first, $last)) {
            throw new \OutOfBoundsException("Invalid slot range $first-$last");
        }

        return array_intersect_key($this->slots, array_fill($first, $last - $first + 1, null));
    }

    /**
     * Checks if the specified slot is assigned.
     *
     * @param int $slot Slot index.
     *
     * @return bool
     */
    public function offsetExists($slot)
    {
        return isset($this->slots[$slot]);
    }

    /**
     * Returns the node assigned to the specified slot.
     *
     * @param int $slot Slot index.
     *
     * @return string
     */
    public function offsetGet($slot)
    {
        if (isset($this->slots[$slot])) {
            return $this->slots[$slot];
        }
    }

    /**
     * Assigns the specified slot to a node.
     *
     * @param int                            $slot       Slot index.
     * @param NodeConnectionInterface|string $connection ID or connection instance.
     *
     * @return string
     */
    public function offsetSet($slot, $connection)
    {
        if (!static::isValid($slot)) {
            throw new \OutOfBoundsException("Invalid slot $slot for `$connection`");
        }

        $this->slots[(int) $slot] = (string) $connection;
    }

    /**
     * Returns the node assigned to the specified slot.
     *
     * @param int $slot Slot index.
     *
     * @return string
     */
    public function offsetUnset($slot)
    {
        unset($this->slots[$slot]);
    }

    /**
     * Returns the current number of assigned slots.
     *
     * @return int
     */
    public function count()
    {
        return count($this->slots);
    }

    /**
     * Returns an iterator over the slot map.
     *
     * @return \ArrayIterator
     */
    public function getIterator()
    {
        return new \ArrayIterator($this->slots);
    }
}


<?php

/*
 * This file is part of the overtrue/wechat.
 *
 * (c) overtrue <i@overtrue.me>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

/**
 * Guard.php.
 *
 * @author    overtrue <i@overtrue.me>
 * @copyright 2015 overtrue <i@overtrue.me>
 *
 * @see      https://github.com/overtrue
 * @see      http://overtrue.me
 */

namespace EasyWeChat\Server;

use EasyWeChat\Core\Exceptions\FaultException;
use EasyWeChat\Core\Exceptions\InvalidArgumentException;
use EasyWeChat\Core\Exceptions\RuntimeException;
use EasyWeChat\Encryption\Encryptor;
use EasyWeChat\Message\AbstractMessage;
use EasyWeChat\Message\Raw as RawMessage;
use EasyWeChat\Message\Text;
use EasyWeChat\Support\Collection;
use EasyWeChat\Support\Log;
use EasyWeChat\Support\XML;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Class Guard.
 */
class Guard
{
    /**
     * Empty string.
     */
    const SUCCESS_EMPTY_RESPONSE = 'success';

    const TEXT_MSG = 2;
    const IMAGE_MSG = 4;
    const VOICE_MSG = 8;
    const VIDEO_MSG = 16;
    const SHORT_VIDEO_MSG = 32;
    const LOCATION_MSG = 64;
    const LINK_MSG = 128;
    const DEVICE_EVENT_MSG = 256;
    const DEVICE_TEXT_MSG = 512;
    const EVENT_MSG = 1048576;
    const ALL_MSG = 1049598;

    /**
     * @var Request
     */
    protected $request;

    /**
     * @var string
     */
    protected $token;

    /**
     * @var Encryptor
     */
    protected $encryptor;

    /**
     * @var string|callable
     */
    protected $messageHandler;

    /**
     * @var int
     */
    protected $messageFilter;

    /**
     * @var array
     */
    protected $messageTypeMapping = [
        'text' => 2,
        'image' => 4,
        'voice' => 8,
        'video' => 16,
        'shortvideo' => 32,
        'location' => 64,
        'link' => 128,
        'device_event' => 256,
        'device_text' => 512,
        'event' => 1048576,
    ];

    /**
     * @var bool
     */
    protected $debug = false;

    /**
     * Constructor.
     *
     * @param string  $token
     * @param Request $request
     */
    public function __construct($token, Request $request = null)
    {
        $this->token = $token;
        $this->request = $request ?: Request::createFromGlobals();
    }

    /**
     * Enable/Disable debug mode.
     *
     * @param bool $debug
     *
     * @return $this
     */
    public function debug($debug = true)
    {
        $this->debug = $debug;

        return $this;
    }

    /**
     * Handle and return response.
     *
     * @return Response
     *
     * @throws BadRequestException
     */
    public function serve()
    {
        Log::debug('Request received:', [
            'Method' => $this->request->getMethod(),
            'URI' => $this->request->getRequestUri(),
            'Query' => $this->request->getQueryString(),
            'Protocal' => $this->request->server->get('SERVER_PROTOCOL'),
            'Content' => $this->request->getContent(),
        ]);

        $this->validate($this->token);

        if ($str = $this->request->get('echostr')) {
            Log::debug("Output 'echostr' is '$str'.");

            return new Response($str);
        }

        $result = $this->handleRequest();

        $response = $this->buildResponse($result['to'], $result['from'], $result['response']);

        Log::debug('Server response created:', compact('response'));

        return new Response($response);
    }

    /**
     * Validation request params.
     *
     * @param string $token
     *
     * @throws FaultException
     */
    public function validate($token)
    {
        $params = [
            $token,
            $this->request->get('timestamp'),
            $this->request->get('nonce'),
        ];

        if (!$this->debug && $this->request->get('signature') !== $this->signature($params)) {
            throw new FaultException('Invalid request signature.', 400);
        }
    }

    /**
     * Add a event listener.
     *
     * @param callable $callback
     * @param int      $option
     *
     * @return Guard
     *
     * @throws InvalidArgumentException
     */
    public function setMessageHandler($callback = null, $option = self::ALL_MSG)
    {
        if (!is_callable($callback)) {
            throw new InvalidArgumentException('Argument #2 is not callable.');
        }

        $this->messageHandler = $callback;
        $this->messageFilter = $option;

        return $this;
    }

    /**
     * Return the message listener.
     *
     * @return string
     */
    public function getMessageHandler()
    {
        return $this->messageHandler;
    }

    /**
     * Request getter.
     *
     * @return Request
     */
    public function getRequest()
    {
        return $this->request;
    }

    /**
     * Request setter.
     *
     * @param Request $request
     *
     * @return $this
     */
    public function setRequest(Request $request)
    {
        $this->request = $request;

        return $this;
    }

    /**
     * Set Encryptor.
     *
     * @param Encryptor $encryptor
     *
     * @return Guard
     */
    public function setEncryptor(Encryptor $encryptor)
    {
        $this->encryptor = $encryptor;

        return $this;
    }

    /**
     * Return the encryptor instance.
     *
     * @return Encryptor
     */
    public function getEncryptor()
    {
        return $this->encryptor;
    }

    /**
     * Build response.
     *
     * @param $to
     * @param $from
     * @param mixed $message
     *
     * @return string
     *
     * @throws \EasyWeChat\Core\Exceptions\InvalidArgumentException
     */
    protected function buildResponse($to, $from, $message)
    {
        if (empty($message) || $message === self::SUCCESS_EMPTY_RESPONSE) {
            return self::SUCCESS_EMPTY_RESPONSE;
        }

        if ($message instanceof RawMessage) {
            return $message->get('content', self::SUCCESS_EMPTY_RESPONSE);
        }

        if (is_string($message) || is_numeric($message)) {
            $message = new Text(['content' => $message]);
        }

        if (!$this->isMessage($message)) {
            $messageType = gettype($message);
            throw new InvalidArgumentException("Invalid Message type .'{$messageType}'");
        }

        $response = $this->buildReply($to, $from, $message);

        if ($this->isSafeMode()) {
            Log::debug('Message safe mode is enable.');
            $response = $this->encryptor->encryptMsg(
                $response,
                $this->request->get('nonce'),
                $this->request->get('timestamp')
            );
        }

        return $response;
    }

    /**
     * Whether response is message.
     *
     * @param mixed $message
     *
     * @return bool
     */
    protected function isMessage($message)
    {
        if (is_array($message)) {
            foreach ($message as $element) {
                if (!is_subclass_of($element, AbstractMessage::class)) {
                    return false;
                }
            }

            return true;
        }

        return is_subclass_of($message, AbstractMessage::class);
    }

    /**
     * Get request message.
     *
     * @return array
     *
     * @throws BadRequestException
     */
    public function getMessage()
    {
        $message = $this->parseMessageFromRequest($this->request->getContent(false));

        if (!is_array($message) || empty($message)) {
            throw new BadRequestException('Invalid request.');
        }

        return $message;
    }

    /**
     * Handle request.
     *
     * @return array
     *
     * @throws \EasyWeChat\Core\Exceptions\RuntimeException
     * @throws \EasyWeChat\Server\BadRequestException
     */
    protected function handleRequest()
    {
        $message = $this->getMessage();
        $response = $this->handleMessage($message);

        return [
            'to' => $message['FromUserName'],
            'from' => $message['ToUserName'],
            'response' => $response,
        ];
    }

    /**
     * Handle message.
     *
     * @param array $message
     *
     * @return mixed
     */
    protected function handleMessage(array $message)
    {
        $handler = $this->messageHandler;

        if (!is_callable($handler)) {
            Log::debug('No handler enabled.');

            return null;
        }

        Log::debug('Message detail:', $message);

        $message = new Collection($message);

        $type = $this->messageTypeMapping[$message->get('MsgType')];

        $response = null;

        if ($this->messageFilter & $type) {
            $response = call_user_func_array($handler, [$message]);
        }

        return $response;
    }

    /**
     * Build reply XML.
     *
     * @param string          $to
     * @param string          $from
     * @param AbstractMessage $message
     *
     * @return string
     */
    protected function buildReply($to, $from, $message)
    {
        $base = [
            'ToUserName' => $to,
            'FromUserName' => $from,
            'CreateTime' => time(),
            'MsgType' => is_array($message) ? current($message)->getType() : $message->getType(),
        ];

        $transformer = new Transformer();

        return XML::build(array_merge($base, $transformer->transform($message)));
    }

    /**
     * Get signature.
     *
     * @param array $request
     *
     * @return string
     */
    protected function signature($request)
    {
        sort($request, SORT_STRING);

        return sha1(implode($request));
    }

    /**
     * Parse message array from raw php input.
     *
     * @param string|resource $content
     *
     * @throws \EasyWeChat\Core\Exceptions\RuntimeException
     * @throws \EasyWeChat\Encryption\EncryptionException
     *
     * @return array
     */
    protected function parseMessageFromRequest($content)
    {
        $content = strval($content);

        $dataSet = json_decode($content, true);
        if ($dataSet && (JSON_ERROR_NONE === json_last_error())) {
            // For mini-program JSON formats.
            // Convert to XML if the given string can be decode into a data array.
            $content = XML::build($dataSet);
        }

        if ($this->isSafeMode()) {
            if (!$this->encryptor) {
                throw new RuntimeException('Safe mode Encryptor is necessary, please use Guard::setEncryptor(Encryptor $encryptor) set the encryptor instance.');
            }

            $message = $this->encryptor->decryptMsg(
                $this->request->get('msg_signature'),
                $this->request->get('nonce'),
                $this->request->get('timestamp'),
                $content
            );
        } else {
            $message = XML::parse($content);
        }

        return $message;
    }

    /**
     * Check the request message safe mode.
     *
     * @return bool
     */
    private function isSafeMode()
    {
        return $this->request->get('encrypt_type') && $this->request->get('encrypt_type') === 'aes';
    }
}


<?php

declare(strict_types=1);

namespace Ruwork\RunetIdBundle\Basket\Form;

use RunetId\Client\Exception\RunetIdException;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\PropertyAccess\Exception\RuntimeException;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;

final class FormErrorsMapper implements FormErrorsMapperInterface
{
    private const PREFIX = 'ruwork_runet_id.form_errors.';

    private $session;
    private $accessor;

    public function __construct(SessionInterface $session, ?PropertyAccessorInterface $accessor = null)
    {
        $this->session = $session;
        $this->accessor = $accessor ?? PropertyAccess::createPropertyAccessor();
    }

    /**
     * {@inheritdoc}
     */
    public function save(string $id, $object, $map): void
    {
        if (\is_callable($map)) {
            $map = $map();
        }

        if (!is_iterable($map)) {
            throw new \InvalidArgumentException('Map must be iterable or a callback, returning an iterable value.');
        }

        $data = [];

        foreach ($map as $source => $target) {
            $exception = $this->accessor->getValue($object, $source);

            if (null === $exception) {
                continue;
            }

            if (!$exception instanceof RunetIdException) {
                throw new \UnexpectedValueException(sprintf('Expected null or an instance of "%s".', RunetIdException::class));
            }

            $data[] = [$target, $exception->getMessage()];
        }

        $id = self::PREFIX.$id;
        $this->session->set($id, $data);
    }

    /**
     * {@inheritdoc}
     */
    public function apply(string $id, FormInterface $form): void
    {
        $id = self::PREFIX.$id;
        $data = $this->session->get($id, []);
        $this->session->remove($id);

        foreach ($data as [$target, $message]) {
            try {
                $target = $this->accessor->getValue($form, $target);
            } catch (RuntimeException $exception) {
                continue;
            }

            if ($target instanceof FormInterface) {
                $target->addError(new FormError($message));
            }
        }
    }
}


<?php

/**
 * Manage Cache by Memory
 *
 * @category  	lib
 * @package		lib\Cache
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */
namespace Venus\lib\Cache;
use \Venus\lib\Cache\CacheInterface;

/**
 * This class manage the Cache by Memory
 *
 * @category  	lib
 * @package		lib\Cache
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */
class Memory implements CacheInterface
{
    /**
     * A static variable to keep the cache
     * @var array
     */
    private static $_aMemories = array();

	/**
	 * set a value
	 *
	 * @access public
	 * @param  string $sName name of the session
	 * @param  mixed $mValue value of this sesion var
	 * @param  int $iFlag unused
	 * @param  int $iExpire expiration of cache
	 * @return \Venus\lib\Cache\Apc
	 */
	public function set(string $sName, $mValue, int $iFlag = 0, int $iExpire = 0)
	{
		self::$_aMemories[$sName] = $mValue;
		return $this;
	}

	/**
	 * get a value
	 *
	 * @access public
	 * @param  string $sName name of the session
	 * @param  int $iFlags flags
	 * @param  int $iTimeout expiration of cache
	 * @return mixed
	 */
	public function get(string $sName, int &$iFlags = null, int $iTimeout = 0)
	{
		return self::$_aMemories[$sName];
	}

	/**
	 * delete a value
	 *
	 * @access public
	 * @param  string $sName name of the session
	 * @return true
	 */
	public function delete(string $sName)
	{
		unset(self::$_aMemories[$sName]);
		return true;
	}

	/**
	 * flush the cache
	 *
	 * @access public
	 * @return mixed
	 */
	public function flush()
	{
		return self::$_aMemories = array();
	}
}


<?php
namespace eMacros;

use eMacros\Exception\ParseException;

class Parser {
	/**
	 * Validated symbols
	 * @var array
	 */
	public static $map = [];

	/*
	 * SYMBOL REGEX
	 */
	const PARENTHESES = '()';
	const COMMENT_PREFIX = ';';
	const WHITESPACES = " \t\n\r\f\v\0";

	/**
	 * Float validation regex
	 * @var string
	 */
	const REAL_PATTERN = '{^[+-]?((\d+|(\d*\.\d+|\d+\.\d*))e[+-]?\d+|\d*\.\d+|\d+\.\d*)}i';

	/**
	 * Integer validation regex
	 * @var unknown
	 */
	const INTEGER_PATTERN = '/^([+-]?)(0x([0-9a-f]+)|0([0-7]+)|[1-9]\d*|0)/i';

	/**
	 * String validation regex
	 * @var string
	 */
	const STRING_PATTERN = '/^"([^"\\\\]|\\\\.)*"|^\'([^\'\\\\]|\\\\.)*\'/';

	/**
	 * Escape string replacement regex
	 * @var string
	 */
    const STRING_ESCAPE_PATTERN = '/\\\\(([0-7]{1,3})|x([0-9A-Fa-f]{1,2})|.)/';

    /**
     * Symbol validation regex
     * @var string
     */
    const SYMBOL_PATTERN = '{^[^\s\d(){}\[\]"\';][^\s\'"(){}\[\];]*}';

    /**
     * Parses a program
     * @param string $program
     * @throws ParseException
     * @return \eMacros\GenericList
     */
	public static function parse($program) {
		$i = 0;
		$len = strlen($program);
		$forms = [];

		while ($i < $len) {
			if (strpos(self::WHITESPACES, $program[$i]) === false) {
				try {
					$form = self::parseExpression(substr($program, $i), $offset);
					if (!is_null($form)) $forms[] = $form;
 				}
 				catch (ParseException $e) {
 					throw new ParseException($program, $e->offset + $i);
 				}

				$i += $offset;
			}
			else
				++$i;
		}

		return $forms;
	}

	/**
	 * Parses an inner expression
	 * @param string $form
	 * @param int $offset
	 * @throws ParseException
	 * @return mixed
	 */
	public static function parseExpression($form, &$offset) {
		static $parentheses = null;

		if (is_null($parentheses)) {
			$_parentheses = self::PARENTHESES;
			$parentheses = [];

			for ($i = 0, $len = strlen($_parentheses); $i < $len; $i += 2)
				$parentheses[$_parentheses[$i]] = $_parentheses[$i + 1];

			unset($_parentheses);
		}

		if (isset($form[0], $parentheses[$form[0]])) {
			$end = $parentheses[$form[0]];
			$values = [];
			$i = 1;
			$len = strlen($form);

			while ($i < $len && $form[$i] != $end) {
				if (strpos(self::WHITESPACES, $form[$i]) !== false) {
					++$i;
					continue;
				}

				try {
					$values[] = self::parseExpression(substr($form, $i), $_offset);
					$i += $_offset;
				}
 				catch (ParseException $e) {
 					throw new ParseException($form, $i + $e->offset);
 				}
			}

			if (isset($form[$i]) && $form[$i] == $end) {
				$offset = $i + 1;
				return new GenericList($values);
			}

			throw new ParseException($form, $i);
		}
		elseif (isset($form[0]) && $form[0] == self::COMMENT_PREFIX) {
			$offset = strlen(strtok($form, "\n"));
			return;
		}
		elseif (preg_match(self::REAL_PATTERN, $form, $matches)) {
			$offset = strlen($matches[0]);
			return new Literal((float) $matches[0]);
		}
		elseif (preg_match(self::INTEGER_PATTERN, $form, $matches)) {
			$offset = strlen($matches[0]);
			$sign = $matches[1] == '-' ? -1 : 1;
			$value = !empty($matches[3]) ? hexdec($matches[3]) : (!empty($matches[4]) ? octdec($matches[4]) : $matches[2]);
			return new Literal($sign * $value);
		}
		elseif (preg_match(self::STRING_PATTERN, $form, $matches)) {
			list($parsed) = $matches;
			$offset = strlen($parsed);
			return new Literal(preg_replace_callback(self::STRING_ESCAPE_PATTERN, [__CLASS__, 'unescapeString'], substr($parsed, 1, -1)));
		}
		elseif (preg_match(self::SYMBOL_PATTERN, $form, $matches)) {
			$symbol = $matches[0];
			$offset = strlen($matches[0]);

			//store validated symbols in order to reduce checks
			if (array_key_exists($symbol, self::$map))
				return self::$map[$symbol];

			return self::$map[$symbol] = new Symbol($symbol);
		}

		throw new ParseException($form, 0);
	}

	/**
	 * Replaces special characters in a string
	 * @param array $matches
	 * @return string
	 */
	protected static function unescapeString($matches) {
		static $map = ['n' => "\n", 'r' => "\r", 't' => "\t", 'v' => "\v", 'f' => "\f"];

		if (!empty($matches[2]))
			return chr(octdec($matches[2]));
		elseif (!empty($matches[3]))
			return chr(hexdec($matches[3]));
		elseif (isset($map[$matches[1]]))
			return $map[$matches[1]];

		return $matches[1];
	}

	/**
	 * Flushes validated symbols table
	 */
	public static function flush() {
		self::$map = [];
	}
}
?>


<?php
namespace asbamboo\di;

use asbamboo\di\exception\ServiceMappingException;
use PHPUnit\Framework\MockObject\Matcher\AnyParameters;

/**
 * 容器[container]的服务配置信息的一个单元 [asbamboo\di\ServiceMappingInterface]的实现
 * @author 李春寅 <licy2013@aliyun.com>
 * @since 2018年3月15日
 */
class ServiceMapping implements ServiceMappingInterface
{
    /**
     * 一个服务的唯一标识符
     * @var string
     */
    protected $id;

    /**
     * 一个服务的类名
     * @var string
     */
    protected $class;

    /**
     * @var AnyParameters
     */
    protected $init_params;

    /**
     * @param array $option
     */
    public function __construct(array $option)
    {
        foreach($option as $prop => $value){
            if(property_exists($this, $prop)){
                $this->{$prop}  = $value;
            }
        }
    }

    /**
     * {@inheritDoc}
     * @see \asbamboo\di\ServiceMappingInterface::getClass()
     */
    public function getClass(): string
    {
        if(empty($this->class)){
            throw new ServiceMappingException(sprintf('容器[container]的服务配置信息，必须设置类名[class name][%s]。', $this->id));
        }
        return $this->class;
    }

    /**
     * {@inheritDoc}
     * @see \asbamboo\di\ServiceMappingInterface::getInitParams()
     */
    public function getInitParams(): array
    {
        return (array) $this->init_params;
    }

    /**
     * {@inheritDoc}
     * @see \asbamboo\di\ServiceMappingInterface::getId()
     */
    public function getId(): string
    {
        if(!$this->id){
            $this->id   = $this->getClass();
        }
        return $this->id;
    }
}


<?php
/**
 * HasParent trait assigns parent to a class.
 *
 * @license https://www.gnu.org/licenses/gpl-3.0.en.html GPL-3.0
 * @author deMagog <seotils@gmail.com>
 *
 */

namespace Seotils\Traits;

use Seotils\Traits\DeferredExceptions;

/**
 * Assigns parent to a class.
 */
trait HasParent {

  use DeferredExceptions;

  /**
   * Instance of the parent class
   * @var mixed
   */
  protected $traitHasParentClass;

  /**
   * Parent class getter/setter
   *
   * @param mixed $parentClass Parent class instance
   * @return mixed Parent class
   */
  public function parentClass( $parentClass = 'undefined') {
    if( 'undefined' !== $parentClass ){
      if( ! is_object( $parentClass)){
        $this->exception('Invalid instance of a parent class.');
      } else {
        $this->traitHasParentClass = $parentClass;
      }
    }
    return $this->traitHasParentClass;
  }

}


<?php

namespace Dothiv\Bundle\ContentfulBundle\Adapter;

use Doctrine\Common\Collections\ArrayCollection;
use Dothiv\Bundle\ContentfulBundle\Item\ContentfulAsset;
use Dothiv\Bundle\ContentfulBundle\Item\ContentfulContentType;
use Dothiv\Bundle\ContentfulBundle\Item\ContentfulEntry;
use Dothiv\Bundle\ContentfulBundle\Item\DeletedContentfulEntry;

class ContentfulEntityReader
{
    /**
     * @var string
     */
    private $spaceId;

    /**
     * @var ContentfulContentType[]|ArrayCollection
     */
    private $contentTypes;

    /**
     * @param string                                  $spaceId
     * @param ContentfulContentType[]|ArrayCollection $contentTypes
     */
    public function __construct($spaceId, ArrayCollection $contentTypes)
    {
        $this->spaceId      = $spaceId;
        $this->contentTypes = $contentTypes;
    }

    /**
     * @param \stdClass $data
     *
     * @return ContentfulAsset|ContentfulEntry|null
     */
    public function getEntry(\stdClass $data)
    {
        $postFill = function () {
        };
        switch ($data->sys->type) {
            case 'Entry':
                /** @var ContentfulContentType $contentType */
                $contentType = $this->contentTypes->get($data->sys->contentType->sys->id);
                $entry       = new ContentfulEntry();
                $entry->setContentTypeId($contentType->getId());
                $postFill = function () use ($contentType, $entry) {
                    $contentType->updateEntryName($entry);
                };
                break;
            case 'Asset':
                $entry = new ContentfulAsset();
                break;
            case 'DeletedEntry':
                $entry = new DeletedContentfulEntry();
                break;
            default:
                return null;
        }

        $entry->setId($data->sys->id);
        $entry->setRevision($data->sys->revision);
        $entry->setSpaceId($this->spaceId);
        $entry->setCreatedAt(new \DateTime($data->sys->createdAt));
        $entry->setUpdatedAt(new \DateTime($data->sys->updatedAt));

        if (property_exists($data, 'fields')) {
            foreach ($data->fields as $k => $field) {
                if (is_array($field)) {
                    $fieldValue = array();
                    foreach ($field as $subItem) {
                        $fieldValue[] = $this->getEntry($subItem);
                    }
                    $entry->$k = $fieldValue;
                } else if (is_object($field) && property_exists($field, 'sys')) {
                    $entry->$k = $this->getEntry($field);
                } else {
                    $entry->$k = $field;
                }
            }
        }

        $postFill();

        return $entry;
    }
}


<?php

namespace Maba\OAuthCommerceAccountsClient;

use Guzzle\Service\Client;
use Maba\OAuthCommerceAccountsClient\DependencyInjection\AccountsClientExtension;
use Maba\OAuthCommerceClient\AuthClientFactory;
use Maba\OAuthCommerceClient\CodeGrantHandler;
use Maba\OAuthCommerceClient\DependencyInjection\BaseClientExtension;
use Maba\OAuthCommerceClient\Entity\SignatureCredentials;
use Maba\OAuthCommerceClient\MacSignature\AlgorithmManager;
use Maba\OAuthCommerceClient\Plugin\MacSignatureProvider;
use Maba\OAuthCommerceClient\Random\RandomProviderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;

class AccountsApiFactory
{
    const DEFAULT_ENDPOINT = 'https://accounts.maba.lt';

    protected $authFactory;
    protected $accountsFactory;
    protected $algorithmManager;
    protected $randomProvider;

    public function __construct(
        AuthClientFactory $authFactory,
        AccountsClientFactory $accountsFactory,
        AlgorithmManager $algorithmManager,
        RandomProviderInterface $randomProvider
    ) {
        $this->authFactory = $authFactory;
        $this->accountsFactory = $accountsFactory;
        $this->algorithmManager = $algorithmManager;
        $this->randomProvider = $randomProvider;
    }

    /**
     * @param SignatureCredentials|array $signatureCredentials
     * @param string|null                $baseUrl
     * @param array                      $config
     *
     * @return AccountsApi
     */
    public function createApi($signatureCredentials, $baseUrl = self::DEFAULT_ENDPOINT, $config = array())
    {
        if (!$signatureCredentials instanceof SignatureCredentials) {
            $signatureCredentials = $this->algorithmManager->createSignatureCredentials($signatureCredentials);
        }

        $authUrl = isset($config['base_auth_url']) ? $config['base_auth_url'] : $baseUrl . '/api/auth/v1';
        $accountsUrl = isset($config['base_accounts_url'])
            ? $config['base_accounts_url']
            : $baseUrl . '/api/accounts/v1';
        $oauthEndpointUrl = isset($config['oauth_endpoint'])
            ? $config['oauth_endpoint']
            : $baseUrl . '/confirm';

        return new AccountsApi(
            $this->authFactory->createClient($signatureCredentials, $authUrl, $config),
            $this->accountsFactory->createClient($signatureCredentials, $accountsUrl, $config),
            new CodeGrantHandler($this->randomProvider, $signatureCredentials->getMacId(), $oauthEndpointUrl)
        );
    }

    public static function loadContainer(array $parameters = array(), $compile = true)
    {
        $container = new ContainerBuilder(new ParameterBag($parameters));
        $container->setResourceTracking(false); // this is not needed if cache is not used, also it requires Config

        $extension = new BaseClientExtension();
        $container->registerExtension($extension);
        $container->loadFromExtension($extension->getAlias());
        $extension->addCompilerPasses($container);
        $extension = new AccountsClientExtension();
        $container->registerExtension($extension);
        $container->loadFromExtension($extension->getAlias());

        if ($compile) {
            $container->compile();
        }
        return $container;
    }

}


<?php
/**
 * @link http://psesd.org/
 *
 * @copyright Copyright (c) 2015 Puget Sound ESD
 * @license http://psesd.org/license/
 */

namespace cascade\components\db\behaviors;

use Yii;

/**
 * QueryFamiliarity [[@doctodo class_description:cascade\components\db\behaviors\QueryFamiliarity]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class QueryFamiliarity extends \canis\db\behaviors\QueryBehavior
{
    /**
     * [[@doctodo method_description:withFamiliarity]].
     *
     * @return \yii\db\ActiveRelation
     */
    public function withFamiliarity()
    {
        if (empty(Yii::$app->user->id)) {
            return;
        }
        $familiarityModelClass = Yii::$app->classes['ObjectFamiliarity'];
        $familiartyTable = $familiarityModelClass::tableName();
        $params = [];
        $where = ['and'];
        $where[] = $this->owner->primaryAlias . '.' . $this->owner->primaryTablePk . ' = ft.object_id';
        $where[] = 'ft.user_id = :user_id';
        $params[':user_id'] = Yii::$app->user->id;
        $this->owner->join('LEFT JOIN', $familiartyTable . ' ft', $where, $params);
    }
}


<?php
namespace app\manage\block;

class DateBlock extends Block
{

    /**
     * form
     *
     * @param array $data
     * @return string
     */
    public static function form($data = [])
    {
        if (isset($data['format']) && ! empty($data['format'])) {
            $data['attr'] = 'data-am-datepicker="{format: \'' . $data['format'] . '\'}"';
        } else {
            $data['attr'] = 'data-am-datepicker';
        }

        return TextBlock::form($data);
    }

    /**
     * search
     *
     * @param array $data
     * @return string
     */
    public static function search($data = [])
    {
        if (isset($data['format']) && ! empty($data['format'])) {
            $data['attr'] = 'data-am-datepicker="{format: \'' . $data['format'] . '\'}"';
        } else {
            $data['attr'] = 'data-am-datepicker';
        }

        return TextBlock::search($data);
    }
}


<?php

/*
 * This file is part of the Dektrium project.
 *
 * (c) Dektrium project <http://github.com/dektrium/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace dektrium\user\controllers;

use dektrium\user\Finder;
use dektrium\user\models\RecoveryForm;
use dektrium\user\models\Token;
use yii\base\Model;
use yii\web\Controller;
use yii\filters\AccessControl;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\widgets\ActiveForm;

/**
 * RecoveryController manages password recovery process.
 *
 * @property \dektrium\user\Module $module
 *
 * @author Dmitry Erofeev <dmeroff@gmail.com>
 */
class RecoveryController extends Controller
{
    /** @var Finder */
    protected $finder;

    /**
     * @param string           $id
     * @param \yii\base\Module $module
     * @param Finder           $finder
     * @param array            $config
     */
    public function __construct($id, $module, Finder $finder, $config = [])
    {
        $this->finder = $finder;
        parent::__construct($id, $module, $config);
    }

    /** @inheritdoc */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    ['allow' => true, 'actions' => ['request', 'reset'], 'roles' => ['?']],
                ]
            ],
        ];
    }

    /**
     * Shows page where user can request password recovery.
     * @return string
     * @throws \yii\web\NotFoundHttpException
     */
    public function actionRequest()
    {
        if (!$this->module->enablePasswordRecovery) {
            throw new NotFoundHttpException;
        }

        $model = \Yii::createObject([
            'class'    => RecoveryForm::className(),
            'scenario' => 'request',
        ]);

        $this->performAjaxValidation($model);

        if ($model->load(\Yii::$app->request->post()) && $model->sendRecoveryMessage()) {
            return $this->render('/message', [
                'title'  => \Yii::t('user', 'Recovery message sent'),
                'module' => $this->module,
            ]);
        }

        return $this->render('request', [
            'model' => $model,
        ]);
    }

    /**
     * Displays page where user can reset password.
     * @param  integer $id
     * @param  string  $code
     * @return string
     * @throws \yii\web\NotFoundHttpException
     */
    public function actionReset($id, $code)
    {
        if (!$this->module->enablePasswordRecovery) {
            throw new NotFoundHttpException;
        }

        /** @var Token $token */
        $token = $this->finder->findToken(['user_id' => $id, 'code' => $code, 'type' => Token::TYPE_RECOVERY])->one();

        if ($token === null || $token->isExpired || $token->user === null) {
            \Yii::$app->session->setFlash('danger', \Yii::t('user', 'Recovery link is invalid or expired. Please try requesting a new one.'));
            return $this->render('/message', [
                'title'  => \Yii::t('user', 'Invalid or expired link'),
                'module' => $this->module,
            ]);
        }

        $model = \Yii::createObject([
            'class'    => RecoveryForm::className(),
            'scenario' => 'reset',
        ]);

        $this->performAjaxValidation($model);

        if ($model->load(\Yii::$app->getRequest()->post()) && $model->resetPassword($token)) {
            return $this->render('/message', [
                'title'  => \Yii::t('user', 'Password has been changed'),
                'module' => $this->module,
            ]);
        }

        return $this->render('reset', [
            'model' => $model,
        ]);
    }

    /**
     * Performs ajax validation.
     * @param Model $model
     * @throws \yii\base\ExitException
     */
    protected function performAjaxValidation(Model $model)
    {
        if (\Yii::$app->request->isAjax && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            echo json_encode(ActiveForm::validate($model));
            \Yii::$app->end();
        }
    }
}


<?php

/**
 * Manage Form
 *
 * @category  	lib
 * @package		lib\Form
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */
namespace Venus\lib\Form;

/**
 * This class manage the Form
 *
 * @category  	lib
 * @package		lib\Form
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */
class Radio extends Common
{
	/**
	 * the name of element
	 *
	 * @access private
	 * @var    string
	 */
	private $_sType = null;

	/**
	 * the label of element
	 *
	 * @access private
	 * @var    string
	 */
	private $_sLabel = null;

	/**
	 * the value of element
	 *
	 * @access private
	 * @var    string
	 */
	private $_sValue = null;

	/**
	 * the value of the checked element
	 *
	 * @access private
	 * @var    string
	 */
	private $_sValueChecked = null;

	/**
	 * constructor that it increment (static) for all use
	 *
	 * @access public
	 * @param  string $sName name
	 * @param  string $sLabel label of radio
	 * @param  string $sValue value of radio
	 * @param  string $sValueChecked value checked of radio
	 * @return \Venus\lib\Form\Input
	 */
	public function __construct(string $sName, string $sLabel, string $sValue = null, string $sValueChecked = null)
	{
		$this->setName($sName);
		$this->setValue($sValue);
		$this->setValueChecked($sValueChecked);
		$this->setLabel($sLabel);
	}

	/**
	 * get the Value
	 *
	 * @access public
	 * @return string
	 */
	public function getValue()
	{
		return $this->_sValue;
	}

	/**
	 * set the Value
	 *
	 * @access public
	 * @param  string $sValue Value of input;
	 * @return Radio
	 */
	public function setValue(string $sValue = null) : Radio
	{
		$this->_sValue = $sValue;
		return $this;
	}

	/**
	 * get the Value Checked
	 *
	 * @access public
	 * @return string
	 */
	public function getValueChecked()
	{
		return $this->_sValueChecked;
	}

	/**
	 * set the Value Checked
	 *
	 * @access public
	 * @param  string $sValueChecked Value of input;
	 * @return Radio
	 */
	public function setValueChecked(string $sValueChecked = null) : Radio
	{
		$this->_sValueChecked = $sValueChecked;
		return $this;
	}

	/**
	 * get the Label
	 *
	 * @access public
	 * @return string
	 */
	public function getLabel() : string
	{
		return $this->_sLabel;
	}

	/**
	 * set the Label
	 *
	 * @access public
	 * @param  string $sLabel Label of input;
	 * @return Radio
	 */
	public function setLabel(string $sLabel) : Radio
	{
		$this->_sLabel = $sLabel;
		return $this;
	}

	/**
	 * if the button is clicked
	 *
	 * @access public
	 * @param  string $sType type of input;
	 * @return bool
	 */
	public function isClicked(string $sType) : bool
	{
		if ($this->getType() === 'submit' || $this->getType() === 'button') {

			if (isset($_POST[$this->getName()])) { return true; }
		}

		return false;
	}

	/**
	 * get the <html>
	 *
	 * @access public
	 * @return string
	 */
	public function fetch() : string
	{
		$sContent = '<input type="radio" name="'.$this->getName().'" value="'.$this->getValue().'"';

		if ($this->getValueChecked() == $this->getValue()) { $sContent .= ' checked="checked"'; }

		$sContent .= '/> '.$this->getLabel();

		return $sContent;
	}
}