<?php

namespace Reaction\Helpers;

/**
 * Class ReflectionHelper.
 * Helper static for some operations where Reflection is needed
 * @package Reaction\Helpers
 */
class ReflectionHelper
{
    const REFLECTION_CLASS = 'class';
    const REFLECTION_METHOD = 'method';
    const REFLECTION_PROPERTY = 'property';

    const ARG_CHECK_RETURN_BOOL = 'bool';
    const ARG_CHECK_RETURN_DATA = 'data';

    const ARG_TYPE_MISMATCH     = 'arg_type_error';
    const ARG_REQUIRED_MISSING  = 'arg_required_error';

    const DOC_COMMENT_FULL      = 'parseDocCommentDetail';
    const DOC_COMMENT_SHORT     = 'parseDocCommentSummary';
    const DOC_COMMENT_TAGS      = 'parseDocCommentTags';

    /**
     * @var array Reflections cache
     */
    protected static $_reflections = [
        self::REFLECTION_CLASS => [],
        self::REFLECTION_METHOD => [],
        self::REFLECTION_PROPERTY => [],
    ];

    /**
     * Check that class (by name) implements some interface
     * @param string $className
     * @param string $interfaceName
     * @return bool
     */
    public static function isImplements($className, $interfaceName)
    {
        $implementations = class_implements($className, true);
        return isset($implementations[$interfaceName]);
    }

    /**
     * Check that class is instantiable
     * @param string $className
     * @return bool
     */
    public static function isInstantiable($className)
    {
        $reflection = static::getClassReflection($className);
        if ($reflection === null) {
            return false;
        }
        return $reflection->isInstantiable();
    }

    /**
     * Get class PHPDoc full text
     * @param string|object $objectOrName
     * @return string|null
     */
    public static function getClassDocFull($objectOrName)
    {
        return static::getClassDoc($objectOrName, static::DOC_COMMENT_FULL);
    }

    /**
     * Get class PHPDoc short text (first line)
     * @param string|object $objectOrName
     * @return string|null
     */
    public static function getClassDocSummary($objectOrName)
    {
        return static::getClassDoc($objectOrName, static::DOC_COMMENT_SHORT);
    }

    /**
     * Get class PHPDoc tags array
     * @param string|object $objectOrName
     * @return array|null
     */
    public static function getClassDocTags($objectOrName)
    {
        return static::getClassDoc($objectOrName, static::DOC_COMMENT_TAGS);
    }

    /**
     * Get class method PHPDoc full text
     * @param \ReflectionMethod|string $method
     * @param string|object|null       $objectOrName
     * @return array|null|string
     */
    public static function getMethodDocFull($method, $objectOrName = null)
    {
        return static::getMethodPropertyDoc($method, $objectOrName, static::REFLECTION_METHOD,static::DOC_COMMENT_FULL);
    }

    /**
     * Get class method PHPDoc short text (first line)
     * @param \ReflectionMethod|string $method
     * @param string|object|null       $objectOrName
     * @return string|null
     */
    public static function getMethodDocSummary($method, $objectOrName = null)
    {
        return static::getMethodPropertyDoc($method, $objectOrName, static::REFLECTION_METHOD, static::DOC_COMMENT_SHORT);
    }

    /**
     * Get class method PHPDoc tags array
     * @param \ReflectionMethod|string $method
     * @param string|object|null       $objectOrName
     * @return array|null
     */
    public static function getMethodDocTags($method, $objectOrName = null)
    {
        return static::getMethodPropertyDoc($method, $objectOrName, static::REFLECTION_METHOD, static::DOC_COMMENT_TAGS);
    }

    /**
     * Get class property PHPDoc full text
     * @param string|\ReflectionProperty $property
     * @param string|object|null         $objectOrName
     * @return string|null
     */
    public static function getPropertyDocFull($property, $objectOrName = null)
    {
        return static::getMethodPropertyDoc($property, $objectOrName, static::REFLECTION_PROPERTY, static::DOC_COMMENT_FULL);
    }

    /**
     * Get class property PHPDoc short text (first line)
     * @param string|\ReflectionProperty $property
     * @param string|object|null         $objectOrName
     * @return string|null
     */
    public static function getPropertyDocSummary($property, $objectOrName = null)
    {
        return static::getMethodPropertyDoc($property, $objectOrName, static::REFLECTION_PROPERTY, static::DOC_COMMENT_SHORT);
    }

    /**
     * Get class property PHPDoc tags array
     * @param string|\ReflectionProperty $property
     * @param string|object|null         $objectOrName
     * @return array|null
     */
    public static function getPropertyDocTags($property, $objectOrName = null)
    {
        return static::getMethodPropertyDoc($property, $objectOrName, static::REFLECTION_PROPERTY, static::DOC_COMMENT_TAGS);
    }

    /**
     * Get class method reflection
     * @param string|object $objectOrName
     * @param string $methodName
     * @return null|\ReflectionMethod
     */
    public static function getMethodReflection($objectOrName, $methodName)
    {
        $cached = static::getReflectionFromCache(static::REFLECTION_METHOD, $objectOrName, $methodName);
        if ($cached !== null) {
            return $cached;
        }
        try {
            $reflection = new \ReflectionMethod($objectOrName, $methodName);
            return static::setReflectionToCache($reflection, static::REFLECTION_METHOD, $objectOrName, $methodName);
        } catch (\ReflectionException $exception) {
            $reflection = null;
        }
        return $reflection;
    }

    /**
     * Get class reflection
     * @param string|object $objectOrName
     * @return null|\ReflectionClass
     */
    public static function getClassReflection($objectOrName)
    {
        $cached = static::getReflectionFromCache(static::REFLECTION_CLASS, $objectOrName);
        if ($cached !== null) {
            return $cached;
        }
        try {
            $reflection = new \ReflectionClass($objectOrName);
            return static::setReflectionToCache($reflection, static::REFLECTION_CLASS, $objectOrName);
        } catch (\ReflectionException $exception) {
            $reflection = null;
        }
        return $reflection;
    }

    /**
     * Get property reflection
     * @param string|object $objectOrName
     * @param string        $propertyName
     * @return mixed|null|\ReflectionProperty
     */
    public static function getPropertyReflection($objectOrName, $propertyName)
    {
        $cached = static::getReflectionFromCache(static::REFLECTION_PROPERTY, $objectOrName, $propertyName);
        if ($cached !== null) {
            return $cached;
        }
        try {
            $reflection = new \ReflectionProperty($objectOrName, $propertyName);
            return static::setReflectionToCache($reflection, static::REFLECTION_PROPERTY, $objectOrName, $propertyName);
        } catch (\ReflectionException $exception) {
            $reflection = null;
        }
        return $reflection;
    }

    /**
     * Check class method arguments for consistency
     * @param array  $arguments
     * @param string|\ReflectionMethod $method
     * @param null   $objectOrName
     * @param string $returnType
     * @return array|bool|null
     */
    public static function checkMethodArguments($arguments = [], $method, $objectOrName = null, $returnType = self::ARG_CHECK_RETURN_DATA)
    {
        if ($method instanceof \ReflectionMethod) {
            $reflection = $method;
        } elseif ($objectOrName !== null) {
            $reflection = static::getMethodReflection($objectOrName, $method);
        } else {
            return null;
        }
        if ($reflection->getNumberOfRequiredParameters() === 0) {
            return $returnType === static::ARG_CHECK_RETURN_DATA ? [] : true;
        }
        $methodParams = $reflection->getParameters();
        $data = [];
        foreach ($methodParams as $param) {
            if (!$param->isOptional() && empty($arguments)) {
                $data[$param->name] = static::ARG_REQUIRED_MISSING;
            } elseif(!empty($arguments) && ($type = $param->getType()) !== null) {
                $arg = reset($arguments);
                $typeName = $type->getName();
                $stdTypes = ['bool', 'int', 'string', 'array', 'object', 'float', 'callable'];
                if (!in_array($typeName, $stdTypes) && !$arg instanceof $typeName) {
                    $data[$param->name] = static::ARG_TYPE_MISMATCH;
                }
            }
            array_shift($arguments);
        }
        return $returnType === static::ARG_CHECK_RETURN_DATA ? $data : empty($data);
    }

    /**
     * Get reflection from cache
     * @param string $type
     * @param string|object $objectOrName
     * @param mixed  ...$params
     * @return mixed
     */
    protected static function getReflectionFromCache($type = self::REFLECTION_CLASS, $objectOrName, ...$params)
    {
        $cache = &static::$_reflections[$type];
        $key = static::getCacheKey($type, $objectOrName, ...$params);
        return isset($cache[$key]) ? $cache[$key] : null;
    }

    /**
     * Save reflection to cache
     * @param \Reflector $reflection
     * @param string     $type
     * @param null       $objectOrName
     * @param mixed      ...$params
     * @return mixed
     */
    protected static function setReflectionToCache($reflection, $type = self::REFLECTION_CLASS, $objectOrName = null, ...$params)
    {
        if (null === $reflection || null === $objectOrName) {
            return null;
        }
        $key = static::getCacheKey($type, $objectOrName, ...$params);
        static::$_reflections[$type][$key] = $reflection;
        return $reflection;
    }

    /**
     * Get object cache key
     * @param string $type
     * @param string|object $objectOrName
     * @param mixed[]  ...$params
     * @return mixed|string
     */
    protected static function getCacheKey($type = self::REFLECTION_CLASS, $objectOrName, ...$params)
    {
        if (is_object($objectOrName)) {
            $className = static::getObjectClassName($objectOrName);
        } else {
            $className = $objectOrName;
        }
        $key = $className;
        switch ($type) {
            case static::REFLECTION_METHOD:
            case static::REFLECTION_PROPERTY:
                $methodOrProperty = $params[0];
                $key .= '::' . $methodOrProperty;
                break;
        }
        return $key;
    }

    /**
     * Get class name of object or its reflection
     * @param object $object
     * @return mixed|string
     */
    protected static function getObjectClassName($object)
    {
        $nameGetters = [
            \ReflectionClass::class => 'getName()',
            \ReflectionMethod::class => 'class',
            \ReflectionProperty::class => 'class',
        ];
        foreach ($nameGetters as $class => $getter) {
            if ($object instanceof $class) {
                $isMethod = substr($getter, -2) === '()';
                if ($isMethod) {
                    $getter = substr($getter, 0, -2);
                    return call_user_func([$object, $getter]);
                }
                return $object->$getter;
            }
        }
        return get_class($object);
    }

    /**
     * Parses PHPDoc block into tags.
     * @param \ReflectionClass|\ReflectionMethod|\ReflectionProperty $reflection the comment block
     * @return array the parsed tags
     */
    protected static function parseDocCommentTags($reflection)
    {
        $comment = $reflection->getDocComment();
        $comment = "@description \n" . strtr(trim(preg_replace('/^\s*\**( |\t)?/m', '', trim($comment, '/'))), "\r", '');
        $parts = preg_split('/^\s*@/m', $comment, -1, PREG_SPLIT_NO_EMPTY);
        $tags = [];
        foreach ($parts as $part) {
            if (preg_match('/^(\w+)(.*)/ms', trim($part), $matches)) {
                $name = $matches[1];
                if (!isset($tags[$name])) {
                    $tags[$name] = trim($matches[2]);
                } elseif (is_array($tags[$name])) {
                    $tags[$name][] = trim($matches[2]);
                } else {
                    $tags[$name] = [$tags[$name], trim($matches[2])];
                }
            }
        }

        return $tags;
    }

    /**
     * Returns the first line of PHPDoc block.
     *
     * @param \ReflectionClass|\ReflectionMethod|\ReflectionProperty  $reflection
     * @return string
     */
    protected static function parseDocCommentSummary($reflection)
    {
        $docLines = preg_split('~\R~u', $reflection->getDocComment());
        if (isset($docLines[1])) {
            return trim($docLines[1], "\t *");
        }

        return '';
    }

    /**
     * Returns full description from the PHPDoc block.
     *
     * @param \ReflectionClass|\ReflectionMethod|\ReflectionProperty $reflection
     * @return string
     */
    protected static function parseDocCommentDetail($reflection)
    {
        $comment = strtr(trim(preg_replace('/^\s*\**( |\t)?/m', '', trim($reflection->getDocComment(), '/'))), "\r", '');
        if (preg_match('/^\s*@\w+/m', $comment, $matches, PREG_OFFSET_CAPTURE)) {
            $comment = trim(substr($comment, 0, $matches[0][1]));
        }
        if ($comment !== '') {
            return rtrim(Console::renderColoredString(Console::markdownToAnsi($comment)));
        }

        return '';
    }

    /**
     * Get class PHPDoc parsed
     * @param object $object
     * @param string $parseMethod
     * @return string|array|null
     */
    protected static function getClassDoc($object, $parseMethod = 'parseDocCommentSummary')
    {
        try {
            $reflection = new \ReflectionClass($object);
            $docData = static::$parseMethod($reflection);
        } catch (\ReflectionException $exception) {
            $docData = null;
        }
        return $docData;
    }

    /**
     * Get method or property PHPDoc parsed
     * @param string|\ReflectionMethod|\ReflectionProperty $method
     * @param object|null                                  $object
     * @param string                                       $type
     * @param string                                       $parseMethod
     * @return string|array|null
     */
    protected static function getMethodPropertyDoc($method, $object = null, $type = self::REFLECTION_METHOD, $parseMethod = self::DOC_COMMENT_SHORT)
    {
        try {
            //Method is already a \ReflectionMethod|\ReflectionProperty
            if ($method instanceof \ReflectionMethod || $method instanceof \ReflectionProperty) {
                $reflection = $method;
            //Method is string
            } else {
                //Check that object is not a \ReflectionClass
                $object = $object instanceof \ReflectionClass ? $object->getName() : $object;
                $reflection = $type === static::REFLECTION_METHOD
                    ? new \ReflectionMethod($object, $method)
                    : new \ReflectionProperty($object, $method);
            }
            $docData = static::$parseMethod($reflection);
        } catch (\ReflectionException $exception) {
            $docData = null;
        }
        return $docData;
    }
}


<?php
/**
 * This file is part of the CarteBlanche PHP framework.
 *
 * (c) Pierre Cassat <me@e-piwi.fr> and contributors
 *
 * License Apache-2.0 <http://github.com/php-carteblanche/carteblanche/blob/master/LICENSE>
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CarteBlanche\Abstracts;

use \CarteBlanche\CarteBlanche;
use \CarteBlanche\App\FrontController;
use \Library\CommandLine\AbstractCommandLineController as Original;
use \Library\CommandLine\CommandLineControllerInterface;

/**
 * @author  Piero Wbmstr <me@e-piwi.fr>
 */
abstract class AbstractCommandLineController
    extends Original
    implements CommandLineControllerInterface
{

// ------------------------------------------
// Abstract methods & user definables
// ------------------------------------------

    /**
     * @var string  The script name
     */
    public static $_name = '';

    /**
     * @var string  The script version
     */
    public static $_version = '';

    /**
     * The default action of the controller, considered as 'home'
     */
    abstract function indexAction();

    /**
     * Initialization: to be overwritten (if needed, this method is called at the end of constructor)
     */
    protected function init(){}

// ------------------------------------------
// Object
// ------------------------------------------

    /**
     * The directory where to search the views files
     */
    static $views_dir = null;

    /**
     * The default console template file
     */
    static $template = 'empty.txt';

    /**
     * Class constructor : it checks if the application is installed
     *
     * @see self::init()
     */
    public function __construct(array $options = array())
    {
        parent::__construct($options);

        $_app = CarteBlanche::getConfig('app');
        $_cls = get_called_class();
        if (empty($_cls::$_name)) self::$_name = $_app['name'];
        if (empty($_cls::$_version)) self::$_version = $_app['version'];

        // the initializer if so
        $this->init();
    }

    /**
     * Get the global app container
     *
     * @return \CarteBlanche\App\Container
     * @see \CarteBlanche\App\Container
     */
    public function getContainer()
    {
        return CarteBlanche::getContainer();
    }

    /**
     * Get the global kernel from any controller
     *
     * @return \CarteBlanche\App\Kernel
     * @see \CarteBlanche\App\Kernel
     */
    public function getKernel()
    {
        return CarteBlanche::getKernel();
    }

    /**
     * Alias of App\FrontController->render()
     *
     * @return string
     * @see \CarteBlanche\App\FrontController::render()
     */
    public function render($params = null, $debug = null, $exception = null)
    {
        return FrontController::getInstance()
            ->render( $params, $debug, $exception );
    }

    /**
     * Alias of App\FrontController->view()
     *
     * @return string
     * @see \CarteBlanche\App\FrontController::view()
     */
    public function view($view = null, $params = null, $display = false, $exit = false)
    {
        return FrontController::getInstance()
            ->view( $view, $params, $display, $exit );
    }

}

// Endfile


<?php
namespace Li;

/**
 * db factor
 */
class Db
{
    public static $_instance;
    private static $_db = array();

    public static function db()
    {
        if(!(self::$_instance instanceof self))
        {
            self::$_instance = new self();
        }

        return self::$_instance;
    }

    function __get($dbName)
    {
        if(isset(App::app()->config['database'][$dbName]))
        {
            $driver = 'Li\\'.ucfirst(App::app()->config['database'][$dbName]['driver']);

            if(!(isset($this->$dbName) && $this->$dbName instanceof $driver))
            {
                $this->$dbName =  new $driver(App::app()->config['database'][$dbName]);
            }

            return $this->$dbName;
        }
        else
        {
            throw new Exception("config no db ".$dbName);
        }
    }

    /**
     * init db instance by config
     * @param $key string the db index
     * @param $config mixed the config
     */
    public function initByConfig($key, $config)
    {
        if(empty($config))
        {
            throw new Exception('db config is empty');
        }
        $driver = 'Li\\'.ucfirst($config['driver']);

        if(!(isset($this->$key) && $this->$key instanceof $driver))
        {
            $this->$key =  new $driver($config);
        }

    }
}


<?php

namespace FzyCommon\View\Helper;

use Zend\View\Helper\AbstractHelper;
use Zend\Mvc\Controller\Plugin\FlashMessenger as FlashMessenger;

/**
 *
 */
class FlashMessages extends AbstractHelper
{
    /**
     * @var FlashMessenger
     */
    protected $flashMessenger;

    public function setFlashMessenger(FlashMessenger $flashMessenger)
    {
        $this->flashMessenger = $flashMessenger;
    }

    private $_nsMap = array(
        'danger' => FlashMessenger::NAMESPACE_ERROR,
        'success' => FlashMessenger::NAMESPACE_SUCCESS,
        'warning' => FlashMessenger::NAMESPACE_WARNING,
        'info' => FlashMessenger::NAMESPACE_INFO,
    );

    /**
     * Accepts foundation class, maps to a FlashMessenger namespace
     * @param  string $foundationClass
     * @return string
     */
    private function _mapNameSpace($foundationClass)
    {
        if (isset($this->_nsMap[$foundationClass])) {
            return $this->_nsMap[$foundationClass];
        }

        return reset($this->_nsMap);
    }

    public function __invoke($includeCurrentMessages = false)
    {
        $messages = array_combine(array_keys($this->_nsMap), array(array(), array(), array(), array()));
        foreach ($messages as $className => &$m) {
            $ns = $this->_mapNameSpace($className);
            $m = $this->flashMessenger->getMessagesFromNamespace($ns);
            if ($includeCurrentMessages) {
                $m = array_merge($m, $this->flashMessenger->getCurrentMessagesFromNamespace($ns));
                $this->flashMessenger->clearCurrentMessagesFromNamespace($ns);
            }
        }

        return $messages;
    }
}


<?php

namespace Maestroprog\Container;

class ServicesExtractor
{
    /**
     * @param $container
     *
     * @return array
     * @throws \ReflectionException
     */
    public function extractServicesId($container): array
    {
        $list = [];

        $reflection = new \ReflectionClass($container);

        foreach ($reflection->getMethods() as $method) {
            $methodName = $method->getName();
            if (substr($methodName, 0, 3) === 'get' && strlen($methodName) > 3) {
                $argument = $this->argumentInfoFrom($method);
                if ($argument->isInternal()) {
                    // не добавляем в общий контейнер внутренние аргументы
                    continue;
                }
                $serviceId = substr($methodName, 3);
                $list[$serviceId] = $argument;
            }
        }

        return $list;
    }

    /**
     * @param \ReflectionMethod $method
     *
     * @return Argument
     */
    private function argumentInfoFrom(\ReflectionMethod $method): Argument
    {
        static $modifiers = [
            'internal',
            'decorates',
            'private'
        ];
        $docs = explode("\n", $method->getDocComment() ?: '');
        array_walk($docs, function (&$key) {
            $key = trim($key, "* \t\r");
        });

        $result = [];
        foreach ($docs as $key) {

            if ('@' !== substr($key, 0, 1)) {
                continue;
            }
            [$modifier, $arguments] = explode(' ', ltrim($key, '@') . ' ', 2);

            if (in_array($modifier, $modifiers, true)) {

                if (isset($result[$modifier])) {
                    throw new \LogicException(sprintf(
                        'Modifier "%s" of service "%s" cannot be duplicated.',
                        $modifier,
                        substr($method->getShortName(), 3)
                    ));
                }

                $result[$modifier] = trim($arguments);
            }
        }

        return new Argument($method->getShortName(), (string)$method->getReturnType(), $result);
    }
}


<?php namespace Ordercloud\Entities\Products;

use JsonSerializable;
use Ordercloud\Entities\Organisations\OrganisationShort;

class Product implements JsonSerializable
{
    /** @var integer */
    private $id;
    /** @var string */
    private $name;
    /** @var string */
    private $description;
    /** @var string */
    private $shortDescription;
    /** @var string */
    private $sku;
    /** @var float */
    private $price;
    /**
     * @var array|ProductAttributeDisplay[]
     * @reflectType Ordercloud\Entities\Products\ProductAttributeDisplay
     */
    private $attributes;
    /**
     * @var array|ProductOptionSet[]
     * @reflectType Ordercloud\Entities\Products\ProductOptionSet
     */
    private $optionSets;
    /**
     * @var array|ProductExtraSet[]
     * @reflectType Ordercloud\Entities\Products\ProductExtraSet
     */
    private $extraSets;
    /**
     * @var array|ProductTag[]
     * @reflectType Ordercloud\Entities\Products\ProductTag
     */
    private $tags;
    /** @var OrganisationShort */
    private $organisation;
    /** @var boolean */
    private $enabled;
    /** @var boolean */
    private $available;
    /** @var boolean */
    private $availableOnline;
    /**
     * @var array|ProductImage[]
     * @reflectType Ordercloud\Entities\Products\ProductImage
     */
    private $images;
    /**
     * @var array|Product[]
     * @reflectType Ordercloud\Entities\Products\Product
     */
    private $groupItems;
    /** @var ProductType */
    private $productType;
    /** @var ProductPriceDiscount */
    private $discount;
    /** @var Boolean */
    private $globalProduct;
    /**
     * @var string
     */
    private $additionalInfo;
    /**
     * @var boolean
     */
    private $optionsPluFlatMappingEnabled;

    public function __construct($id, $name, $description, $shortDescription, $sku, $price, array $attributes, array $optionSets, array $extraSets, array $tags, OrganisationShort $organisation, $enabled, $available, $availableOnline, array $images, array $groupItems, ProductType $productType, ProductPriceDiscount $discount = null, $globalProduct, $additionalInfo, $optionsPluFlatMappingEnabled)
    {
        $this->id = $id;
        $this->name = $name;
        $this->description = $description;
        $this->shortDescription = $shortDescription;
        $this->sku = $sku;
        $this->price = $price;
        $this->attributes = $attributes;
        $this->optionSets = $optionSets;
        $this->extraSets = $extraSets;
        $this->tags = $tags;
        $this->organisation = $organisation;
        $this->enabled = $enabled;
        $this->available = $available;
        $this->availableOnline = $availableOnline;
        $this->images = $images;
        $this->groupItems = $groupItems;
        $this->productType = $productType;
        $this->discount = $discount;
        $this->globalProduct = $globalProduct;
        $this->additionalInfo = $additionalInfo;
        $this->optionsPluFlatMappingEnabled = $optionsPluFlatMappingEnabled;
    }

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

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

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

    /**
     * @return string
     */
    public function getShortDescription()
    {
        return $this->shortDescription;
    }

    /**
     * @return string
     */
    public function getSku()
    {
        return $this->sku;
    }

    /**
     * @return float
     */
    public function getPrice()
    {
        return $this->price;
    }

    /**
     * @return array|ProductAttributeDisplay[]
     */
    public function getAttributes()
    {
        return $this->attributes;
    }

    /**
     * @return array|ProductOptionSet[]
     */
    public function getOptionSets()
    {
        return $this->optionSets;
    }

    /**
     * @param $optionSetID
     *
     * @return ProductOptionSet|null
     */
    public function getOptionSetByID($optionSetID)
    {
        foreach ($this->getOptionSets() as $optionSet) {
            if ($optionSet->getId() == $optionSetID) {
                return $optionSet;
            }
        }

        foreach ($this->getUnlockableOptionSets() as $optionSet) {
            if ($optionSet->getId() == $optionSetID) {
                return $optionSet;
            }
        }

        return null;
    }

    /**
     * @return array|UnlockableProductOptionSet[]
     */
    public function getUnlockableOptionSets()
    {
        return UnlockableProductOptionSet::createFromProduct($this);
    }

    /**
     * @return array|ProductExtraSet[]
     */
    public function getExtraSets()
    {
        return $this->extraSets;
    }

    /**
     * @param $extraSetID
     *
     * @return ProductExtraSet|null
     */
    public function getExtraSetByID($extraSetID)
    {
        foreach ($this->getExtraSets() as $extraSet) {
            if ($extraSet->getId() == $extraSetID) {
                return $extraSet;
            }
        }

        foreach ($this->getUnlockableExtraSets() as $extraSet) {
            if ($extraSet->getId() == $extraSetID) {
                return $extraSet;
            }
        }

        return null;
    }

    /**
     * @return array|UnlockableProductExtraSet[]
     */
    public function getUnlockableExtraSets()
    {
        return UnlockableProductExtraSet::createFromProduct($this);
    }

    /**
     * @return array|ProductTag[]
     */
    public function getTags()
    {
        return $this->tags;
    }

    /**
     * @param string $tagType
     *
     * @return ProductTag|null
     */
    public function getTagByType($tagType)
    {
        foreach ($this->getTags() as $tag) {
            if ($tag->isType($tagType)) {
                return $tag;
            }
        }

        return null;
    }

    /**
     * @return OrganisationShort
     */
    public function getOrganisation()
    {
        return $this->organisation;
    }

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

    /**
     * @return boolean
     */
    public function isAvailable()
    {
        return $this->available;
    }

    /**
     * @return boolean
     */
    public function isAvailableOnline()
    {
        return $this->availableOnline;
    }

    /**
     * @return array|ProductImage[]
     */
    public function getImages()
    {
        return $this->images;
    }

    /**
     * @return ProductImage|null
     */
    public function getDefaultImage()
    {
        foreach ($this->getImages() as $image) {
            if ($image->isDefault()) {
                return $image;
            }
        }

        return null;
    }

    /**
     * @return bool
     */
    public function hasDefaultImage()
    {
        return ! is_null($this->getDefaultImage());
    }

    /**
     * @return bool
     */
    public function hasImages()
    {
        return sizeof($this->getImages()) > 0;
    }

    /**
     * @return array|Product[]
     */
    public function getGroupItems()
    {
        return $this->groupItems;
    }

    /**
     * @return ProductType
     */
    public function getProductType()
    {
        return $this->productType;
    }

    /**
     * @return ProductPriceDiscount
     */
    public function getDiscount()
    {
        return $this->discount;
    }

    /** @return boolean */
    public function isGlobalProduct()
    {
        return $this->globalProduct;
    }

    /**
     * @return string
     */
    public function getAdditionalInfo()
    {
        return $this->additionalInfo;
    }

    /**
     * @return boolean
     */
    public function isOptionsPluFlatMappingEnabled()
    {
        return $this->optionsPluFlatMappingEnabled;
    }

    /**
     * Specify data which should be serialized to JSON
     */
    public function jsonSerialize()
    {
        return [
            'id' => $this->getId(),
            'name' => $this->getName(),
            'description' => $this->getDescription(),
            'shortDescription' => $this->getShortDescription(),
            'sku' => $this->getSku(),
            'price' => $this->getPrice(),
            'attributes' => $this->getAttributes(),
            'options' => $this->getOptionSets(),
            'extras' => $this->getExtraSets(),
            'tags' => $this->getTags(),
            'organisation' => $this->getOrganisation(),
            'enabled' => $this->isEnabled(),
            'available' => $this->isAvailable(),
            'availableOnline' => $this->isAvailableOnline(),
            'images' => $this->getImages(),
            'groupItems' => $this->getGroupItems(),
            'productType' => $this->getProductType(),
            'discount' => $this->getDiscount(),
            'globalProduct' => $this->isGlobalProduct(),
            'additionalInfo' => $this->getAdditionalInfo(),
            'optionsPluFlatMappingEnabled' => $this->isOptionsPluFlatMappingEnabled(),
        ];
    }
}


<?php

/**
 * Jin Framework
 * Diatem
 */

namespace Jin2\Form\Validators;

use Jin2\Language\Translation;

/**
 * Validateur : teste si une date est intéfieure à une date de référence
 */
class IsDateInferior extends AbstractValidator
{

  /**
   * Constructeur
   *
   * @param  array $args          Tableau d'arguments array('arg1'=>'val1','arg2'=>'val2)
   * @throws \Exception
   */
  public function __construct($args)
  {
    return parent::__construct($args, array('format', 'date'));
  }

  /**
   * Implémente la fonction AbstractValidator::getType()
   *
   * @return string
   */
  public static function getType()
  {
    return 'isdateinferior';
  }

  /**
   * Teste la validité
   *
   * @param mixed $value Valeur à tester
   * @return boolean
   */
  public function isValid($value)
  {
    parent::resetErrors();
    if (empty($value)) {
      return true;
    }

    $format = $this->getArgValue('format');
    $dValidator = new Isdate(array('format' => $format));
    if (!$dValidator->isValid($value)) {
      $eMsg = Translation::get('validatorerror_isdateinferior');
      $eMsg = str_replace('%date%', parent::getArgValue('date'), $eMsg);
      parent::addError($eMsg);
      return false;
    } else {
      $date      = \DateTime::createFromFormat($format, $value)->format('U');
      $reference = \DateTime::createFromFormat($format, $this->getArgValue('date'))->format('U');
      if ($date >= $reference) {
        $eMsg = Translation::get('validatorerror_isdateinferior');
        $eMsg = str_replace('%date%', parent::getArgValue('date'), $eMsg);
        parent::addError($eMsg);
        return false;
      }
    }

    return true;
  }

}


<?php
namespace gossi\trixionary\client\responder\html;

use keeko\framework\domain\payload\PayloadInterface;
use keeko\framework\foundation\AbstractPayloadResponder;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Automatically generated HtmlResponder for Edit an Object
 *
 * @author Thomas Gossmann
 */
class ObjectsEditHtmlResponder extends AbstractPayloadResponder {

	/**
	 */
	protected function getPayloadMethods() {
		return [
			'keeko\framework\domain\payload\Blank' => 'form',
			'keeko\framework\domain\payload\NotValid' => 'form',
			'keeko\framework\domain\payload\Updated' => 'updated',
			'keeko\framework\domain\payload\NotUpdated' => 'updated'
		];
	}

	/**
	 * Automatically generated run method
	 *
	 * @param Request $request
	 * @param PayloadInterface $payload
	 * @return Response
	 */
	protected function form(Request $request, PayloadInterface $payload = null) {
		return new Response($this->render('/gossi/trixionary-client/templates/objects-edit.twig', $payload->get()));
	}

	protected function updated(Request $request, PayloadInterface $payload = null) {
		$sport = $payload->getModel()->getSport();
		$baseUrl = $this->getServiceContainer()->getKernel()->getApplication()->getBaseUrl();
		return new RedirectResponse($baseUrl . '/manage/' . $sport->getId() . '/objects');
	}
}


<?php
/**
 * package.xml parsing class, package.xml version 2.0
 *
 * PHP versions 4 and 5
 *
 * @category   pear
 * @package    PEAR
 * @author     Greg Beaver <cellog@php.net>
 * @copyright  1997-2009 The Authors
 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
 * @version    CVS: $Id: v2.php 313023 2011-07-06 19:17:11Z dufuz $
 * @link       http://pear.php.net/package/PEAR
 * @since      File available since Release 1.4.0a1
 */
/**
 * base xml parser class
 */
require_once 'PEAR/XMLParser.php';
require_once 'PEAR/PackageFile/v2.php';
/**
 * Parser for package.xml version 2.0
 * @category   pear
 * @package    PEAR
 * @author     Greg Beaver <cellog@php.net>
 * @copyright  1997-2009 The Authors
 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
 * @version    Release: @PEAR-VER@
 * @link       http://pear.php.net/package/PEAR
 * @since      Class available since Release 1.4.0a1
 */
class PEAR_PackageFile_Parser_v2 extends PEAR_XMLParser
{
    var $_config;
    var $_logger;
    var $_registry;

    function setConfig(&$c)
    {
        $this->_config = &$c;
        $this->_registry = &$c->getRegistry();
    }

    function setLogger(&$l)
    {
        $this->_logger = &$l;
    }
    /**
     * Unindent given string
     *
     * @param string $str The string that has to be unindented.
     * @return string
     * @access private
     */
    function _unIndent($str)
    {
        // remove leading newlines
        $str = preg_replace('/^[\r\n]+/', '', $str);
        // find whitespace at the beginning of the first line
        $indent_len = strspn($str, " \t");
        $indent = substr($str, 0, $indent_len);
        $data = '';
        // remove the same amount of whitespace from following lines
        foreach (explode("\n", $str) as $line) {
            if (substr($line, 0, $indent_len) == $indent) {
                $data .= substr($line, $indent_len) . "\n";
            } else {
                $data .= $line . "\n";
            }
        }
        return $data;
    }

    /**
     * post-process data
     *
     * @param string $data
     * @param string $element element name
     */
    function postProcess($data, $element)
    {
        if ($element == 'notes') {
            return trim($this->_unIndent($data));
        }
        return trim($data);
    }

    /**
     * @param string
     * @param string file name of the package.xml
     * @param string|false name of the archive this package.xml came from, if any
     * @param string class name to instantiate and return.  This must be PEAR_PackageFile_v2 or
     *               a subclass
     * @return PEAR_PackageFile_v2
     */
    function &parse($data, $file, $archive = false, $class = 'PEAR_PackageFile_v2')
    {
        if (PEAR::isError($err = parent::parse($data, $file))) {
            return $err;
        }

        $ret = new $class;
        $ret->encoding = $this->encoding;
        $ret->setConfig($this->_config);
        if (isset($this->_logger)) {
            $ret->setLogger($this->_logger);
        }

        $ret->fromArray($this->_unserializedData);
        $ret->setPackagefile($file, $archive);
        return $ret;
    }
}


<?php
/**
 * Поле типа «datetime»
 *
 * @version ${product.version}
 *
 * @copyright 2013, Михаил Красильников <m.krasilnikov@yandex.ru>
 * @license http://www.gnu.org/licenses/gpl.txt	GPL License 3
 * @author Михаил Красильников <m.krasilnikov@yandex.ru>
 *
 * Данная программа является свободным программным обеспечением. Вы
 * вправе распространять ее и/или модифицировать в соответствии с
 * условиями версии 3 либо (по вашему выбору) с условиями более поздней
 * версии Стандартной Общественной Лицензии GNU, опубликованной Free
 * Software Foundation.
 *
 * Мы распространяем эту программу в надежде на то, что она будет вам
 * полезной, однако НЕ ПРЕДОСТАВЛЯЕМ НА НЕЕ НИКАКИХ ГАРАНТИЙ, в том
 * числе ГАРАНТИИ ТОВАРНОГО СОСТОЯНИЯ ПРИ ПРОДАЖЕ и ПРИГОДНОСТИ ДЛЯ
 * ИСПОЛЬЗОВАНИЯ В КОНКРЕТНЫХ ЦЕЛЯХ. Для получения более подробной
 * информации ознакомьтесь со Стандартной Общественной Лицензией GNU.
 *
 * Вы должны были получить копию Стандартной Общественной Лицензии
 * GNU с этой программой. Если Вы ее не получили, смотрите документ на
 * <http://www.gnu.org/licenses/>
 *
 * @package ORM
 */

/**
 * Поле типа «datetime»
 *
 * @package ORM
 * @since 3.00
 */
class ORM_Field_Datetime extends ORM_Field_Abstract
{
    /**
     * Возвращает имя типа
     *
     * @return string
     *
     * @since 3.00
     */
    public function getTypeName()
    {
        return 'datetime';
    }

    /**
     * Возвращает соответствующий тип PDO (PDO::PARAM_…) или null
     *
     * @return null|int
     *
     * @since 3.00
     */
    public function getPdoType()
    {
        return PDO::PARAM_STR;
    }

    /**
     * Преобразует значение ORM в значение PDO
     *
     * @param mixed $ormValue
     *
     * @throws InvalidArgumentException
     *
     * @return mixed
     *
     * @since 3.00
     */
    public function orm2pdo($ormValue)
    {
        if (is_null($ormValue))
        {
            return null;
        }
        if (!($ormValue instanceof DateTime))
        {
            throw new InvalidArgumentException('$ormValue must be a DateTime object');
        }
        /* @var DateTime $ormValue */
        return $ormValue->format('Y-m-d H:i:s');
    }

    /**
     * Преобразует значение PDO в значение ORM
     *
     * @param mixed $pdoValue
     *
     * @return mixed
     *
     * @since 3.00
     */
    public function pdo2orm($pdoValue)
    {
        return new DateTime(strval($pdoValue));
    }

    /**
     * Возвращает выражение SQL для описания поля при создании таблицы
     *
     * @return string
     */
    public function getSqlFieldDefinition()
    {
        return $this->getName() . ' TIMESTAMP';
    }
}


<?php namespace Ordercloud\Services;

use Ordercloud\Entities\Orders\Order;
use Ordercloud\Entities\Orders\OrderCollection;
use Ordercloud\Entities\Orders\OrderInvoice;
use Ordercloud\Entities\Orders\ScheduleOption;
use Ordercloud\Requests\Exceptions\NotFoundRequestException;
use Ordercloud\Requests\Exceptions\OrdercloudRequestException;
use Ordercloud\Requests\Orders\CreateOrderRequest;
use Ordercloud\Requests\Orders\Criteria\OrganisationOrderCriteria;
use Ordercloud\Requests\Orders\Criteria\UserOrderCriteria;
use Ordercloud\Requests\Orders\EstimateDeliveryCostRequest;
use Ordercloud\Requests\Orders\Exceptions\DeliveryNotAvailableException;
use Ordercloud\Requests\Orders\Exceptions\OrderTotalConflictException;
use Ordercloud\Requests\Orders\GetOrderInvoiceRequest;
use Ordercloud\Requests\Orders\GetOrderRequest;
use Ordercloud\Requests\Orders\GetOrderScheduleOptionsRequest;
use Ordercloud\Requests\Orders\GetOrganisationOrdersRequest;
use Ordercloud\Requests\Orders\GetUserOrdersRequest;

class OrderService extends OrdercloudService
{
    /**
     * @param int $orderId
     *
     * @return Order
     *
     * @throws OrdercloudRequestException
     * @throws NotFoundRequestException
     */
    public function getOrder($orderId)
    {
        return $this->request(new GetOrderRequest($orderId));
    }

    /**
     * @param int               $userId
     * @param UserOrderCriteria $criteria
     *
     * @return OrderCollection
     *
     * @throws OrdercloudRequestException
     */
    public function getUserOrders($userId, UserOrderCriteria $criteria = null)
    {
        $criteria = $criteria ?: UserOrderCriteria::create();

        return $this->request(new GetUserOrdersRequest($userId, $criteria));
    }

    /**
     * @param int                            $organisationId
     * @param OrganisationOrderCriteria|null $criteria
     *
     * @return OrderCollection|Order[]
     *
     * @throws OrdercloudRequestException
     */
    public function getOrganisationOrders($organisationId, OrganisationOrderCriteria $criteria = null)
    {
        $criteria = $criteria ?: OrganisationOrderCriteria::create();

        return $this->request(new GetOrganisationOrdersRequest($organisationId, $criteria));
    }

    /**
     * @param int       $deliveryServiceOrganisationId
     * @param int       $geoId
     * @param array|int $merchantIds
     *
     * @return float
     *
     * @throws OrdercloudRequestException
     * @throws DeliveryNotAvailableException
     */
    public function estimateDeliveryCost($deliveryServiceOrganisationId, $geoId, array $merchantIds)
    {
        return $this->request(new EstimateDeliveryCostRequest($deliveryServiceOrganisationId, $geoId, $merchantIds));
    }

    /**
     * @param CreateOrderRequest $request
     *
     * @see Ordercloud\Requests\Orders\Builders\CreateOrderRequestBuilder
     *
     * @return int The order ID
     *
     * @throws OrdercloudRequestException
     * @throws OrderTotalConflictException
     * @throws DeliveryNotAvailableException
     */
    public function createOrder(CreateOrderRequest $request)
    {
        return $this->request($request);
    }

    /**
     * @param int[]  $organisationIds
     * @param string $fromDate
     * @param string $toDate
     *
     * @return ScheduleOption[]
     *
     * @throws OrdercloudRequestException
     */
    public function getScheduleOptions(array $organisationIds, $fromDate = null, $toDate = null)
    {
        return $this->request(new GetOrderScheduleOptionsRequest($organisationIds, $fromDate, $toDate));
    }

    /**
     * @param int $orderId
     *
     * @return OrderInvoice
     *
     * @throws OrdercloudRequestException
     * @throws NotFoundRequestException
     */
    public function getOrderInvoice($orderId)
    {
        return $this->request(new GetOrderInvoiceRequest($orderId));
    }
}


<?php namespace RestGalleries\APIs\Flickr;

use RestGalleries\APIs\ApiPhoto;

/**
 * Specific implementation of the PhotoAdapter interface, makes requests and normalizes the given data for return them.
 */
class Photo extends ApiPhoto
{
    protected $endPoint = 'http://api.flickr.com/services/rest/';

    /**
     * Common query values for all the requests.
     *
     * @var array
     */
    private $defaultQuery = [
        'format'         => 'json',
        'nojsoncallback' => 1,
    ];

    protected function fetchIds($galleryId)
    {
        $ids     = [];
        $query   = array_merge(
            $this->defaultQuery,
            [
                'method'         => 'flickr.photosets.getPhotos',
                'photoset_id'    => $galleryId,
                'extras'         => '',
                'privacy_filter' => 1,
                'per_page'       => 50,
                'page'           => 1,
                'media'          => 'photos',
            ]
        );
        $request = $this->newRequest();

        do {
            $body = $request->setQuery($query)
                ->GET()
                ->getBody('array');

            if ($body['stat'] == 'fail') {
                return;
            }

            $photoset = &$body['photoset'];
            $newIds   = $this->extractIdsArray($photoset);
            $ids      = $this->addIds($ids, $newIds);

        } while (++$query['page'] <= $photoset['pages']);

        return $ids;

    }

    /**
     * Extracts from the given array data, the identifiers of photos.
     *
     * @param  array $data
     * @return array
     */
    private function extractIdsArray($data)
    {
        return array_pluck($data['photo'], 'id');
    }

    /**
     * Adds to the identifiers array, a new array of identifiers.
     *
     * @param  array $ids
     * @param  array $newIds
     * @return array|null
     */
    private function addIds(array $ids, array $newIds)
    {
        if (! empty($newIds)) {
            return array_merge($ids, $newIds);
        }
    }

    protected function fetchPhoto($id)
    {
        $query = array_merge(
            $this->defaultQuery,
            [
                'method'   => 'flickr.photos.getInfo',
                'photo_id' => $id,
                'secret'   => '',
            ]
        );

        $body = $this->newRequest()
            ->setQuery($query)
            ->GET()
            ->getBody();

        return $this->extractPhotoArray($body);

    }

    /**
     * Specific data are stored into an array and are returned, when it receive an failure, returns null.
     *
     * @param  object $data
     * @return array|null
     */
    private function extractPhotoArray($source)
    {
        if ($source->stat == 'fail') {
            return;
        }

        $data  = &$source->photo;

        $photo                     = [];
        $photo['id']               = $data->id;
        $photo['title']            = $data->title->_content;
        $photo['description']      = $data->description->_content;
        $photo['url']              = $data->urls->url[0]->_content;
        $photo['created']          = (string) $data->dates->posted;
        $photo['views']            = $data->views;
        $images                    = $this->fetchImages($photo['id']);
        $photo['source']           = $images[1];
        $photo['source_thumbnail'] = $images[0];

        return $photo;

    }

    /**
     * This function makes the request to get images sources from a photo and returns them as an array.
     *
     * @param  string $photoId
     * @return array
     */
    private function fetchImages($photoId)
    {
        $query = array_merge(
            $this->defaultQuery,
            [
                'method'   => 'flickr.photos.getSizes',
                'photo_id' => $photoId,
            ]
        );

        $body = $this->newRequest()
            ->setQuery($query)
            ->GET()
            ->getBody('array');

        return $this->extractImagesArray($body);

    }

    /**
     * Extracts an array of images from the photo array and returns them.
     *
     * @param  array $source
     * @return array
     */
    private function extractImagesArray($source)
    {
        $sizes  = array_get($source, 'sizes.size');
        $images = array_where($sizes, function ($key, $value) {
            return in_array($value['label'], ['Original', 'Small 320']);
        });

        return array_fetch($images, 'source');

    }

}


<?php

/*
 * This file is part of the Valkyrja framework.
 *
 * (c) Melech Mizrachi
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Valkyrja\Events\Commands;

use Valkyrja\Console\CommandHandler;
use Valkyrja\Console\Support\ProvidesCommand;

/**
 * Class EventsCache.
 *
 * @author Melech Mizrachi
 */
class EventsCacheCommand extends CommandHandler
{
    use ProvidesCommand;

    /**
     * The command.
     */
    public const COMMAND           = 'events:cache';
    public const PATH              = self::COMMAND;
    public const SHORT_DESCRIPTION = 'Generate the events cache';

    /**
     * Run the command.
     *
     * @return int
     */
    public function run(): int
    {
        $originalDebug = config()['app']['debug'];
        $originalEnv   = config()['app']['env'];

        config()['app']['debug'] = false;
        config()['app']['env']   = 'production';

        $cache = events()->getCacheable();

        config()['app']['debug'] = $originalDebug;
        config()['app']['env']   = $originalEnv;

        // Get the results of the cache attempt
        $result = file_put_contents(
            config()['events']['cacheFilePath'],
            '<?php return ' . var_export($cache, true) . ';',
            LOCK_EX
        );

        if ($result === false) {
            output()->writeMessage(
                'An error occurred while generating events cache.',
                true
            );

            return 1;
        }

        output()->writeMessage('Events cache generated successfully', true);

        return 0;
    }
}


<?php

namespace Reaction\Routes;

use Reaction\Base\Component;
use Reaction\Exceptions\InvalidConfigException;
use Reaction\Helpers\Url;
use Reaction\RequestApplicationInterface;

/**
 * Class UrlManager
 * @package Reaction\Routes
 */
class UrlManager extends Component implements UrlManagerInterface
{
    /**
     * @var string the URL suffix used.
     * For example, ".html" can be used so that the URL looks like pointing to a static HTML page.
     */
    public $suffix;

    /** @var string Application default base URL */
    protected $_baseUrl;
    /** @var string Application host info. (http://www.example.com) */
    protected $_hostInfo;
    /** @var string Application home URL */
    protected $_homeUrl;

    /**
     * Creates a URL using the given route and query parameters.
     *
     * You may specify the route as a string, e.g., `site/index`. You may also use an array
     * if you want to specify additional query parameters for the URL being created. The
     * array format must be:
     *
     * ```php
     * // generates: /site/index?param1=value1&param2=value2
     * ['site/index', 'param1' => 'value1', 'param2' => 'value2']
     * ```
     *
     * If you want to create a URL with an anchor, you can use the array format with a `#` parameter.
     * For example,
     *
     * ```php
     * // generates: /site/index?param1=value1#name
     * ['site/index', 'param1' => 'value1', '#' => 'name']
     * ```
     *
     * If you want to create a URL and such route is defined in any controller, for example '/site/view/{userName:\w+}',
     *
     * ```php
     * // generates: /site/view/admin
     * ['site/view', 'userName' => 'admin']
     *
     * // generates: /site/view/admin?param1=value
     * ['site/view', 'userName' => 'admin', 'param1' => 'value1']
     * ```
     *
     * The URL created is a relative one. Use [[createAbsoluteUrl()]] to create an absolute URL.
     *
     * Note that unlike [[\Reaction\Helpers\Url::toRoute()]], this method always treats the given route
     * as an absolute route.
     *
     * @param string|array             $params use a string to represent a route (e.g. `site/index`),
     * or an array to represent a route with query parameters (e.g. `['site/index', 'param1' => 'value1']`).
     * @param RequestApplicationInterface|null $app
     * @return string the created URL
     */
    public function createUrl($params, $app = null)
    {
        $params = (array)$params;
        $anchor = isset($params['#']) ? '#' . $params['#'] : '';
        unset($params['#']);

        $route = rtrim($params[0], '/');
        unset($params[0]);
        $route = $this->buildRoutePath($route, $params);

        $baseUrl = $this->getBaseUrl($app);

        if ($this->suffix !== null) {
            $route .= $this->suffix;
        }
        if (!empty($params) && ($query = http_build_query($params)) !== '') {
            $route .= '?' . $query;
        }

        $route = ltrim($route, '/');
        return "$baseUrl/{$route}{$anchor}";
    }

    /**
     * Creates an absolute URL using the given route and query parameters.
     *
     * This method prepends the URL created by [[createUrl()]] with the [[hostInfo]].
     *
     * Note that unlike [[\Reaction\Helpers\Url::toRoute()]], this method always treats the given route
     * as an absolute route.
     *
     * @param string|array             $params use a string to represent a route (e.g. `site/index`),
     * or an array to represent a route with query parameters (e.g. `['site/index', 'param1' => 'value1']`).
     * @param string|null              $scheme the scheme to use for the URL (either `http`, `https` or empty string
     * for protocol-relative URL).
     * If not specified the scheme of the current request will be used.
     * @param RequestApplicationInterface|null $app
     * @return string the created URL
     * @see createUrl()
     */
    public function createAbsoluteUrl($params, $scheme = null, $app = null)
    {
        $params = (array)$params;
        $url = $this->createUrl($params);
        if (strpos($url, '://') === false) {
            $hostInfo = $this->getHostInfo($app);
            if (strncmp($url, '//', 2) === 0) {
                $url = substr($hostInfo, 0, strpos($hostInfo, '://')) . ':' . $url;
            } else {
                $url = $hostInfo . $url;
            }
        }

        return Url::ensureScheme($url, $scheme);
    }

    /**
     * Getter for $baseUrl
     * @param RequestApplicationInterface|null $app
     * @return string
     */
    public function getBaseUrl($app = null)
    {
        if ($app !== null && $app instanceof RequestApplicationInterface) {
            return $app->reqHelper->getBaseUrl();
        }
        if ($this->_baseUrl === null) {
            throw new InvalidConfigException('Please configure UrlManager::baseUrl correctly if you are running a console application.');
        }
        return $this->_baseUrl;
    }

    /**
     * Setter for $baseUrl
     * @param string $baseUrl
     */
    public function setBaseUrl($baseUrl)
    {
        $this->_baseUrl = $baseUrl;
    }

    /**
     * Getter for $hostInfo
     * @param RequestApplicationInterface|null $app
     * @return string
     */
    public function getHostInfo($app = null)
    {
        if ($app !== null && $app instanceof RequestApplicationInterface) {
            return $app->reqHelper->getHostInfo();
        }
        if ($this->_hostInfo === null) {
            throw new InvalidConfigException('Please configure UrlManager::hostInfo correctly if you are running a console application.');
        }
        return $this->_hostInfo;
    }

    /**
     * Setter for $hostInfo
     * @param string $hostInfo
     */
    public function setHostInfo($hostInfo)
    {
        $this->_hostInfo = $hostInfo;
    }

    /**
     * Getter for $homeUrl
     * @return string
     */
    public function getHomeUrl() {
        return $this->_homeUrl;
    }

    /**
     * Setter for $homeUrl
     * @param string $homeUrl
     */
    public function setHomeUrl($homeUrl) {
        $this->_homeUrl = $homeUrl;
    }

    /**
     * Extract static part from url (without placeholders)
     * @param string $path
     * @return string
     */
    public function extractStaticPart($path) {
        $pos = $this->findPlaceholderStartPos($path);
        if ($pos !== false) {
            $prefix = substr($path, 0, $pos);
            return strlen($prefix) > 1 ? rtrim($prefix, '/') : $prefix;
        }
        return $path;
    }

    /**
     * Finds a position with first placeholder
     * @param string $path
     * @return bool|int
     */
    protected function findPlaceholderStartPos($path) {
        $brFgPos = strpos($path, '{');
        $brSqPos = strpos($path, '[');
        if ($brFgPos === false && $brSqPos === false) {
            return false;
        }
        $len = strlen($path);
        $positions = [
            $brFgPos !== false ? $brFgPos : $len,
            $brSqPos !== false ? $brSqPos : $len,
        ];
        return min($positions);
    }

    /**
     * Build route path with placeholders replace and searching in router paths
     * @param string $path
     * @param array  $params
     * @return string
     */
    protected function buildRoutePath($path, &$params) {
        $path = $this->replacePlaceholders($path, $params);
        $path = $this->searchInRouter($path, $params);
        return $path;
    }

    /**
     * Search in router for predefined paths
     * @param string $path
     * @param array  $params
     * @return string
     */
    protected function searchInRouter($path, &$params) {
        if (isset(\Reaction::$app->router->routePaths[$path])) {
            $paramsKeys = array_keys($params);
            $routes = \Reaction::$app->router->routePaths[$path];
            foreach ($routes as $routeData) {
                $intersect = array_intersect($paramsKeys, $routeData['params']);
                if (count($intersect) === count($routeData['params'])) {
                    $path = $this->replacePlaceholders($routeData['exp'], $params);
                    break;
                }
            }
            return $path;
        }
        return $path;
    }

    /**
     * Replace placeholders in path
     * @param string $path
     * @param array  $params
     * @return string
     */
    protected function replacePlaceholders($path, &$params) {
        if (strpos($path, '{') === false) {
            return $path;
        }
        $path = preg_replace_callback('/(\{([a-zA-Z0-9]+)\})/i', function($matches) use (&$params) {
            $match = $matches[1];
            $key = $matches[2];
            if (!isset($params[$key])) {
                return $match;
            }
            $replace = $params[$key];
            unset($params[$key]);
            return $replace;
        }, $path);
        return $path;
    }
}


<?php

namespace Reaction\I18n;

use Reaction;
use Reaction\Base\Component;
use Reaction\Promise\ExtendedPromiseInterface;
use function Reaction\Promise\all;
use function Reaction\Promise\resolve;

/**
 * MessageSource is the base class for message translation repository classes.
 *
 * A message source stores message translations in some persistent storage.
 *
 * Child classes should override [[loadMessages()]] to provide translated messages.
 */
class MessageSource extends Component implements MessageSourceInterface
{
    /**
     * @event MissingTranslationEvent an event that is triggered when a message translation is not found.
     */
    const EVENT_MISSING_TRANSLATION = 'missingTranslation';

    /**
     * @var bool whether to force message translation when the source and target languages are the same.
     * Defaults to false, meaning translation is only performed when source and target languages are different.
     */
    public $forceTranslation = false;
    /**
     * @var string the language that the original messages are in. If not set, it will use the value of
     * [[\Reaction\StaticApplicationInterface::sourceLanguage]].
     */
    public $sourceLanguage;
    /**
     * @var array Messages loaded. Indexed by key (language / category)
     */
    private $_messages = [];

    /**
     * Initializes this component.
     */
    public function init()
    {
        parent::init();
        if ($this->sourceLanguage === null) {
            $this->sourceLanguage = Reaction::$app->sourceLanguage;
        }
    }

    /**
     * Preload all messages from source
     * @param string $category Category or wildcard
     * @param array $languages Languages used to preload
     * @return ExtendedPromiseInterface
     */
    public function preloadMessages($category, $languages = [])
    {
        if ($category === '*') {
            $categoriesFind = $this->findAllCategories();
        } else {
            $categoriesFind = strpos($category, '*') > 0 ? $this->findCategoriesByPattern($category) : resolve([$category]);
        }
        return $categoriesFind
            ->otherwise(function() { return []; })
            ->then(function($categories) use ($languages) {
                $promises = [];
                foreach ($categories as $category) {
                    foreach ($languages as $language) {
                        $key = $language . '/' . $category;
                        $promises[$key] = $this->loadMessages($category, $language);
                    }
                }
                if (empty($promises)) {
                    return [];
                }
                return all($promises)
                    ->then(function($results) {
                        $this->_messages = Reaction\Helpers\ArrayHelper::merge($this->_messages, $results);
                        return $results;
                    });
            });
    }

    /**
     * Find categories by string pattern|wildcard
     * @param string $pattern
     * @return ExtendedPromiseInterface
     */
    protected function findCategoriesByPattern($pattern)
    {
        return $this->findAllCategories()
            ->then(function($categories) use ($pattern) {
                $matches = [];
                foreach ($categories as $category) {
                    if (Reaction\Helpers\StringHelper::matchWildcard($pattern, $category)) {
                        $matches[] = $category;
                    }
                }
                return $matches;
            });
    }

    /**
     * Find all categories used in message source
     * @return ExtendedPromiseInterface
     */
    protected function findAllCategories()
    {
        return resolve([]);
    }

    /**
     * Loads the message translation for the specified language and category.
     * If translation for specific locale code such as `en-US` isn't found it
     * tries more generic `en`.
     *
     * @param string $category the message category
     * @param string $language the target language
     * @return ExtendedPromiseInterface with array the loaded messages. The keys are original messages, and the values
     * are translated messages.
     */
    protected function loadMessages($category, $language)
    {
        return resolve([]);
    }

    /**
     * Translates a message to the specified language.
     *
     * Note that unless [[forceTranslation]] is true, if the target language
     * is the same as the [[sourceLanguage|source language]], the message
     * will NOT be translated.
     *
     * If a translation is not found, a [[EVENT_MISSING_TRANSLATION|missingTranslation]] event will be triggered.
     *
     * @param string $category the message category
     * @param string $message the message to be translated
     * @param string $language the target language
     * @return string|bool the translated message or false if translation wasn't found or isn't required
     */
    public function translate($category, $message, $language)
    {
        if ($this->forceTranslation || $language !== $this->sourceLanguage) {
            return $this->translateMessage($category, $message, $language);
        }

        return false;
    }

    /**
     * Translates the specified message.
     * If the message is not found, a [[EVENT_MISSING_TRANSLATION|missingTranslation]] event will be triggered.
     * If there is an event handler, it may provide a [[MissingTranslationEvent::$translatedMessage|fallback translation]].
     * If no fallback translation is provided this method will return `false`.
     * @param string $category the category that the message belongs to.
     * @param string $message the message to be translated.
     * @param string $language the target language.
     * @return string|bool the translated message or false if translation wasn't found.
     */
    protected function translateMessage($category, $message, $language)
    {
        $key = $language . '/' . $category;
        //No load on run, all messages must be preloaded
        //if (!isset($this->_messages[$key])) {
        //    $this->_messages[$key] = $this->loadMessages($category, $language);
        //}
        if (isset($this->_messages[$key][$message]) && $this->_messages[$key][$message] !== '') {
            return $this->_messages[$key][$message];
        } elseif ($this->hasEventListeners(self::EVENT_MISSING_TRANSLATION)) {
            $translation = null;
            $this->emit(self::EVENT_MISSING_TRANSLATION, [$this, $category, $language, $message, &$translation]);
            if ($translation !== null) {
                return $this->_messages[$key][$message] = $translation;
            }
        }

        return $this->_messages[$key][$message] = false;
    }
}


<?php

/*
 * This file is part of the Valkyrja framework.
 *
 * (c) Melech Mizrachi
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Valkyrja\Model;

use JsonSerializable;

/**
 * Class Model.
 *
 * @author Melech Mizrachi
 */
abstract class Model implements JsonSerializable
{
    /**
     * Model constructor.
     *
     * @param array $properties [optional] The properties
     */
    public function __construct(array $properties = [])
    {
        $this->fromArray($properties);
    }

    /**
     * Get a property.
     *
     * @param string $name The property to get
     *
     * @return mixed
     */
    public function __get(string $name)
    {
        $methodName = str_replace('_', '', ucwords($name, '_'));
        $methodName = 'get' . $methodName;

        if (method_exists($this, $methodName)) {
            return $this->$methodName();
        }

        return $this->{$name};
    }

    /**
     * Set a property.
     *
     * @param string $name  The property to set
     * @param mixed  $value The value to set
     *
     * @return void
     */
    public function __set(string $name, $value): void
    {
        $methodName = str_replace('_', '', ucwords($name, '_'));
        $methodName = 'set' . $methodName;

        if (method_exists($this, $methodName)) {
            $this->$methodName($value);
        }

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

    /**
     * Check if a property is set.
     *
     * @param string $name The property to check
     *
     * @return bool
     */
    public function __isset(string $name): bool
    {
        $methodName = str_replace('_', '', ucwords($name, '_'));
        $methodName = 'isset' . $methodName;

        if (method_exists($this, $methodName)) {
            return $this->$methodName();
        }

        return property_exists($this, $name);
    }

    /**
     * Set properties from an array of properties.
     *
     * @param array $properties
     *
     * @return void
     */
    public function fromArray(array $properties): void
    {
        // Iterate through the properties
        foreach ($properties as $property => $value) {
            // If the value is null or the property doesn't exist in this model
            if (null === $value || ! property_exists($this, $property)) {
                // Continue to the next property
                continue;
            }

            // Set the property
            $this->__set($property, $value);
        }
    }

    /**
     * Serialize properties for json_encode.
     *
     * @return array
     */
    public function jsonSerialize(): array
    {
        return get_object_vars($this);
    }
}


<?php

/*
 * This file is part of the Valkyrja framework.
 *
 * (c) Melech Mizrachi
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Valkyrja\Debug;

use ErrorException;
use Exception;
use Throwable;
use Valkyrja\Http\Exceptions\HttpException;
use Valkyrja\Http\Exceptions\HttpRedirectException;
use Valkyrja\Http\Response;
use Valkyrja\Http\StatusCode;
use Valkyrja\Valkyrja;

/**
 * Class ExceptionHandler.
 *
 * @author Melech Mizrachi
 */
class ExceptionHandler
{
    /**
     * Charset.
     *
     * @var string
     */
    protected $charset = 'UTF-8';

    /**
     * File link format.
     *
     * @var string
     */
    protected $fileLinkFormat;

    /**
     * Whether to display errors.
     *
     * @var bool
     */
    protected $displayErrors;

    /**
     * ExceptionHandler constructor.
     *
     * @param bool $displayErrors [optional]
     */
    public function __construct(bool $displayErrors = false)
    {
        $this->displayErrors  = $displayErrors;
        $this->fileLinkFormat = ini_get('xdebug.file_link_format')
            ?? get_cfg_var('xdebug.file_link_format');
    }

    /**
     * Handle an uncaught exception from the application.
     *
     * Note: Most exceptions can be handled via the try / catch block in
     * the HTTP and Console kernels. But, fatal error exceptions must
     * be handled differently since they are not normal exceptions.
     *
     * @param \Throwable $exception The exception that was captured
     *
     * @return void
     */
    public function handleException(Throwable $exception): void
    {
        $this->sendExceptionResponse($exception);
    }

    /**
     * Handle the PHP shutdown event.
     *
     * @return void
     */
    public function handleShutdown(): void
    {
        $error = error_get_last();

        if (
            null !== $error &&
            \in_array(
                $error['type'],
                [
                    E_ERROR,
                    E_CORE_ERROR,
                    E_COMPILE_ERROR,
                    E_PARSE,
                ],
                true
            )
        ) {
            $this->handleException($this->fatalExceptionFromError($error));
        }
    }

    /**
     * Create a new fatal exception instance from an error array.
     *
     * @param array $error The error array to use
     *
     * @return \Exception
     */
    protected function fatalExceptionFromError(array $error): Exception
    {
        return new ErrorException(
            $error['message'], 0, $error['type'], $error['file'], $error['line']
        );
    }

    /**
     * Get a response from an exception.
     *
     * @param \Throwable $exception The exception
     *
     * @return \Valkyrja\Http\Response
     */
    public function getResponse($exception): Response
    {
        if (! $exception instanceof Throwable) {
            $exception = new Exception($exception);
        }

        $headers    = [];
        $statusCode = StatusCode::INTERNAL_SERVER_ERROR;
        $content    = $this->html(
            $this->getContent($exception),
            $this->getStylesheet()
        );

        if ($exception instanceof HttpException) {
            foreach ($exception->getHeaders() as $name => $value) {
                $headers[$name] = $value;
            }

            $statusCode = $exception->getStatusCode();
        }

        if ($exception instanceof HttpRedirectException) {
            $response = Valkyrja::app()->redirect(
                $exception->getUri(),
                $statusCode,
                $headers
            );
        } else {
            $response = Valkyrja::app()->response(
                $content,
                $statusCode,
                $headers
            );
        }

        $response->setCharset($this->charset);

        return $response;
    }

    /**
     * Send response.
     *
     * @param \Throwable $exception The exception
     *
     * @return void
     */
    public function sendResponse($exception): void
    {
        $this->getResponse($exception)->send();
    }

    /**
     * Send response.
     *
     * @param \Throwable $exception
     *
     * @return void
     */
    public function sendExceptionResponse($exception): void
    {
        if (! headers_sent()) {
            if ($exception instanceof HttpException) {
                header(sprintf('HTTP/1.0 %s', $exception->getStatusCode()));

                foreach ($exception->getHeaders() as $name => $value) {
                    header($name . ': ' . $value, false);
                }
            }

            header('Content-Type: text/html; charset=' . $this->charset);
        }

        echo $this->html($this->getContent($exception), $this->getStylesheet());
    }

    /**
     * Gets the HTML content associated with the given exception.
     *
     * @param \Throwable $exception A FlattenException instance
     *
     * @return string The content as a string
     */
    public function getContent(Throwable $exception): string
    {
        $title = 'Whoops, looks like something went wrong.';

        if (
            $exception instanceof HttpException
            && $exception->getStatusCode() === 404
        ) {
            $title = 'Sorry, the page you are looking for could not be found.';
        }

        $content = '';

        if ($this->displayErrors) {
            try {
                $exceptions = [
                    $exception,
                ];
                $e          = $exception;

                while ($e = $e->getPrevious()) {
                    $exceptions[] = $e;
                }

                $count = \count($exceptions);
                $total = $count;

                /**
                 * @var int
                 * @var \Throwable $e
                 */
                foreach ($exceptions as $position => $e) {
                    $ind     = $count - $position;
                    $class   = $this->formatClass(\get_class($e));
                    $message = nl2br($this->escapeHtml($e->getMessage()));
                    $content .= sprintf(
                        <<<'EOF'

                            %d/%d
                            %s%s:
                            %s

EOF
                        ,
                        $ind,
                        $total,
                        $class,
                        $this->formatPath(
                            $e->getTrace()[0]['file'] ?? 'Unknown file',
                            $e->getTrace()[0]['line'] ?? 0
                        ),
                        $message
                    );

                    foreach ($e->getTrace() as $trace) {
                        $traceClass    = $trace['class'] ?? '';
                        $traceArgs     = $trace['args'] ?? [];
                        $traceType     = $trace['type'] ?? '';
                        $traceFunction = $trace['function'] ?? '';

                        $content .= '
';

                        if ($trace['function']) {
                            $content .= sprintf(
                                'at %s%s%s(%s)',
                                $this->formatClass($traceClass),
                                $traceType,
                                $traceFunction,
                                $this->formatArgs($traceArgs)
                            );
                        }

                        if (isset($trace['file'], $trace['line'])) {
                            $content .= $this->formatPath(
                                $trace['file'],
                                $trace['line']
                            );
                        }

                        $content .= "
\n";
                    }

                    $content .= "
\n
\n";
                }
            } catch (Exception $e) {
                // Something nasty happened and we cannot throw an exception anymore
                $title = sprintf(
                    'Exception thrown when handling an exception (%s: %s)',
                    \get_class($e),
                    $this->escapeHtml($e->getMessage())
                );
            }
        }

        return <<<EOF

$title

                $content

EOF;
    }

    /**
     * Gets the stylesheet associated with the given exception.
     *
     * @return string The stylesheet as a string
     */
    public function getStylesheet(): string
    {
        return <<<'EOF'
            .sf-reset { font: 11px Verdana, Arial, sans-serif; color: #333 }
            .sf-reset .clear { clear:both; height:0; font-size:0; line-height:0; }
            .sf-reset .clear_fix:after { display:block; height:0; clear:both; visibility:hidden; }
            .sf-reset .clear_fix { display:inline-block; }
            .sf-reset * html .clear_fix { height:1%; }
            .sf-reset .clear_fix { display:block; }
            .sf-reset, .sf-reset .block { margin: auto }
            .sf-reset abbr { border-bottom: 1px dotted #000; cursor: help; }
            .sf-reset p { font-size:14px; line-height:20px; color:#868686; padding-bottom:20px }
            .sf-reset strong { font-weight:bold; }
            .sf-reset a { color:#6c6159; cursor: default; }
            .sf-reset a img { border:none; }
            .sf-reset a:hover { text-decoration:underline; }
            .sf-reset em { font-style:italic; }
            .sf-reset h1, .sf-reset h2 { font: 20px Georgia, "Times New Roman", Times, serif }
            .sf-reset .exception_counter { background-color: #fff; color: #333; padding: 6px; float: left; margin-right: 10px; float: left; display: block; }
            .sf-reset .exception_title { margin-left: 3em; margin-bottom: 0.7em; display: block; }
            .sf-reset .exception_message { margin-left: 3em; display: block; }
            .sf-reset .traces li { font-size:12px; padding: 2px 4px; list-style-type:decimal; margin-left:20px; }
            .sf-reset .block { background-color:#FFFFFF; padding:10px 28px; margin-bottom:20px;
                -webkit-border-bottom-right-radius: 16px;
                -webkit-border-bottom-left-radius: 16px;
                -moz-border-radius-bottomright: 16px;
                -moz-border-radius-bottomleft: 16px;
                border-bottom-right-radius: 16px;
                border-bottom-left-radius: 16px;
                border-bottom:1px solid #ccc;
                border-right:1px solid #ccc;
                border-left:1px solid #ccc;
            }
            .sf-reset .block_exception { background-color:#ddd; color: #333; padding:20px;
                -webkit-border-top-left-radius: 16px;
                -webkit-border-top-right-radius: 16px;
                -moz-border-radius-topleft: 16px;
                -moz-border-radius-topright: 16px;
                border-top-left-radius: 16px;
                border-top-right-radius: 16px;
                border-top:1px solid #ccc;
                border-right:1px solid #ccc;
                border-left:1px solid #ccc;
                overflow: hidden;
                word-wrap: break-word;
            }
            .sf-reset a { background:none; color:#868686; text-decoration:none; }
            .sf-reset a:hover { background:none; color:#313131; text-decoration:underline; }
            .sf-reset ol { padding: 10px 0; }
            .sf-reset h1 { background-color:#FFFFFF; padding: 15px 28px; margin-bottom: 20px;
                -webkit-border-radius: 10px;
                -moz-border-radius: 10px;
                border-radius: 10px;
                border: 1px solid #ccc;
            }
EOF;
    }

    /**
     * Decorate the html response.
     *
     * @param string $content
     * @param string $css
     *
     * @return string
     */
    public function html(string $content, string $css): string
    {
        return <<<EOF
            <!DOCTYPE html>

                    <meta charset="{$this->charset}" />
                    <meta name="robots" content="noindex,nofollow" />

                    $content

EOF;
    }

    /**
     * Format class.
     *
     * @param string $class
     *
     * @return string
     */
    protected function formatClass(string $class): string
    {
        $parts = explode('\\', $class);

        return sprintf('%s', $class, array_pop($parts));
    }

    /**
     * Format path.
     *
     * @param string $path
     * @param int    $line
     *
     * @return string
     */
    protected function formatPath(string $path, int $line): string
    {
        $path = $this->escapeHtml($path);
        $file = preg_match('#[^/\\\\]*$#', $path, $file)
            ? $file[0]
            : $path;

        if ($linkFormat = $this->fileLinkFormat) {
            $link = strtr(
                $this->escapeHtml($linkFormat),
                ['%f' => $path, '%l' => $line]
            );

            return sprintf(
                ' in %s line %d',
                $link,
                $file,
                $line
            );
        }

        return sprintf(
            ' in %s line %d',
            $path,
            $file,
            $line
        );
    }

    /**
     * Formats an array as a string.
     *
     * @param array $args The argument array
     *
     * @return string
     */
    protected function formatArgs(array $args): string
    {
        $result = [];

        foreach ($args as $key => $item) {
            if (\is_object($item)) {
                $formattedValue = sprintf(
                    'object(%s)',
                    $this->formatClass(\get_class($item))
                );
            } elseif (\is_array($item)) {
                $formattedValue = sprintf(
                    'array(%s)',
                    $this->formatArgs($item)
                );
            } elseif (\is_string($item)) {
                $formattedValue = sprintf("'%s'", $this->escapeHtml($item));
            } elseif (null === $item) {
                $formattedValue = 'null';
            } elseif (\is_bool($item)) {
                $formattedValue = ''
                    . strtolower(var_export($item, true))
                    . '';
            } elseif (\is_resource($item)) {
                $formattedValue = 'resource';
            } else {
                $formattedValue = str_replace(
                    "\n",
                    '',
                    var_export($this->escapeHtml((string) $item), true)
                );
            }

            $result[] = \is_int($key)
                ? $formattedValue
                : sprintf("'%s' => %s", $key, $formattedValue);
        }

        return implode(', ', $result);
    }

    /**
     * Escape HTML.
     *
     * @param string $str
     *
     * @return string
     */
    protected function escapeHtml(string $str): string
    {
        return htmlspecialchars(
            $str,
            ENT_QUOTES | ENT_SUBSTITUTE,
            $this->charset
        );
    }
}


<?php

namespace Oxygen\Data\Validation\Laravel;

use Illuminate\Validation\Factory;
use Illuminate\Validation\Validator;
use Illuminate\Support\MessageBag;
use Oxygen\Data\Validation\ValidationService;

class LaravelValidationService implements ValidationService {

    /**
     * The Validation Factory.
     *
     * @var \Illuminate\Validation\Factory
     */

    protected $factory;

    /**
     * The Laravel validator instance.
     *
     * @var \Illuminate\Validation\Validator
     */

    protected $validator;

    /**
     * Constructs the LaravelValidationService.
     *
     * @param Factory $factory
     */
    public function __construct(Factory $factory) {
        $this->factory = $factory;
    }

    /**
     * Sets the data to be validated.
     *
     * @param array $data
     * @param array $rules
     * @return mixed
     */
    public function with(array $data, array $rules) {
        $this->validator = $this->factory->make($data, $rules);
    }

    /**
     * Does the validator pass?
     *
     * @return boolean
     */
    public function passes() {
        return $this->validator->passes();
    }

    /**
     * Returns the validation errors
     *
     * @return MessageBag
     */
    public function errors() {
        return $this->validator->errors();
    }
}


<?php

namespace Yami\SheetFight\Model;

use InvalidArgumentException;

/**
 * Provides a parser to transform a string to a collection of Input.
 *
 * @author Kevin GITTENS <kgittens973@gmail.com>
 * @author Ludovic FLEURY <ludo.fleury@gmail.com>
 */
class InputParser implements InputParserInterface
{
    /**
     * Transform a string to a collection of Input.
     *
     * @param string $string
     *
     * @return InputInterface[]
     */
    public function transforms($string)
    {
        if (!is_string($string)) {
            throw new InvalidArgumentException('A string is required');
        }
        if (false == preg_match('#^[a-zA-Z0-9]+$#', $string)) {
            throw new InvalidArgumentException('A valid string is required');
        }
        $inputs = [];
        $splitted = str_split($string);

        foreach ($splitted as $value) {
            $inputs[] = new Input($value);
        }

        return $inputs;
    }
}


<?php

/*
 * This file is part of the MimeSniffer package.
 *
 * (c) Stephan Wentz <stephan@wentz.it>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Temp\MediaClassifier\Loader;

use Temp\MediaClassifier\Model\MediaType;
use Temp\MediaClassifier\Model\MediaTypeCollection;

/**
 * XML media type loader.
 *
 * @author Stephan Wentz <stephan@wentz.it>
 */
class XmlLoader implements LoaderInterface
{
    /**
     * {@inheritdoc}
     */
    public function supports($file)
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function load($filename)
    {
        $mediaTypes = new MediaTypeCollection();

        $xml = simplexml_load_file($filename);

        foreach ($xml->mediatype as $mediatypeNode) {
            $attrs = $mediatypeNode->attributes();
            $name = (string) $attrs['name'];
            $category = (string) $attrs['category'];

            $mimetypes = [];
            if ($mediatypeNode->mimetypes->count() && $mediatypeNode->mimetypes->mimetype->count()) {
                foreach ($mediatypeNode->mimetypes->mimetype as $mimetypeNode) {
                    $mimetypes[] = (string) $mimetypeNode;
                }
            }

            $attributes = [];
            if ($mediatypeNode->attributes->count() && $mediatypeNode->attributes->attribute->count()) {
                foreach ($mediatypeNode->attributes->attribute as $attributeNode) {
                    $attrs = $attributeNode->attributes();
                    $attributes[(string) $attrs['key']] = (string) $attributeNode;
                }
            }

            $mediaType = new MediaType($name, $category, $mimetypes, $attributes);

            $mediaTypes->add($mediaType);
        }

        return $mediaTypes;
    }
}