<?php namespace Ordercloud\Entities\Products;

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

class ProductDiscount implements JsonSerializable
{
    /** @var integer */
    private $id;
    /** @var OrganisationShort */
    private $organisation;
    /** @var OrganisationShort */
    private $discountProvider;
    /** @var OrganisationShort */
    private $brand;
    /** @var ConnectionShort */
    private $connection;
    /** @var ProductShort */
    private $productItem;
    /** @var float */
    private $amount;
    /** @var string */
    private $startDate;
    /** @var boolean */
    private $enabled;
    /**
     * @var string
     */
    private $endDate;

    public function __construct($id, OrganisationShort $organisation = null, OrganisationShort $discountProvider, OrganisationShort $brand = null, ConnectionShort $connection = null, ProductShort $productItem = null, $amount, $startDate = null, $endDate = null, $enabled)
    {
        $this->id = $id;
        $this->organisation = $organisation;
        $this->discountProvider = $discountProvider;
        $this->brand = $brand;
        $this->connection = $connection;
        $this->productItem = $productItem;
        $this->amount = $amount;
        $this->startDate = $startDate;
        $this->endDate = $endDate;
        $this->enabled = $enabled;
    }

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

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

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

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

    /**
     * @return ConnectionShort
     */
    public function getConnection()
    {
        return $this->connection;
    }

    /**
     * @return ProductShort
     */
    public function getProductItem()
    {
        return $this->productItem;
    }

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

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

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

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

    /**
     * Specify data which should be serialized to JSON
     */
    public function jsonSerialize()
    {
        return [
            'id'               => $this->getId(),
            'organisation'     => $this->getOrganisation(),
            'discountProvider' => $this->getDiscountProvider(),
            'brand'            => $this->getBrand(),
            'connection'       => $this->getConnection(),
            'productItem'      => $this->getProductItem(),
            'amount'           => $this->getAmount(),
            'startDate'        => $this->getStartDate(),
            'endDate'          => $this->getEndDate(),
            'enabled'          => $this->isEnabled(),
        ];
    }
}


<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Filter
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Null.php 24593 2012-01-05 20:35:02Z matthew $
 */

/**
 * @see Zend_Filter_Interface
 */

/**
 * @category   Zend
 * @package    Zend_Filter
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Filter_Null implements Zend_Filter_Interface
{
    const BOOLEAN      = 1;
    const INTEGER      = 2;
    const EMPTY_ARRAY  = 4;
    const STRING       = 8;
    const ZERO         = 16;
    const ALL          = 31;

    protected $_constants = array(
        self::BOOLEAN     => 'boolean',
        self::INTEGER     => 'integer',
        self::EMPTY_ARRAY => 'array',
        self::STRING      => 'string',
        self::ZERO        => 'zero',
        self::ALL         => 'all'
    );

    /**
     * Internal type to detect
     *
     * @var integer
     */
    protected $_type = self::ALL;

    /**
     * Constructor
     *
     * @param string|array|Zend_Config $options OPTIONAL
     */
    public function __construct($options = null)
    {
        if ($options instanceof Zend_Config) {
            $options = $options->toArray();
        } else if (!is_array($options)) {
            $options = func_get_args();
            $temp    = array();
            if (!empty($options)) {
                $temp = array_shift($options);
            }
            $options = $temp;
        } else if (is_array($options) && array_key_exists('type', $options)) {
            $options = $options['type'];
        }

        if (!empty($options)) {
            $this->setType($options);
        }
    }

    /**
     * Returns the set null types
     *
     * @return array
     */
    public function getType()
    {
        return $this->_type;
    }

    /**
     * Set the null types
     *
     * @param  integer|array $type
     * @throws Zend_Filter_Exception
     * @return Zend_Filter_Null
     */
    public function setType($type = null)
    {
        if (is_array($type)) {
            $detected = 0;
            foreach($type as $value) {
                if (is_int($value)) {
                    $detected += $value;
                } else if (in_array($value, $this->_constants)) {
                    $detected += array_search($value, $this->_constants);
                }
            }

            $type = $detected;
        } else if (is_string($type)) {
            if (in_array($type, $this->_constants)) {
                $type = array_search($type, $this->_constants);
            }
        }

        if (!is_int($type) || ($type < 0) || ($type > self::ALL)) {

            throw new Zend_Filter_Exception('Unknown type');
        }

        $this->_type = $type;
        return $this;
    }

    /**
     * Defined by Zend_Filter_Interface
     *
     * Returns null representation of $value, if value is empty and matches
     * types that should be considered null.
     *
     * @param  string $value
     * @return string
     */
    public function filter($value)
    {
        $type = $this->getType();

        // STRING ZERO ('0')
        if ($type >= self::ZERO) {
            $type -= self::ZERO;
            if (is_string($value) && ($value == '0')) {
                return null;
            }
        }

        // STRING ('')
        if ($type >= self::STRING) {
            $type -= self::STRING;
            if (is_string($value) && ($value == '')) {
                return null;
            }
        }

        // EMPTY_ARRAY (array())
        if ($type >= self::EMPTY_ARRAY) {
            $type -= self::EMPTY_ARRAY;
            if (is_array($value) && ($value == array())) {
                return null;
            }
        }

        // INTEGER (0)
        if ($type >= self::INTEGER) {
            $type -= self::INTEGER;
            if (is_int($value) && ($value == 0)) {
                return null;
            }
        }

        // BOOLEAN (false)
        if ($type >= self::BOOLEAN) {
            $type -= self::BOOLEAN;
            if (is_bool($value) && ($value == false)) {
                return null;
            }
        }

        return $value;
    }
}


<?php

namespace Encore\Resource;

use InvalidArgumentException;
use Encore\Filesystem\Filesystem;

class FileFinder implements FinderInterface
{
    use FinderTrait;

    protected $fs;
    protected $paths = [];
    protected $resolved = [];
    protected $extensions = [];

    public function __construct(Filesystem $fs, array $paths)
    {
        $this->fs = $fs;
        $this->paths = $paths;
    }

    /**
     * Get the fully qualified location of the view.
     *
     * @param string $view
     * @return string
     */
    public function find($name)
    {
        if (isset($this->resolved[$name])) return $this->resolved[$name];

        if (strpos($name, '::') !== false) {
            return $this->resolved[$name] = $this->findNamedPathView($name);
        }

        return $this->resolved[$name] = $this->findInPaths($name, $this->paths);
    }

    /**
     * Find the file in the possible paths
     *
     * @param  string $name
     * @param  array  $paths
     * @throws InvalidArgumentException
     * @return string Path the the view
     */
    protected function findInPaths($name, array $paths)
    {
        foreach ($paths as $path) {
            foreach ($this->getPossibleFiles($name) as $file) {

                if ($this->fs->exists($viewPath = $path.'/'.$file)) {
                    return $viewPath;
                }

            }
        }

        throw new InvalidArgumentException("Resource '$name' not found.");
    }

    /**
     * Get an array of possible files.
     *
     * @param string $name
     * @return array
     */
    protected function getPossibleFiles($name)
    {
        return array_map(function($extension) use ($name) {
            return str_replace('.', '/', $name).'.'.$extension;
        }, $this->extensions);
    }
}


<?php

namespace QCharts\ApiBundle\Controller;

use QCharts\ApiBundle\Exception\InvalidCredentialsException;
use QCharts\CoreBundle\Exception\InstanceNotFoundException;
use QCharts\CoreBundle\Exception\NotFoundException;
use QCharts\CoreBundle\Exception\SnapshotException;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;

/**
 * Class SnapshotController
 * @package QCharts\ApiBundle\Controller
 */
class SnapshotController extends Controller
{
    /**
     *
     * ApiDoc(
     *     description = "Returns the list of snapshots from the queried Query",
     *     parameters = {
     *          {
     *              "name" = "q",
     *              "required" = true,
     *              "description" = "Query Id",
     *              "dataType" = "string"
     *          }
     *     },
     *     statusCodes = {
     *          200 = "The snapshot list was returned",
     *          558 = "Query does not support snapshots",
     *          402 = "Credentials not valid",
     *          454 = "Snapshot directory not found, snapshot was not yet created"
     *     }
     * )
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function snapshotListAction(Request $request)
    {
        $authService = $this->get("security.authorization_checker");
        $roles = $this->getParameter("qcharts.user_roles");
        $allow_demo_users = $this->getParameter("qcharts.allow_demo_users");
        $options = [];
        try
        {
            ApiController::checkCredentials($authService, $roles, "user", $allow_demo_users);
            $snapshotService = $this->get("qcharts.core.snapshot_service");
            $queryService = $this->get("qcharts.query");
            $queryId = $request->query->get("q", null);
            if (is_null($queryId))
            {
                throw new InstanceNotFoundException("Query not passed", 404);
            }
            $queryRequest = $queryService->getQueryRequestById($queryId);
            $snapshots = $snapshotService->getSnapshotsFormatted($queryRequest);

            $options = [
                "status" => 200,
                "textStatus" => "Snapshots were returned",
                "snapshots" => $snapshots
            ];
        }
        catch (InvalidCredentialsException $e)
        {
            $options = [
                "status" => $e->getCode(),
                "textStatus" => $e->getMessage()
            ];
        }
        catch (InstanceNotFoundException $e)
        {
            $options = [
                "status" => $e->getCode(),
                "textStatus" => $e->getMessage()
            ];
        }
        catch (SnapshotException $e)
        {
            $options = [
                "status" => $e->getCode(),
                "textStatus" => $e->getMessage()
            ];
        }
        catch (IOException $e)
        {
            $options = [
                "status" => $e->getCode(),
                "textStatus" => $e->getMessage()
            ];
        }
        finally
        {
            return new JsonResponse($options);
        }

    }

    /**
     *
     * ApiDoc(
     *     description = "Download snapshot file",
     *     parameters = {
     *          {
     *              "name" = "q",
     *              "description" = "Query Request Id to get the desired snapshot",
     *              "dataType" = "integer",
     *              "required" = true
     *          }, {
     *              "name" = "snapshot",
     *              "description" = "The desired snapshot to download, if absent the most recent will be returned",
     *              "dataType" = "string",
     *              "required" = false
     *          }
     *     }, statusCodes = {
     *          402 = "Credentials not valid"
     *     }
     * )
     *
     * @param Request $request
     * @return JsonResponse|BinaryFileResponse
     */
    public function downLoadSnapshotAction(Request $request)
    {
        $authChecker = $this->get("security.authorization_checker");
        $roles = $this->getParameter("qcharts.user_roles");
        $allow_demo_users = $this->getParameter("qcharts.allow_demo_users");
        $response = null;

        try
        {
            ApiController::checkCredentials($authChecker, $roles, "user", $allow_demo_users);
            $snapshotService = $this->get("qcharts.core.snapshot_service");
            $queryService = $this->get("qcharts.query");

            $queryRequest = $request->query->get("q");
            $snapshotName = $request->query->get("snapshot", null);

            $queryRequest = $queryService->getQueryRequestById($queryRequest);
            $file = $snapshotService->getSnapshotFile($queryRequest, $snapshotName);

            $response =  new BinaryFileResponse($file);
            $response->trustXSendfileTypeHeader();
            $response->headers->set("Content-Type", "text/csv");
            $fileName = substr($file->getFilename(), 0, -4);
            $fileName = "{$snapshotService->formatSnapshotName($queryRequest, $fileName)}.csv";
            $response->setContentDisposition(
                ResponseHeaderBag::DISPOSITION_INLINE,
                $fileName,
                iconv('UTF-8', 'ASCII//TRANSLIT', $fileName));
        }
        catch (InvalidCredentialsException $e)
        {
            $response = new JsonResponse(ApiController::getNotValidCredentials());
        }
        catch (InstanceNotFoundException $e)
        {
            $response = new JsonResponse([
                "status" => $e->getCode(),
                "textStatus" => $e->getMessage()
            ]);
        }
        catch (SnapshotException $e)
        {
            $response = new JsonResponse([
                "status" => $e->getCode(),
                "textStatus" => $e->getMessage()
            ]);
        }
        catch(NotFoundException $e)
        {
            $response = new JsonResponse([
                "status" => $e->getCode(),
                "textStatus" => $e->getMessage()
            ]);
        }
        finally
        {
            return $response;
        }
    }

    /**
     * ApiDoc(
     *     description = "Deletes the requested snapshot file",
     *     parameters = {
     *          {
     *              "name" = "snapshot",
     *              "dataType" = "integer",
     *              "description" = "The snapshot name to delete",
     *              "required" = true
     *          },
     *          {
     *              "name" = "q",
     *              "dataType" = "integer",
     *              "description" = "Query request that has the snapshot",
     *              "required" = true
     *          }
     *     },
     *     statusCodes = {
     *          202 = "Snapshot deleted",
     *          402 = "Credentials invalid"
     *     }
     * )
     * @param Request $request
     * @return JsonResponse
     */
    public function deleteSnapshotAction(Request $request)
    {
        $options = [];
        $authChecker = $this->get("security.authorization_checker");
        $roles = $this->getParameter("qcharts.user_roles");
        try
        {
            ApiController::checkCredentials($authChecker, $roles, ApiController::SUPER_ADMIN);

            $snapshotService = $this->get("qcharts.core.snapshot_service");
            $queryService = $this->get("qcharts.query");

            $snapshotId = $request->request->get("snapshot", null);
            $queryId = $request->request->get("q", null);

            $queryRequest = $queryService->getQueryRequestById($queryId);
            $snapshot = $snapshotService->getSnapshotFile($queryRequest, $snapshotId);

            $snapshotService->deleteSnapshot($queryRequest, $snapshot);

            $options = [
                "status" => 202,
                "textStatus" => "The snapshot was deleted"
            ];
        }
        catch (InvalidCredentialsException $e)
        {
            $options = ApiController::getNotValidCredentials();
        }
        catch (SnapshotException $e)
        {
            $options = [
                "status" => $e->getCode(),
                "textStatus" => $e->getMessage()
            ];
        }
        catch (InstanceNotFoundException $e)
        {
            $options = [
                "status" => $e->getCode(),
                "textStatus" => $e->getMessage()
            ];
        }
        finally
        {
            return new JsonResponse($options);
        }
    }

}


<?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\Session;

use Valkyrja\Application;
use Valkyrja\Session\Exceptions\InvalidSessionId;
use Valkyrja\Session\Exceptions\SessionStartFailure;
use Valkyrja\Support\Providers\Provides;

/**
 * Class Session.
 *
 * @author Melech Mizrachi
 */
class NativeSession implements Session
{
    use Provides;

    /**
     * The application.
     *
     * @var \Valkyrja\Application
     */
    protected $app;

    /**
     * The session data.
     *
     * @var array
     */
    protected $data = [];

    /**
     * Whether the session has been started.
     *
     * @var bool
     */
    protected $started;

    /**
     * Session constructor.
     *
     * @param Application $application The application
     * @param string      $sessionId   [optional] The session id
     * @param string      $sessionName [optional] The session name
     *
     * @throws \Valkyrja\Session\Exceptions\InvalidSessionId
     * @throws \Valkyrja\Session\Exceptions\SessionStartFailure
     */
    public function __construct(Application $application, string $sessionId = null, string $sessionName = null)
    {
        $this->app = $application;

        $sessionId   = $sessionId ?? $this->app->config()['session']['id'];
        $sessionName = $sessionName ?? $this->app->config()['session']['name'];

        // If a session id is provided
        if (null !== $sessionId) {
            // Set the id
            $this->setId($sessionId);
        }

        // If a session name is provided
        if (null !== $sessionName) {
            // Set the name
            $this->setName($sessionName);
        }

        // Start the session
        $this->start();
    }

    /**
     * Start the session.
     *
     * @throws \Valkyrja\Session\Exceptions\SessionStartFailure
     *
     * @return void
     */
    public function start(): void
    {
        // If the session is already active
        if ($this->isActive() || headers_sent()) {
            // No need to reactivate
            return;
        }

        // If the session failed to start
        if (! session_start()) {
            // Throw a new exception
            throw new SessionStartFailure('The session failed to start!');
        }

        // Set the data
        $this->data = &$_SESSION;
    }

    /**
     * Get the session id.
     *
     * @return string
     */
    public function id(): string
    {
        return session_id();
    }

    /**
     * Set the session id.
     *
     * @param string $id The session id
     *
     * @throws \Valkyrja\Session\Exceptions\InvalidSessionId
     *
     * @return void
     */
    public function setId(string $id): void
    {
        if (! preg_match('/^[-,a-zA-Z0-9]{1,128}$/', $id)) {
            throw new InvalidSessionId(
                "The session id, '{$id}', is invalid! "
                . 'Session id can only contain alpha numeric characters, dashes, commas, '
                . 'and be at least 1 character in length but up to 128 characters long.'
            );
        }

        session_id($id);
    }

    /**
     * Get the session name.
     *
     * @return string
     */
    public function name(): string
    {
        return session_name();
    }

    /**
     * Set the session name.
     *
     * @param string $name The session name
     *
     * @return void
     */
    public function setName(string $name): void
    {
        session_name($name);
    }

    /**
     * Is a session active?
     *
     * @return bool
     */
    public function isActive(): bool
    {
        return PHP_SESSION_ACTIVE === session_status();
    }

    /**
     * Determine whether the session has an item.
     *
     * @param string $id The item id
     *
     * @return bool
     */
    public function has(string $id): bool
    {
        return isset($this->data[$id]);
    }

    /**
     * Get an item from the session.
     *
     * @param string $id The item id
     *
     * @return mixed
     */
    public function get(string $id)
    {
        return $this->has($id) ? $this->data[$id] : null;
    }

    /**
     * Set an item into the session.
     *
     * @param string $id    The id
     * @param string $value The value
     *
     * @return void
     */
    public function set(string $id, string $value): void
    {
        $this->data[$id] = $value;
    }

    /**
     * Remove a session item.
     *
     * @param string $id The item id
     *
     * @return bool
     */
    public function remove(string $id): bool
    {
        if (! $this->has($id)) {
            return false;
        }

        unset($this->data[$id]);

        return true;
    }

    /**
     * Get a csrf token for a unique token id.
     *
     * @param string $id The csrf unique token id
     *
     * @throws \Exception
     *
     * @return string
     */
    public function csrf(string $id): string
    {
        $token = bin2hex(random_bytes(64));

        $this->set($id, $token);

        return $token;
    }

    /**
     * Validate a csrf token.
     *
     * @param string $id    The csrf unique token id
     * @param string $token The token to validate
     *
     * @return bool
     */
    public function validateCsrf(string $id, string $token): bool
    {
        if (! $this->has($id)) {
            return false;
        }

        $sessionToken = $this->get($id);

        if (! \is_string($sessionToken)) {
            return false;
        }

        $this->remove($id);

        return hash_equals($token, $sessionToken);
    }

    /**
     * Clear the local session.
     *
     * @return void
     */
    public function clear(): void
    {
        $this->data = [];

        session_unset();
    }

    /**
     * Destroy the session.
     *
     * @return void
     */
    public function destroy(): void
    {
        $this->data = [];

        session_unset();
    }

    /**
     * The items provided by this provider.
     *
     * @return array
     */
    public static function provides(): array
    {
        return [
            Session::class,
        ];
    }

    /**
     * Publish the provider.
     *
     * @param Application $app The application
     *
     * @throws \Valkyrja\Session\Exceptions\InvalidSessionId
     * @throws \Valkyrja\Session\Exceptions\SessionStartFailure
     *
     * @return void
     */
    public static function publish(Application $app): void
    {
        $app->container()->singleton(
            Session::class,
            new static($app)
        );
    }
}


<?php

namespace tourze\Http\Exception;

use tourze\Base\Exception\BaseException;
use tourze\Http\Http;

class Http401Exception extends ExpectedException
{

    /**
     * @var int
     */
    protected $_code = Http::UNAUTHORIZED;

    /**
     * 指定基础认证的提示信息
     *
     * @param  string $challenge 基础认证返回信息，如`Basic realm="Control Panel"`
     * @return $this
     */
    public function authenticate($challenge = null)
    {
        if (null === $challenge)
        {
            return $this->headers('www-authenticate');
        }

        $this->headers('www-authenticate', $challenge);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function check()
    {
        if (null === $this->headers('www-authenticate'))
        {
            throw new BaseException("A 'www-authenticate' header must be specified for a HTTP 401 Unauthorized");
        }

        return true;
    }

}


<?php
namespace ROH\Util;

class Inflector
{
    /**
     * Plural inflector rules
     *
     * @var array
     */
    private static $plural = array(
        'rules' => array(
            '/(s)tatus$/i' => '\1\2tatuses',
            '/(quiz)$/i' => '\1zes',
            '/^(ox)$/i' => '\1\2en',
            '/([m|l])ouse$/i' => '\1ice',
            '/(matr|vert|ind)(ix|ex)$/i' => '\1ices',
            '/(x|ch|ss|sh)$/i' => '\1es',
            '/([^aeiouy]|qu)y$/i' => '\1ies',
            '/(hive)$/i' => '\1s',
            '/(?:([^f])fe|([lr])f)$/i' => '\1\2ves',
            '/sis$/i' => 'ses',
            '/([ti])um$/i' => '\1a',
            '/(p)erson$/i' => '\1eople',
            '/(m)an$/i' => '\1en',
            '/(c)hild$/i' => '\1hildren',
            '/(buffal|tomat)o$/i' => '\1\2oes',
            '/(alumn|bacill|cact|foc|fung|nucle|radi|stimul|syllab|termin|vir)us$/i' => '\1i',
            '/us$/i' => 'uses',
            '/(alias)$/i' => '\1es',
            '/(ax|cris|test)is$/i' => '\1es',
            '/s$/' => 's',
            '/^$/' => '',
            // '/$/' => 's',
        ),
        'uninflected' => array(
            '.*[nrlm]ese', '.*deer', '.*fish', '.*measles', '.*ois', '.*pox', '.*sheep', 'people', 'cookie'
        ),
        'irregular' => array(
            'atlas' => 'atlases',
            'beef' => 'beefs',
            'brother' => 'brothers',
            'cafe' => 'cafes',
            'child' => 'children',
            'cookie' => 'cookies',
            'corpus' => 'corpuses',
            'cow' => 'cows',
            'ganglion' => 'ganglions',
            'genie' => 'genies',
            'genus' => 'genera',
            'graffito' => 'graffiti',
            'hoof' => 'hoofs',
            'loaf' => 'loaves',
            'man' => 'men',
            'money' => 'monies',
            'mongoose' => 'mongooses',
            'move' => 'moves',
            'mythos' => 'mythoi',
            'niche' => 'niches',
            'numen' => 'numina',
            'occiput' => 'occiputs',
            'octopus' => 'octopuses',
            'opus' => 'opuses',
            'ox' => 'oxen',
            'penis' => 'penises',
            'person' => 'people',
            'sex' => 'sexes',
            'soliloquy' => 'soliloquies',
            'testis' => 'testes',
            'trilby' => 'trilbys',
            'turf' => 'turfs'
        )
    );

    /**
     * Singular inflector rules
     *
     * @var array
     */
    private static $singular = array(
        'rules' => array(
            '/(s)tatuses$/i' => '\1\2tatus',
            '/^(.*)(menu)s$/i' => '\1\2',
            '/(quiz)zes$/i' => '\\1',
            '/(matr)ices$/i' => '\1ix',
            '/(vert|ind)ices$/i' => '\1ex',
            '/^(ox)en/i' => '\1',
            '/(alias)(es)*$/i' => '\1',
            '/(alumn|bacill|cact|foc|fung|nucle|radi|stimul|syllab|termin|viri?)i$/i' => '\1us',
            '/([ftw]ax)es/i' => '\1',
            '/(cris|ax|test)es$/i' => '\1is',
            '/(shoe|slave)s$/i' => '\1',
            '/(o)es$/i' => '\1',
            '/ouses$/' => 'ouse',
            '/([^a])uses$/' => '\1us',
            '/([m|l])ice$/i' => '\1ouse',
            '/(x|ch|ss|sh)es$/i' => '\1',
            '/(m)ovies$/i' => '\1\2ovie',
            '/(s)eries$/i' => '\1\2eries',
            '/([^aeiouy]|qu)ies$/i' => '\1y',
            '/([lr])ves$/i' => '\1f',
            '/(tive)s$/i' => '\1',
            '/(hive)s$/i' => '\1',
            '/(drive)s$/i' => '\1',
            '/([^fo])ves$/i' => '\1fe',
            '/(^analy)ses$/i' => '\1sis',
            '/(analy|diagno|^ba|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i' => '\1\2sis',
            '/([ti])a$/i' => '\1um',
            '/(p)eople$/i' => '\1\2erson',
            '/(m)en$/i' => '\1an',
            '/(c)hildren$/i' => '\1\2hild',
            '/(n)ews$/i' => '\1\2ews',
            '/eaus$/' => 'eau',
            '/^(.*us)$/' => '\\1',
            '/s$/i' => ''
        ),
        'uninflected' => array(
            '.*[nrlm]ese', '.*deer', '.*fish', '.*measles', '.*ois', '.*pox', '.*sheep', '.*ss'
        ),
        'irregular' => array(
            'foes' => 'foe',
            'waves' => 'wave',
            'curves' => 'curve'
        )
    );

    /**
     * Words that should not be inflected
     *
     * @var array
     */
    private static $uninflected = array(
        'Amoyese', 'bison', 'Borghese', 'bream', 'breeches', 'britches', 'buffalo', 'cantus',
        'carp', 'chassis', 'clippers', 'cod', 'coitus', 'Congoese', 'contretemps', 'corps',
        'debris', 'diabetes', 'djinn', 'eland', 'elk', 'equipment', 'Faroese', 'flounder',
        'Foochowese', 'gallows', 'Genevese', 'Genoese', 'Gilbertese', 'graffiti',
        'headquarters', 'herpes', 'hijinks', 'Hottentotese', 'information', 'innings',
        'jackanapes', 'Kiplingese', 'Kongoese', 'Lucchese', 'mackerel', 'Maltese', '.*?media',
        'mews', 'moose', 'mumps', 'Nankingese', 'news', 'nexus', 'Niasese',
        'Pekingese', 'Piedmontese', 'pincers', 'Pistoiese', 'pliers', 'Portuguese',
        'proceedings', 'rabies', 'rice', 'rhinoceros', 'salmon', 'Sarawakese', 'scissors',
        'sea[- ]bass', 'series', 'Shavese', 'shears', 'siemens', 'species', 'swine', 'testes',
        'trousers', 'trout', 'tuna', 'Vermontese', 'Wenchowese', 'whiting', 'wildebeest',
        'Yengeese'
    );

    /**
     * Method cache array.
     *
     * @var array
     */
    private static $cache = [];

    /**
     * The initial state of Inflector so reset() works.
     *
     * @var array
     */
    private static $initialState = [];

    /**
     * Convert word in to the format for a table name. Converts 'ModelName' to 'model_name'
     *
     * @param  string $word       Word to tableize
     * @param  string $separator  Separator, default: "_"
     * @return string $word       Tableized word
     */
    public static function tableize($word, $separator = '_')
    {
        return strtolower(preg_replace('~(?<=\\w)([A-Z])~', $separator . '$1', $word));
    }

    /**
     * Convert word in to the human format.
     * @param  [type] $name [description]
     * @return [type]       [description]
     */
    public static function humanize($name)
    {
        if (empty($name)) {
            return '';
        }
        $word = static::tableize(static::classify($name), ' ');
        $word = strtoupper($word[0]) . substr($word, 1);
        return $word;
    }

    /**
     * Convert a word in to the format for a class name. Converts 'table_name' to 'TableName'
     *
     * @param string  $word  Word to classify
     * @return string $word  Classified word
     */
    public static function classify($word)
    {
        return str_replace(" ", "", ucwords(strtr($word, "_-", "  ")));
    }

    /**
     * Camelize a word. This uses the classify() method and turns the first character to lowercase
     *
     * @param string $word
     * @return string $word
     */
    public static function camelize($word)
    {
        return lcfirst(self::classify($word));
    }

    /**
     * Clears Inflectors inflected value caches. And resets the inflection
     * rules to the initial values.
     *
     * @return void
     */
    public static function reset()
    {
        self::$cache = [];
        // if (empty(self::$initialState)) {
        //     self::$initialState = get_class_vars(static::class);
        //     return;
        // }
        // foreach (self::$initialState as $key => $val) {
        //     if ($key != 'initialState') {
        //         self::${$key} = $val;
        //     }
        // }
    }

    /**
     * Adds custom inflection $rules, of either 'plural' or 'singular' $type.
     *
     * ### Usage:
     *
     * {{{
     * Inflector::rules('plural', array('/^(inflect)or$/i' => '\1ables'));
     * Inflector::rules('plural', array(
     *     'rules' => array('/^(inflect)ors$/i' => '\1ables'),
     *     'uninflected' => array('dontinflectme'),
     *     'irregular' => array('red' => 'redlings')
     * ));
     * }}}
     *
     * @param string $type The type of inflection, either 'plural' or 'singular'
     * @param array $rules Array of rules to be added.
     * @param boolean $reset If true, will unset default inflections for all
     *        new rules that are being defined in $rules.
     * @return void
     */
    // public static function rules($type, $rules, $reset = false)
    // {
    //     foreach ($rules as $rule => $pattern) {
    //         if (is_array($pattern)) {
    //             if ($reset) {
    //                 self::${$type}[$rule] = $pattern;
    //             } else {
    //                 if ($rule === 'uninflected') {
    //                     self::${$type}[$rule] = array_merge($pattern, self::${$type}[$rule]);
    //                 } else {
    //                     self::${$type}[$rule] = $pattern + self::${$type}[$rule];
    //                 }
    //             }
    //             unset($rules[$rule], self::${$type}['cache' . ucfirst($rule)]);
    //             if (isset(self::${$type}['merged'][$rule])) {
    //                 unset(self::${$type}['merged'][$rule]);
    //             }
    //             if ($type === 'plural') {
    //                 self::$cache['pluralize'] = self::$cache['tableize'] = [];
    //             } elseif ($type === 'singular') {
    //                 self::$cache['singularize'] = [];
    //             }
    //         }
    //     }
    //     self::${$type}['rules'] = $rules + self::${$type}['rules'];
    // }

    /**
     * Return $word in plural form.
     *
     * @param string $word Word in singular
     * @return string Word in plural
     */
    public static function pluralize($word)
    {
        if (isset(self::$cache['pluralize'][$word])) {
            return self::$cache['pluralize'][$word];
        }

        if (!isset(self::$plural['merged']['irregular'])) {
            self::$plural['merged']['irregular'] = self::$plural['irregular'];
        }

        if (!isset(self::$plural['merged']['uninflected'])) {
            self::$plural['merged']['uninflected'] = array_merge(self::$plural['uninflected'], self::$uninflected);
        }

        if (!isset(self::$plural['cacheUninflected']) || !isset(self::$plural['cacheIrregular'])) {
            self::$plural['cacheUninflected'] = '(?:' . implode('|', self::$plural['merged']['uninflected']) . ')';
            self::$plural['cacheIrregular'] = '(?:' . implode('|', array_keys(self::$plural['merged']['irregular'])) . ')';
        }

        if (preg_match('/(.*)\\b(' . self::$plural['cacheIrregular'] . ')$/i', $word, $regs)) {
            self::$cache['pluralize'][$word] = $regs[1] . substr($word, 0, 1) . substr(self::$plural['merged']['irregular'][strtolower($regs[2])], 1);
            return self::$cache['pluralize'][$word];
        }

        if (preg_match('/^(' . self::$plural['cacheUninflected'] . ')$/i', $word, $regs)) {
            self::$cache['pluralize'][$word] = $word;
            return $word;
        }

        foreach (self::$plural['rules'] as $rule => $replacement) {
            if (preg_match($rule, $word)) {
                self::$cache['pluralize'][$word] = preg_replace($rule, $replacement, $word);
                return self::$cache['pluralize'][$word];
            }
        }

        self::$cache['pluralize'][$word] = $word . 's';
        return self::$cache['pluralize'][$word];
    }

    /**
     * Return $word in singular form.
     *
     * @param string $word Word in plural
     * @return string Word in singular
     */
    public static function singularize($word)
    {
        if (isset(self::$cache['singularize'][$word])) {
            return self::$cache['singularize'][$word];
        }

        if (!isset(self::$singular['merged']['uninflected'])) {
            self::$singular['merged']['uninflected'] = array_merge(
                self::$singular['uninflected'],
                self::$uninflected
            );
        }

        if (!isset(self::$singular['merged']['irregular'])) {
            self::$singular['merged']['irregular'] = array_merge(
                self::$singular['irregular'],
                array_flip(self::$plural['irregular'])
            );
        }

        if (!isset(self::$singular['cacheUninflected']) || !isset(self::$singular['cacheIrregular'])) {
            self::$singular['cacheUninflected'] = '(?:' . join('|', self::$singular['merged']['uninflected']) . ')';
            self::$singular['cacheIrregular'] = '(?:' . join('|', array_keys(self::$singular['merged']['irregular'])) . ')';
        }

        if (preg_match('/(.*)\\b(' . self::$singular['cacheIrregular'] . ')$/i', $word, $regs)) {
            self::$cache['singularize'][$word] = $regs[1] . substr($word, 0, 1) . substr(self::$singular['merged']['irregular'][strtolower($regs[2])], 1);
            return self::$cache['singularize'][$word];
        }

        if (preg_match('/^(' . self::$singular['cacheUninflected'] . ')$/i', $word, $regs)) {
            self::$cache['singularize'][$word] = $word;
            return $word;
        }

        foreach (self::$singular['rules'] as $rule => $replacement) {
            if (preg_match($rule, $word)) {
                self::$cache['singularize'][$word] = preg_replace($rule, $replacement, $word);
                return self::$cache['singularize'][$word];
            }
        }
        self::$cache['singularize'][$word] = $word;
        return $word;
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: Bartosz Gołek
 * Date: 09.11.13
 * Time: 15:30
 *
 * @package    Conpago
 * @subpackage Helpers
 * @author     Bartosz Gołek <bartosz.golek@gmail.com>
 * @copyright  Copyright (c) 2015, Bartosz Gołek
 */

namespace Conpago\Helpers;

use Conpago\Core\RequestData;
use Conpago\Helpers\Contract\IRequest;
use Conpago\Helpers\Contract\IRequestParser;

class RequestParser implements IRequestParser
{
    private $contentType;

    /**
     * @var RequestData
     */
    protected $requestData;

    /**
     * @var IRequest
     */
    private $request;

    public function __construct(IRequest $request)
    {
        $this->request = $request;
    }

    /**
     * @return RequestData
     */
    public function parseRequestData()
    {
        if ($this->requestData == null) {
            $this->initializeContentType();

            $this->requestData = new RequestData(
                $this->getUrlElements(),
                $this->getRequestMethod(),
                $this->determineFormat(),
                $this->parseIncomingParams()
            );
        }

        return $this->requestData;
    }

    private function getRequestMethod()
    {
        return $this->request->getRequestMethod();
    }

    private function getUrlElements()
    {
        return $this->convertPathInfoToArray($this->request->getPathInfo());
    }

    /**
     * @param $pathInfo
     *
     * @return array
     */
    private function convertPathInfoToArray($pathInfo)
    {
        return $pathInfo != null ? explode('/', $pathInfo) : array();
    }

    private function parseIncomingParams()
    {
        $urlParameters = $this->parseQueryString();
        $bodyParameters = $this->parseBody();

        return $this->mergeUrlAndBodyParameters($urlParameters, $bodyParameters);
    }

    /**
     * @return array
     */
    private function parseQueryString()
    {
        $parameterTreeBuilder = new ParameterTreeBuilder();
        $queryString = $this->request->getQueryString();
        if ($queryString != null) {
            return $parameterTreeBuilder->getParams($queryString);
        }

        return array();
    }

    /**
     * @return array
     */
    private function parseBody()
    {
        return $this->extractParameters($this->request->getBody());
    }

    /**
     * @param $urlParameters
     * @param $bodyParameters
     *
     * @return array
     */
    private function mergeUrlAndBodyParameters($urlParameters, $bodyParameters)
    {
        return array_merge($urlParameters, $bodyParameters);
    }

    /**
     * @param $body
     *
     * @return mixed
     */
    private function extractParameters($body)
    {
        $parametersExtractor = $this->getExtractor($this->contentType, $body);
        return $parametersExtractor->getParameters();
    }

    public function getExtractor($contentType, $body)
    {
        switch ($contentType) {
            case "application/json":
                return new JsonParametersExtractor($body);
            case "application/x-www-form-urlencoded":
                return new FormParametersExtractor($body);
            case "":
                return new DummyParametersExtractor($body);
            default:
                throw new \BadMethodCallException();
        }
    }

    /**
     * @return void
     */
    private function initializeContentType()
    {
        $this->contentType = $this->request->getContentType();
    }

    private function determineFormat()
    {
        return $this->getRequestDataFormat();
    }

    private function getRequestDataFormat()
    {
        return $this->contentType == "application/json" ? "json" : "html";
    }
}


<?php

namespace Simply\Container\Entry;

use Psr\Container\ContainerInterface;

/**
 * A standard container entry that may be any value or a closure used to determine that value.
 *
 * @author Riikka Kalliomäki <riikka.kalliomaki@gmail.com>
 * @copyright Copyright (c) 2018 Riikka Kalliomäki
 * @license http://opensource.org/licenses/mit-license.php MIT License
 */
class MixedEntry implements EntryInterface
{
    /** @var mixed The value for the entry */
    private $value;

    /**
     * MixedType constructor.
     * @param mixed $value The value for the entry
     */
    public function __construct($value)
    {
        $this->value = $value;
    }

    /** {@inheritdoc} */
    public static function createFromCacheParameters(array $parameters): EntryInterface
    {
        return new static($parameters[0]);
    }

    /** {@inheritdoc} */
    public function getCacheParameters(): array
    {
        return [$this->value];
    }

    /** {@inheritdoc} */
    public function isFactory(): bool
    {
        return false;
    }

    /** {@inheritdoc} */
    public function getValue(ContainerInterface $container)
    {
        if ($this->value instanceof \Closure) {
            return ($this->value)($container);
        }

        return $this->value;
    }
}


<?php
namespace Core\Toolbox\IO;

use Psr\Log\LoggerInterface;
use Core\Toolbox\Strings\Normalize;

/**
 * File.php
 *
 * @author Michael "Tekkla" Zorn <tekkla@tekkla.de>
 * @copyright 2016
 * @license MIT
 */
class File extends AbstractFile
{
    use ReplaceDirectorySeperatorTrait;

    /**
     * Deletes a file or a complete directory tree
     *
     * @param boolean $clean_only
     *            Flag to delete only files while a directorystructure stays intact
     *
     * @return bool
     */
    public function delete($clean_only = false): bool
    {
        $path = $this->replaceDirectorySeperator($this->filename);

        if (!file_exists($path)) {
            return true;
        }

        if (!is_dir($path)) {
            return unlink($path);
        }

        $files = scandir($path);

        foreach ($files as $item) {

            $file = $path . DIRECTORY_SEPARATOR . $item;

            if (is_dir($file)) {
                $this->delete($file);
            }
            else {
                unlink($file);
            }
        }

        return $clean_only == false ? rmdir($path) : true;
    }

    /**
     * Moves the source to the destination.
     * Both parameter have to be a full paths.On success the return value will be the destination path.
     * Otherwise it will be boolean false.
     *
     * @param string $source
     *            Path to source file
     * @param string $destination
     *            Path to destination file
     *
     * @return string boolean
     */
    public function move($destination)
    {
        if (copy($this->filename, $destination)) {
            unlink($this->filename);

            $this->filename = $destination;

            return $destination;
        }
        else {
            return false;
        }
    }

    /**
     * Wrapper method for file_exists() plus logging feature
     *
     * @param string $filename
     *            Complete path to file
     * @param LoggerInterface $logger
     *            Optional logger component to track notices when file does not exist
     *
     * @return boolean
     */
    public function exists(LoggerInterface $logger = null): bool
    {
        $filename = $this->replaceDirectorySeperator($this->filename);
        $exists = file_exists($filename);

        if (!$exists && isset($logger)) {
            $logger->notice(sprintf('File "%s" not found.', $filename));
        }

        return $exists;
    }

    /**
     * Cleans up a filename string from all characters which can make trouble on filesystems.
     *
     * @param string $name
     *            The string to cleanup
     * @param string $delimiter
     *
     * @return string
     */
    public function clean($delimiter = '-')
    {
        // The fileextension should not be normalized.
        if (strrpos($this->filename, '.') !== false) {
            list ($name, $extension) = explode('.', $this->filename);
        }

        $normalize = new Normalize($name);

        $name = $normalize->normalize();
        $name = preg_replace('/[^[:alnum:]\-]+/', $delimiter, $name);
        $name = preg_replace('/' . $delimiter . '+/', $delimiter, $name);
        $name = rtrim($name, $delimiter);

        $cleaned = isset($extension) ? $name . '.' . $extension : $name;

        return $cleaned;
    }

    /**
     * Returns an array of files inside the given directory path.
     *
     * @param string $path
     *            Directory path to get filelist from
     *
     * @throws FileException
     *
     * @return void multitype:string
     */
    public function getFilenamesFromDir($path, $recursive = false)
    {
        // Add trailing slash if missing
        if (substr($path, -1) != '/') {
            $path .= '/';
        }

        $path = $this->replaceDirectorySeperator($path);

        $filenames = [];

        // No handle, error exception
        if (!file_exists($path)) {
            Throw new FileException(sprintf('Path "%s" not found.', $path, 2000));
        }

        $files = scandir($path);

        foreach ($files as $file) {

            // no '.' or '..'
            if ($file{0} == '.') {
                continue;
            }

            if (is_dir($path . $file) && $recursive) {
                $filenames[$file] = $this->getFilenamesFromDir($path . $file, $recursive);
            }
            else {
                continue;
            }

            // store filename
            $filenames[$file] = $file;
        }

        return $filenames;
    }
}


<?php
/**
 * This file is part of the bee4/events package.
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright Bee4 2014
 * @author Stephane HULARD <s.hulard@chstudio.fr>
 * @package Bee4\Events
 */

namespace Bee4\Events;

/**
 * Trait implementation of the DispatcherAwareInterface
 * @package Bee4\Event
 */
trait DispatcherAwareTrait
{
    /**
     * The linked dispatcher instance
     * @var DispatcherInterface
     */
    private $dispatcher;

    /**
     * Dependency injection
     * @param DispatcherInterface $dispatcher
     */
    public function setDispatcher(DispatcherInterface $dispatcher)
    {
        $this->dispatcher = $dispatcher;
    }

    /**
     * Access to the current dispatcher
     * @return DispatcherInterface|null
     */
    final public function getDispatcher()
    {
        return $this->dispatcher;
    }

    /**
     * Check if a dispatcher has been injected or not
     * @return boolean
     */
    final public function hasDispatcher()
    {
        return
            $this->dispatcher !== null &&
            $this->dispatcher instanceof DispatcherInterface;
    }

    /**
     * Dispatch an event if the dispatcher is loaded
     * @param string $name event name to dispatch
     * @param EventInterface $event
     * @return boolean
     */
    final public function dispatch($name, EventInterface $event)
    {
        if ($this->hasDispatcher()) {
            $this->getDispatcher()->dispatch($name, $event);
            return true;
        }
        return false;
    }
}


<?php
/*
 * This file is part of the Skeetr package.
 *
 * (c) Máximo Cuadros <mcuadros@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Skeetr\Client\Handler;

use Psr\Log\LoggerInterface;

/**
 * @author Máximo Cuadros <mcuadros@gmail.com>
 * @author Fabien Potencier <fabien@symfony.com>
 */
class Error
{
    const TYPE_DEPRECATION = -100;

    private $levels = array(
        E_WARNING           => 'Warning',
        E_NOTICE            => 'Notice',
        E_USER_ERROR        => 'User Error',
        E_USER_WARNING      => 'User Warning',
        E_USER_NOTICE       => 'User Notice',
        E_STRICT            => 'Runtime Notice',
        E_RECOVERABLE_ERROR => 'Catchable Fatal Error',
        E_DEPRECATED        => 'Deprecated',
        E_USER_DEPRECATED   => 'User Deprecated',
        E_ERROR             => 'Error',
        E_CORE_ERROR        => 'Core Error',
        E_COMPILE_ERROR     => 'Compile Error',
        E_PARSE             => 'Parse',
    );

    private $level;
    private $reservedMemory;
    private static $logger;

    /**
     * Register the error handler. The level at which the conversion to Exception is done
     * (null to use the error_reporting() value and 0 to disable)
     *
     * @param  integer $level
     * @return The     registered error handler
     */
    public static function register($level = null)
    {
        $handler = new static();
        $handler->setLevel($level);

        ini_set('display_errors', 0);
        set_exception_handler(array($handler, 'handleException'));
        set_error_handler(array($handler, 'handle'));
        register_shutdown_function(array($handler, 'handleFatal'));
        $handler->reservedMemory = str_repeat('x', 10240);

        return $handler;
    }

    /**
     * Return the logger instance
     *
     * @return LoggerInterface
     */
    public static function getLogger()
    {
        return self::$logger;
    }

    /**
     * Configure the logger used by the error handler
     *
     * @param LoggerInterface $logger
     */
    public static function setLogger(LoggerInterface $logger)
    {
        self::$logger = $logger;
    }

    /**
     * Returns the minimum error level
     *
     * @return integer
     */
    public function getLevel()
    {
        return $this->level;
    }

    /**
     * Configure the minimum error level
     *
     * @param integer $level
     */
    public function setLevel($level)
    {
        if ( $level === null ) $level = error_reporting();
        $this->level = $level;
    }

    /**
     * This method will be used by set_error_handler
     *
     * @throws \ErrorException When error_reporting returns error
     */
    public function handle($level, $message, $file, $line, $context)
    {
        if ( $this->level === 0 ) return true;

        if ( $level & (E_USER_DEPRECATED | E_DEPRECATED) ) {
            if (self::$logger !== null) {
                if ( version_compare(PHP_VERSION, '5.4', '<') ) {
                    $stack = array_slice(debug_backtrace(false), 0, 10);
                } else {
                    $stack = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 10);
                }

                self::$logger->warning($message, array(
                    'type' => self::TYPE_DEPRECATION,
                    'stack' => $stack
                ));
            }

            return true;
        }

        if ( error_reporting() & $level && $this->level & $level ) {
            $this->generateErrorException($level, $message, $file, $line, false);
        }

        return true;
    }

    /**
     * This method will be used by register_shutdown_function
     */
    public function handleFatal()
    {
        $error = $this->getLastError();
        if ($error === null) return;

        unset($this->reservedMemory);
        $type = $error['type'];
        if ( $this->level === 0 || !in_array($type, array(E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE))) {
            return;
        }

        // get current exception handler
        $exceptionHandler = set_exception_handler(function() {});
        restore_exception_handler();

        if (
            is_array($exceptionHandler) &&
            $exceptionHandler[0] instanceof Error
        ) {
            $this->generateErrorException($type, $error['message'], $error['file'], $error['line']);
        }
    }

    protected function getLastError()
    {
        return error_get_last();
    }

    /**
     * This handler will get all the Excpetion, out of a try/catch
     *
     * @param \Exception $exception
     */
    public function handleException(\Exception $exception)
    {
        self::printException($exception);
    }

    private function generateErrorException($type, $message, $file, $line, $fatal = true)
    {
        $level = isset($this->levels[$type]) ? $this->levels[$type] : $type;
        $text = sprintf('%s: %s in %s line %d', $level, $message, $file, $line);

        $exception = new \ErrorException($text, 0, $type, $file, $line);
        self::printException($exception, $fatal);

        return $exception;
    }

    /**
     * This handler will get all the Excpetion, out of a try/catch
     *
     * @param \Exception $exception
     */
    public static function printException(\Exception $exception, $fatal = true)
    {
        if ( !self::$logger ) return false;

        self::$logger->error($exception->getMessage(), get_object_vars($exception));
        if ( $fatal ) self::$logger->notice('Execution will stop due to the previous exception');
    }
}


<?php

namespace Zax\Application\UI;

use Nette;

trait TControlForward {

	/**
	 * Forward using $presenter->forward() (doesn't work well with redrawControl)
	 *
	 * @param string $destination
	 * @param array $args
	 */
	public function presenterForward($destination, $args = []) {

		// Get full path
		$name = $this->getUniqueId();
		if($destination !== 'this') {
			$destination = "$name-$destination";
		}

		// Prepend full path to param keys
		$params = [];
		foreach($args as $key => $val) {
			$params["$name-$key"] = $val;
		}

		$this->getPresenter()->forward($destination, $params);
	}

	/**
	 * This method gets called during forward().
	 * You can override it if you want to eg. send url and/or anchor in payload in AJAX requests.
	 *
	 * @param string $url
	 * @param string|NULL $anchor
	 */
	protected function processDestination($url, $anchor = NULL) {

	}

	/**
	 * Custom "hacky" forward (works well with redrawControl)
	 *
	 * @param string $destination
	 * @param array $args
	 */
	public function forward($destination, $args = []) {

		// Remove '!' from destination
		$destination = str_replace('!', '', $destination);

		// Remove anchor from destination
		$anchor = strpos($destination, '#');
		if(is_int($anchor)) {
			list($destination, $anchor) = explode('#', $destination);
		} else {
			$anchor = NULL;
		}
		$this->processDestination($this->link($destination, $args), $anchor);

		// Process arguments
		$params = [];
		foreach($args as $key => $param) {
			$control = $this;
			$property = $key;

			// Get subcomponent from name
			if(strpos($key, self::NAME_SEPARATOR) > 0) {
				$names = explode(self::NAME_SEPARATOR, $key);
				$property = array_pop($names);
				$control = $this->getComponent(implode(self::NAME_SEPARATOR, $names));
			}

			if($control->hasPersistentProperty($property)) {
				$control->$property = $param;
			} else {
				$params[$key] = $param;
			}
		}
		$this->params = $params;

		if($destination === 'this')
			return; // Definitely not a signal

		$this->signalReceived($destination);
	}

	/**
	 * Does this control have a persistent property $property?
	 *
	 * @param $property
	 * @return bool
	 */
	protected function hasPersistentProperty($property) {
		$ref = $this->getReflection();
		if($ref->hasProperty($property)) {
			$refp = $ref->getProperty($property);
			return $refp->isPublic() && $refp->hasAnnotation('persistent');
		}
		return FALSE;
	}

}


<?php

namespace Potherca\Katwizy\Factory;

use Potherca\Katwizy\ConfigLoader;
use Potherca\Katwizy\Directories;

class ConfigLoaderFactory
{
    /** @var string */
    private $environment;
    /** @var string */
    private $rootDirectory;

    /**
     * @param string $rootDirectory
     * @param string $environment
     *
     * @throws \RuntimeException
     */
    final public function __construct($rootDirectory, $environment)
    {
        $this->rootDirectory = (string) $rootDirectory;
        $this->environment = (string) $environment;
    }

    /**
     * @return ConfigLoader
     * @throws \RuntimeException
     */
    final public function create()
    {
        $rootDirectory = $this->rootDirectory;
        $environment = $this->environment;

        $varDir = $rootDirectory . '/var/' . $environment;
        $configDir = $rootDirectory . '/config';

        if (is_dir($configDir) === false) {
            $configDir = $rootDirectory;
        }

        $this->ensureDirectoryExists($varDir);

        $directories = new Directories(
            dir($configDir),
            dir($rootDirectory . '/vendor/symfony/framework-standard-edition/app/config'),
            dir($rootDirectory),
            dir($varDir)
        );

        return new ConfigLoader($directories, $environment);
    }

    /**
     * @param string $varDir
     *
     * @throws \RuntimeException
     */
    private  function ensureDirectoryExists($varDir)
    {
        if (is_dir($varDir) === false) {
            if (file_exists($varDir) === true) {
                throw new \RuntimeException(
                    sprintf(
                        'Could not create directory "%s", file already exists at given location.',
                        $varDir
                    )
                );
            } else {
                /* @NOTE: Error is suppressed with "@" so an exception can be thrown instead of triggering an error */
                /** @noinspection NotOptimalIfConditionsInspection *///No use in checking dir before creation
                if (@mkdir($varDir, 0777, true) === false && is_dir($varDir) === false) {
                    throw new \RuntimeException(sprintf('Could not create directory "%s"', $varDir));
                }
            }
        } elseif (is_writable($varDir) === false) {
            throw new \RuntimeException(sprintf('Could not write in directory "%s"', $varDir));
        }
    }

}

/*EOF*/


<?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.md
 * file that was distributed with this source code.
 */

namespace jarrus90\User\models;

use yii\base\Model;
use yii\rbac\Item;
use jarrus90\User\validators\RbacValidator;

/**
 * @author Dmitry Erofeev <dmeroff@gmail.com>
 */
abstract class AuthItem extends Model {

    /** @var string */
    public $name;

    /** @var string */
    public $description;

    /** @var string */
    public $rule;

    /** @var string[] */
    public $children = [];

    /** @var \yii\rbac\Role|\yii\rbac\Permission */
    public $item;

    /** @var \jarrus90\User\components\DbManager */
    protected $manager;

    /** @inheritdoc */
    public function init() {
        parent::init();
        $this->manager = \Yii::$app->authManager;
        if ($this->item instanceof Item) {
            $this->name = $this->item->name;
            $this->description = $this->item->description;
            $this->children = array_keys($this->manager->getChildren($this->item->name));
            if ($this->item->ruleName !== null) {
                $this->rule = get_class($this->manager->getRule($this->item->ruleName));
            }
        }
    }

    /** @inheritdoc */
    public function attributeLabels() {
        return [
            'name' => \Yii::t('rbac', 'Name'),
            'description' => \Yii::t('rbac', 'Description'),
            'children' => \Yii::t('rbac', 'Children'),
            'rule' => \Yii::t('rbac', 'Rule'),
        ];
    }

    /** @inheritdoc */
    public function scenarios() {
        return [
            'create' => ['name', 'description', 'children', 'rule'],
            'update' => ['name', 'description', 'children', 'rule'],
        ];
    }

    /** @inheritdoc */
    public function rules() {
        return [
            ['name', 'required'],
            ['name', 'match', 'pattern' => '/^[\w][\w-.:]+[\w]$/'],
            [['name', 'description', 'rule'], 'trim'],
            ['name', function () {
                    if ($this->manager->getItem($this->name) !== null) {
                        $this->addError('name', \Yii::t('rbac', 'Auth item with such name already exists'));
                    }
                }, 'when' => function () {
                    return $this->scenario == 'create' || $this->item->name != $this->name;
                }],
            ['children', RbacValidator::className()],
            ['rule', function () {
                    try {
                        $class = new \ReflectionClass($this->rule);
                    } catch (\Exception $ex) {
                        $this->addError('rule', \Yii::t('rbac', 'Class "{0}" does not exist', $this->rule));
                        return;
                    }

                    if ($class->isInstantiable() == false) {
                        $this->addError('rule', \Yii::t('rbac', 'Rule class can not be instantiated'));
                    }
                    if ($class->isSubclassOf('\yii\rbac\Rule') == false) {
                        $this->addError('rule', \Yii::t('rbac', 'Rule class must extend "yii\rbac\Rule"'));
                    }
                }],
        ];
    }

    /**
     * Saves item.
     *
     * @return bool
     */
    public function save() {
        if ($this->validate() == false) {
            return false;
        }

        if ($isNewItem = ($this->item === null)) {
            $this->item = $this->createItem($this->name);
        } else {
            $oldName = $this->item->name;
        }

        $this->item->name = $this->name;
        $this->item->description = $this->description;

        if (!empty($this->rule)) {
            $rule = \Yii::createObject($this->rule);
            if (null === $this->manager->getRule($rule->name)) {
                $this->manager->add($rule);
            }
            $this->item->ruleName = $rule->name;
        } else {
            $this->item->ruleName = null;
        }

        if ($isNewItem) {
            \Yii::$app->session->setFlash('success', \Yii::t('rbac', 'Item has been created'));
            $this->manager->add($this->item);
        } else {
            \Yii::$app->session->setFlash('success', \Yii::t('rbac', 'Item has been updated'));
            $this->manager->update($oldName, $this->item);
        }

        $this->updateChildren();

        return true;
    }

    /**
     * Updated items children.
     */
    protected function updateChildren() {
        $children = $this->manager->getChildren($this->item->name);
        $childrenNames = array_keys($children);

        if (is_array($this->children)) {
            // remove children that
            foreach (array_diff($childrenNames, $this->children) as $item) {
                $this->manager->removeChild($this->item, $children[$item]);
            }
            // add new children
            foreach (array_diff($this->children, $childrenNames) as $item) {
                $this->manager->addChild($this->item, $this->manager->getItem($item));
            }
        } else {
            $this->manager->removeChildren($this->item);
        }
    }

    /**
     * @return array An array of unassigned items.
     */
    abstract public function getUnassignedItems();

    /**
     * @param  string         $name
     * @return \yii\rbac\Item
     */
    abstract protected function createItem($name);
}


<?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\Loader;

use \CarteBlanche\CarteBlanche;
use \CarteBlanche\Interfaces\DependencyLoaderInterface;

/**
 * @author  Piero Wbmstr <me@e-piwi.fr>
 */
class RouterLoader
    implements DependencyLoaderInterface
{

    /**
     * Instance loader
     *
     * @param   array                       $config
     * @param   \CarteBlanche\App\Container $container
     * @return  \CarteBlanche\App\Router
     */
    public function load(array $config = null, \CarteBlanche\App\Container $container)
    {
//        $route = null, array $routes_table = array(), array $arguments_table = array(), array $matchers_table = array()
        return new \CarteBlanche\App\Router(
            null,
            $container->get('config')->get('routing.routes', \CarteBlanche\App\Config::NOT_FOUND_GRACEFULLY, array()),
            $container->get('config')->get('routing.arguments_mapping', \CarteBlanche\App\Config::NOT_FOUND_GRACEFULLY, array()),
            $container->get('config')->get('routing.masks', \CarteBlanche\App\Config::NOT_FOUND_GRACEFULLY, array())
        );
    }

}

// Endfile


<?php

namespace writecrow\TagConverter;

/**
 * Class TagConverter.
 *
 * A helper class to convert Tagged corpus text to universal formats.
 *
 * @author markfullmer <mfullmer@gmail.com>
 *
 * @link https://github.com/writecrow/tag-converter/
 *
 * @license http://www.opensource.org/licenses/mit-license.php MIT
 */
class TagConverter {

  /**
   * Convert to JSON.
   *
   * @param string $original
   *   The text, in tagged corpus format.
   *
   * @return string
   *   A JSON object as a string.
   */
  public static function json($original) {
    return str_replace('\\ufeff', '', json_encode(self::convert($original)));
  }

  /**
   * Return PHP array.
   *
   * @param string $original
   *   The text, in tagged corpus format.
   *
   * @return string[]
   *   A PHP array.
   */
  public static function php($original) {
    return self::convert($original);
  }

  /**
   * Return XML object.
   *
   * @param string $original
   *   The text, in tagged corpus format.
   *
   * @return object
   *   An XML object.
   */
  public static function xml($original) {
    $array = self::convert($original);
    $xml_data = new \SimpleXMLElement('<?xml version="1.0"?><data></data>');
    self::arrayToXml($array, $xml_data);
    return $xml_data->asXML();
  }

  /**
   * Additional logic to convert to XML syntax.
   */
  public static function arrayToXml($data, &$xml_data) {
    foreach ($data as $key => $value) {
      if (is_numeric($key)) {
        $key = 'item' . $key;
      }
      if (is_array($value)) {
        $subnode = $xml_data->addChild($key);
        self::arrayToXml($value, $subnode);
      }
      else {
        $xml_data->addChild("$key", htmlspecialchars("$value"));
      }
    }
  }

  /**
   * Convert tag format into PHP array.
   *
   * @param string $original
   *   The text, in tagged corpus format.
   */
  protected static function convert($original = '') {
    $array = [];
    // Only search for tags within header section, if demarcated.
    $header_split = preg_split('/<End Header>/', $original);
    preg_match_all("/<([a-zA-Z0-9_ -]*):([a-zA-Z0-9_&;, -]*)>/", $header_split[0], $matches, PREG_SET_ORDER);
    if (isset($matches[0])) {
      // Store <TAGNAME: VALUE> strings.
      foreach ($matches as $key => $values) {
        $values[2] = trim($values[2]);
        $multiple_terms = preg_grep('/;/', explode("\n", $values[2]));
        if (!empty($multiple_terms)) {
          $terms = preg_split('/;/', $values[2]);
          foreach ($terms as $i => &$term) {
            if (empty($term)) {
              unset($terms[$i]);
            }
            $term = (string) trim($term);
          }
        }
        else {
          $terms = (string) trim($values[2]);
        }
        $array[trim($values[1])] = $terms;
      }
    }

    // Remove tags and parse each line into an array element.
    if (isset($header_split[1])) {
      $untagged = $header_split[1];
    }
    else {
      $untagged = preg_replace("/<([a-zA-Z0-9_ -]*):([a-zA-Z0-9_&;, -]*)>/", "", $original);
      $untagged = str_replace('<End Header>', '', $untagged);
    }
    $clean = '';
    $lines = preg_split('/((\r?\n)|(\n?\r))/', htmlspecialchars($untagged, ENT_NOQUOTES));
    $end = end($lines);
    foreach ($lines as $key => $line) {
      if ($line != '') {
        $clean .= $line;
        if ($key != $end) {
          $clean .= PHP_EOL;
        }
      }
    }
    // Add a new array element, 'text', to the array. If nothing else, the
    // $array array will now contain the 'text' element with an empty string.
    $array['text'] = $clean;
    return $array;
  }

}


<?php namespace Ordercloud\Entities\Organisations;

use JsonSerializable;

class OrganisationBillingProfile implements JsonSerializable
{

    /** @var integer */
    private $businessName;
    /** @var UserShort */
    private $vatNumber;
    /** @var string */
    private $contactName;
    /** @var string */
    private $phoneNumber;
    /** @var string */
    private $email;
    /** @var String */
    private $address;

    public function __construct($businessName, $vatNumber, $contactName, $phoneNumber, $email, $address)
    {
        $this->businessName = $businessName;
        $this->vatNumber = $vatNumber;
        $this->contactName = $contactName;
        $this->phoneNumber = $phoneNumber;
        $this->email = $email;
        $this->address = $address;
    }

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

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

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

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

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

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

    /**
     * Specify data which should be serialized to JSON
     */
    public function jsonSerialize()
    {
        return [
            'businessName' => $this->getBusinessName(),
            'vatNumber' => $this->getVatNumber(),
            'contactName' => $this->getContactName(),
            'phoneNumber' => $this->getPhoneNumber(),
            'email' => $this->getEmail(),
            'address' => $this->getAddress(),
        ];
    }
}


<?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\App;

use \CarteBlanche\App\Kernel;
use \CarteBlanche\Interfaces\ConfigInterface;
use \Patterns\Commons\Registry;
use \Library\Helper\Code as CodeHelper;
use \CarteBlanche\Exception\ErrorException;
use \CarteBlanche\Exception\InvalidArgumentException;

/**
 * This is the configuration manager of CarteBlanche
 *
 * @author  Piero Wbmstr <me@e-piwi.fr>
 */
class Config
    implements ConfigInterface
{

    /**
     * Constant to use to not throw error if a configuration is not found
     */
    const NOT_FOUND_GRACEFULLY = 1;

    /**
     * Constant to use to throw an error if a configuration is not found
     */
    const NOT_FOUND_ERROR = 2;

    /**
     * @var \Patterns\Commons\Registry The singleton instance of the registry (MAIN REGISTRY OBJECT)
     */
    protected $registry;

    /**
     * @var array
     */
    protected $files_loaded;

    /**
     * @var int The current global configuration stack ID
     */
    private static $global_config_id = null;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->setRegistry(new Registry);
        self::$global_config_id = time();
        $this->getRegistry()->saveStack(self::$global_config_id);
    }

    /**
     * Load and parse a configuration file
     *
     * @param   string      $filename
     * @param   bool        $merge_globals
     * @param   null|string $stack_name
     * @param   null|string $handler    A classname to parse concerned config content
     * @return  self
     * @throws  \CarteBlanche\Exception\ErrorException if the file is not found
     */
    public function load($filename, $merge_globals = true, $stack_name = null, $handler = null)
    {
        $file = new \SplFileInfo($filename);
        if ($file->isFile()) {
            if (empty($handler)) {
                $handler = $file->getExtension();
            }
            $factory = \Library\Factory::create()
                ->factoryName(__CLASS__)
                ->mustImplement(Kernel::CONFIG_FILETYPE_INTERFACE)
                ->defaultNamespace(Kernel::CONFIG_FILETYPE_DEFAULT_NAMESPACE)
                ->classNameMask(array('%s', '%s'.Kernel::CONFIG_FILETYPE_SUFFIX))
                ;
            $config = $factory->build($handler);
            $values = $config->parse($file);
            if (!empty($values)) {
                $this->set($values, $merge_globals, $stack_name);
                $this->_registerConfigFile($filename, count($values));
            } else {
                $this->_registerConfigFile($filename, 'empty content');
            }
        } else {
            throw new ErrorException(
                sprintf('Configuration file "%s" not found!', $filename)
            );
        }
        return $this;
    }

    /**
     * Parse and set a configuration array
     *
     * @param   array       $config
     * @param   bool        $merge_globals
     * @param   null/string $stack_name
     * @return  self/array  Returns the parsed array if `$merge_globals` is false, the config object otherwise
     */
    public function set(array $config, $merge_globals = true, $stack_name = null)
    {
        if (!empty($config)) {
            $config = $this->_buildConfigStack($config);
            if (!empty($stack_name)) {
                $this->getRegistry()->loadStack($stack_name);
            }
            foreach ($config as $index=>$val) {
                $this->getRegistry()->setEntry($index, $val);
            }
            if (!empty($stack_name)) {
                $this->getRegistry()->saveStack($stack_name);
            }
        }

        if (!$merge_globals) {
            return $config;
        } else {
            $this->getRegistry()->loadStack(self::$global_config_id);
            $globals = array_replace_recursive(
                $this->getRegistry()->dump(), $config
            );
            foreach ($globals as $index=>$val) {
                $this->getRegistry()->setEntry($index, $val);
            }
            $this->getRegistry()->saveStack(self::$global_config_id);
            return $this;
        }
    }

    /**
     * Get a configuration stack or entry
     *
     * @param   string      $index
     * @param   int         $flag
     * @param   null/mixed   $default
     * @param   string      $stack_name
     * @return  mixed
     * @throws  \CarteBlanche\Exception\InvalidArgumentException if the index doesn't exist and `$flag` is NOT_FOUND_ERROR
     */
    public function get($index, $flag = self::NOT_FOUND_GRACEFULLY, $default = null, $stack_name = 'global')
    {
        $value = null;
        if ($stack_name==='global') {
            $config = $this->getRegistry()->dumpStack(self::$global_config_id);
        } else {
            if ($this->getRegistry()->isStack($stack_name)) {
                $config = $this->getRegistry()->dumpStack($stack_name);
            } else {
                if ($flag & self::NOT_FOUND_ERROR) {
                    throw new InvalidArgumentException(
                        sprintf('Unknown configuration stack "%s"!', $stack_name)
                    );
                } else {
                    return $default;
                }
            }
        }

        if (strpos($index, self::$depth_separator_char)!==false) {
            $depth_index = explode(self::$depth_separator_char, $index);
            $tmp_conf =& $config;
            foreach ($depth_index as $count=>$_i) {
                if (array_key_exists($_i, $tmp_conf)) {
                    $tmp_conf =& $tmp_conf[$_i];
                } else {
                    if ($count===0) {
                        $stack_name = array_shift($depth_index);
                        return $this->get(
                            implode(self::$depth_separator_char, $depth_index),
                            $flag, $default, $stack_name
                        );
                    }
                    $tmp_conf = array();
                }
            }
            if (!empty($tmp_conf)) {
                $value = $this->_parseConfig($tmp_conf, $stack_name);
            }
        } else {
            if (array_key_exists($index, $config)) {
                $value = $this->_parseConfig($config[$index], $stack_name);
            }
        }

        if (!$value) {
            if ($flag & self::NOT_FOUND_GRACEFULLY) {
                return $default;
            } else {
                throw new InvalidArgumentException(
                    sprintf('Unknown configuration entry "%s"!', $index)
                );
            }
        } else {
            return $value;
        }
    }

    /**
     * Get the full configuration array
     *
     * @return array
     */
    public function dump()
    {
        return $this->getRegistry()->dumpStack(self::$global_config_id);
    }

// ---------------------------------
// Registry Getter/Setter
// ---------------------------------

    /**
     * Set the configuration object registry
     *
     * @param   \Patterns\Commons\Registry $registry
     * @return  self
     */
    public function setRegistry(Registry $registry)
    {
        $this->registry = $registry;
        return $this;
    }

    /**
     * Get the configuration object registry
     *
     * @return  \Patterns\Commons\Registry
     */
    public function getRegistry()
    {
        return $this->registry;
    }

    /**
     * Add a configuration file in the files registry
     *
     * @param   string  $file_name
     * @param   int     $length
     * @return  self
     */
    protected function _registerConfigFile($file_name, $length)
    {
        $this->files_loaded[$file_name] = $length;
        return $this;
    }

    /**
     * Get the configuration files loaded
     *
     * @return array
     */
    public function getRegisteredConfigFiles()
    {
        return $this->files_loaded;
    }

// ---------------------------------
// Process
// ---------------------------------

    /**
     * @var string  Indexes depth separator
     */
    public static $depth_separator_char = '.';

    /**
     * @var array   Characters list to replace in a configuration index (dot is not included as it is the separator)
     */
    public static $slugify_stripped_chars = array(
        ' ', '-', '/', '\\', ',', '?', ';', ':', '=', '+', '%', '§', '<', '>', '|',
        '`', '$', '^', '¨', '*', '€', '£', ')', '!', '(', "'", '"', '&', '#', '@'
    );

    /**
     * @var string  Replacement character in a configuration index
     */
    public static $slugify_replacement_char = '_';

    /**
     * Rebuild a configuration array
     *
     * This will slugify all indexes and dispatch values following the dotted indexes.
     *
     * @param   array   $config_array
     * @return  array
     */
    protected function _buildConfigStack(array $config_array)
    {
        $config = array();
        foreach ($config_array as $index=>$val) {
            $index = $this->_slugify($index);
            $val = $this->_treatValue($val);

            if (strpos($index, self::$depth_separator_char)!==false) {
                $depth_index = explode(self::$depth_separator_char, $index);
                $tmp_conf =& $config;
                foreach ($depth_index as $count=>$_i) {
                    if (!array_key_exists($_i, $tmp_conf)) {
                        $tmp_conf[$_i] = array();
                    }
                    $tmp_conf =& $tmp_conf[$_i];
                    if ($count===count($depth_index)-1) {
                        $tmp_conf = $val;
                    }
                }
                unset($config[$index]);
            } else {
                if (is_array($val)) {
                    foreach ($val as $val_index=>$val_val) {
                        if (strpos($val_index, self::$depth_separator_char)!==false) {
                            $val = $this->_buildConfigStack($val);
                        }
                    }
                }
                $config[$index] = $val;
            }
        }
        return $config;
    }

    /**
     * Rebuild an index as a slug: lower case with no punctuation
     *
     * @param   string  $index
     * @return  string
     */
    protected function _slugify($index)
    {
        $index = utf8_encode(strtolower($index));
        $index = str_replace(self::$slugify_stripped_chars, self::$slugify_replacement_char, $index);
        $doubled = self::$slugify_replacement_char.self::$slugify_replacement_char;
        do {
            $index = str_replace($doubled, self::$slugify_replacement_char, $index);
        } while (strpos($index, $doubled)!==false);
        return $index;
    }

    /**
     * Process special treatment on configuration values such as BIT values
     *
     * @param mixed $value
     * @return mixed
     */
    protected function _treatValue($value)
    {
        if (is_array($value)) {
            $values = array();
            foreach ($value as $j=>$v) {
                $values[$j] = $this->_treatValue($v);
            }
        }
        if (is_string($value) && (
            in_array(strtolower(trim($value)), array('on', 'off')) ||
            in_array(strtolower(trim($value)), array('true', 'false')) ||
            in_array(trim($value), array('0', '1')) ||
            is_bool($value)
        )) {
            if (in_array(strtolower(trim($value)), array('on', 'true'))) {
                $value = true;
            } elseif (in_array(strtolower(trim($value)), array('off', 'false'))) {
                $value = false;
            }
            return (Boolean) $value;
        }
        return $value;
    }

    /**
     * Parse a configuration stack or entry
     *
     * This function will complete a configuration entry replacing references to other entries written like :
     *    'name' => '%entry%'
     * where "entry" is the name of another defined configuration entry.
     *
     * @param   mixed   $conf
     * @param   string  $stack_name
     * @return  mixed
     */
    protected function _parseConfig($conf, $stack_name = 'global')
    {
        if (is_string($conf)) {
            $this->_parseConfigRecursive($conf, null, $stack_name);
        } elseif (is_array($conf)) {
            array_walk_recursive($conf, array($this, '_parseConfigRecursive'), $stack_name);
            $conf = array_filter($conf);
        }
        return $conf;
    }

    /**
     * Parse a configuration stack array recursively
     *
     * @param   mixed       $value
     * @param   null/string $key
     * @param   string      $stack_name
     * @return  void        As the value is set by reference, nothing is returned but the original array is modified
     */
    protected function _parseConfigRecursive(&$value, $key = null, $stack_name = 'global')
    {
        if (!is_string($value)) return;

        // escape any '\%'
        $hash = 'XH'.uniqid();
        $value = str_replace('\%', $hash, $value);

        // configuration value notation : %name%
        while (is_string($value) && 0!=preg_match('/^(.*)\%(.*)\%(.*)$/i', $value, $matches) && count($matches)>1) {
            $_cf = $matches[2];
            if ($_cfg_val = $this->get($_cf, self::NOT_FOUND_GRACEFULLY, null, $stack_name)) {
                if (is_array($_cfg_val)) {
                    $value = $_cfg_val;
                } else {
                    $value = $matches[1].$_cfg_val.$matches[3];
                }
            }
            $matches = array();
        }

        // un-escape any '\%'
        if (is_string($value)) {
            $value = str_replace($hash, '%', $value);
        }

        // configuration stack notation : {name}
        if (is_string($value) && 0!=preg_match('/^\{(.*)\}$/i', $value, $matches)) {
            $_cf = $matches[1];
            if (substr(trim($_cf), 0, strlen('function'))!=='function') {
                $_cf = 'function(){ '.$_cf.'; }';
            }
            @eval("\$_cfg_closure = $_cf;");
            if ($_cfg_closure && is_callable($_cfg_closure)) {
                $value = call_user_func($_cfg_closure);
            }
        }
    }

}

// Endfile


<?php

namespace jamesvweston\Utilities;

class OAuthUtil
{

    /**
     * Example value in $headers:   ['Authorization' => 'Bearer TOKEN_GOES_HERE'];
     * @param   array       $headers
     * @param   string      $key
     * @param   string      $tokenType
     * @param   string      $separator
     * @return  string|null
     */
    public static function getAccessToken($headers, $key = 'Authorization', $tokenType = 'Bearer', $separator = ' ')
    {
        $value              = ArrayUtil::get($headers[strtolower($key)]);

        if (is_null($value))
            return null;

        if (!is_array($value))
            return null;

        if (sizeof($value) != 1)
            return null;

        $tokenString        = $value[0];

        $tokenArray         = explode($tokenType . $separator, $tokenString);

        if (sizeof($tokenArray) != 2)
            return null;

        return $tokenArray[1];
    }

}


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

namespace curlient\crawler;

use curlient\Curlient;
use curlient\filter\ConcatFilter;
use curlient\filter\JsonFilter;
use curlient\filter\QueryFilter;
use curlient\StringFilter;
use Symfony\Component\DomCrawler\Crawler;

class ListCrawler {
	private $ip;

	/**
	 * ListPageCrawler constructor.
	 *
	 * @param string $ip
	 */
	public function __construct($ip = '') {
		$this->ip = $ip;
	}

	/**
	 * 抓取一个列表页.
	 *
	 * @param array    $config
	 * @param \Closure $filter
	 *
	 * @return array
	 */
	public function crawl($config, $filter = null) {
		$pages = [];
		$gcfg  = $config['conf'];
		$cfg   = $config['list'];
		$url   = $config['url'];

		//$cfg['pages']为URL提取规则
		if ($url && $cfg['pages']) {//可以抓取
			$gcfg['ip'] = $this->ip;
			$client     = Curlient::build($gcfg);

			if (isset($cfg['method']) && $cfg['method'] == 'post') {
				$client->request($url, 'post', isset($cfg['data']) ? $cfg['data'] : null);
			} else {
				$client->request($url);
			}

			if (isset($cfg['ajax'])) {
				$client->ajax();
			}

			if (isset($cfg['encoding'])) {
				$encoding = $cfg['encoding'];
			} else if (isset($gcfg['encoding'])) {
				$encoding = $gcfg['encoding'];
			}

			$isJson = false;
			if (isset($cfg['json']) && $cfg['json']) {
				$content = $client->json(isset($encoding) ? $encoding : null);
				$isJson  = true;
			} else {
				$content = $client->text(isset($encoding) ? $encoding : null);
			}
			$cookies = $client->getCookies();
			if ($cookies) {
				$gcfg['cookie'] = isset($gcfg['cookie']) && is_array($gcfg['cookie']) ? @array_merge($gcfg['cookie'], $cookies) : $cookies;
			}
			if ($content) {//解析内容
				if ($isJson) {
					$this->parseJsonData($content, $cfg, $pages, $gcfg, $url);
				} else if (isset($cfg['dom'])) {
					$content = new Crawler($content);
					$this->parseDomData($content, $cfg, $pages, $gcfg, $url);
				} else {
					$this->parseTextData($content, $cfg, $pages, $gcfg, $url);
				}
			}
		}
		$pages = $this->unique($pages);
		if ($cfg['includes']) {
			$pages = $this->includes($pages, $cfg['includes']);
		}
		if ($cfg['excludes']) {
			$pages = $this->excludes($pages, $cfg['excludes']);
		}

		if ($pages) {
			Curlient::goodURL($url, $pages);//完整URL
		}

		if ($pages && $filter) {
			$pages = call_user_func_array($filter, [$pages]);
		}

		return $pages;
	}

	private function parseTextData($data, $cfg, &$pages, $gcfg, $url) {
		static $grabber = false;
		if ($grabber === false) {
			$grabber = StringFilter::getInstance();
		}
		if (isset($cfg['wrapper'])) {
			@list($start, $end) = $cfg['wrapper'];
			$data = StringFilter::sub($data, $start, $end);
		}
		if ($data) {
			$filterCfg = $cfg['pages'];
			if (!$filterCfg) {
				return;
			}
			$filterCfg[] = true;//匹配全部
			$filter      = new ConcatFilter();
			$links       = $filter->filter($data, $filterCfg);
			$limit       = isset($cfg['limit']) ? intval($cfg['limit']) : 100;
			$limit       = $limit <= 0 ? 100 : $limit;
			$spos        = isset($cfg['start']) ? $cfg['start'] : 0;
			$i           = 0;
			if ($links) {
				if ($cfg['fields']) {
					$preLink = '';//前一个匹配链接全字符，用于定位后一个链接.
					foreach ($links as $link) {
						$i++;
						if ($i > $limit || $i < $spos) {
							break;
						}
						$page = ['url' => $link[0], 'fields' => ['URL' => $link[0]], 'conf' => $gcfg, 'refer' => $url];
						foreach ($cfg['fields'] as $name => $fieldCfg) {
							$name = explode('.', $name);
							$pos  = isset($name[1]) ? $name[1] : 'before';
							$name = $name[0];
							if ($pos == 'after') {
								$fdata = StringFilter::sub($data, $link[1]);
							} else {
								$fdata = StringFilter::sub($data, $preLink, $link[1]);
							}
							$page['fields'][ $name ] = $grabber->filter($fdata, $fieldCfg);
							unset($fdata);
						}
						$preLink = $link[1];
						$pages[] = $page;
					}
				} else {
					foreach ($links as $link) {//每一个页面
						$i++;
						if ($i > $limit || $i < $spos) {
							break;
						}
						$page    = [
							'url'    => $link[0],
							'fields' => ['URL' => $link[0]],
							'conf'   => $gcfg,
							'refer'  => $url
						];
						$pages[] = $page;
					}
				}
			}
		}
	}

	private function parseJsonData($data, $cfg, &$pages, $gcfg, $url) {
		static $grabber = false;
		if ($grabber === false) {
			$grabber = StringFilter::getInstance();
		}
		$limit     = isset($cfg['limit']) ? intval($cfg['limit']) : 100;
		$limit     = $limit <= 0 ? 100 : $limit;
		$spos      = isset($cfg['start']) ? $cfg['start'] : 0;
		$links     = [];
		$i         = 0;
		$filterCfg = $cfg['pages'];
		if ($filterCfg) {
			$filter = new JsonFilter();
			do {
				if ($i < $spos) {
					$i++;
					continue;
				}
				$filterCfg[1] = ['{$i}', $i];
				$link         = $filter->filter($data, $filterCfg);
				if (!$link) {
					break;
				}
				$links[ $i ] = $link;
				$i++;
			} while ($i < $limit);
		}
		if ($links) {
			if ($cfg['fields']) {
				foreach ($links as $i => $link) {
					$page = ['url' => $link, 'fields' => ['URL' => $link], 'conf' => $gcfg, 'refer' => $url];
					foreach ($cfg['fields'] as $name => $fieldCfg) {
						if ($fieldCfg[0][0] != 'json') {
							$page['fields'][ $name ] = '';
						} else {
							$li                      = count($fieldCfg[0]);
							$fieldCfg[0][ $li ]      = ['{$i}', $i];
							$page['fields'][ $name ] = $grabber->filter($data, $fieldCfg);
						}
					}
					$pages[] = $page;
				}
			} else {
				foreach ($links as $link) {
					$page    = ['url' => $link, 'fields' => ['URL' => $link], 'conf' => $gcfg, 'refer' => $url];
					$pages[] = $page;
				}
			}
		}
	}

	private function parseDomData($data, $cfg, &$pages, $gcfg, $url) {
		static $grabber = false;
		if ($grabber === false) {
			$grabber = StringFilter::getInstance();
		}
		$limit     = isset($cfg['limit']) ? intval($cfg['limit']) : 100;
		$limit     = $limit <= 0 ? 100 : $limit;
		$spos      = isset($cfg['start']) ? $cfg['start'] : 0;
		$links     = [];
		$i         = 0;
		$filterCfg = $cfg['pages'];
		if ($filterCfg) {
			$filter = new QueryFilter();
			$li     = count($filterCfg);
			do {
				if ($i < $spos) {
					$i++;
					continue;
				}
				$filterCfg[ $li ] = ['{$i}', $i + 1];
				$link             = $filter->filter($data, $filterCfg);
				if (!$link) {
					break;
				}
				$links[ $i ] = $link;
				$i++;
			} while ($i < $limit);
		}
		if ($links) {
			if ($cfg['fields']) {
				foreach ($links as $i => $link) {
					$page = ['url' => $link, 'fields' => ['URL' => $link], 'conf' => $gcfg, 'refer' => $url];
					//处理每一个字段
					foreach ($cfg['fields'] as $name => $fieldCfg) {
						if ($fieldCfg[0][0] != 'query') {
							$page['fields'][ $name ] = '';
						} else {
							$li                      = count($fieldCfg[0]);
							$fieldCfg[0][ $li ]      = ['{$i}', $i];
							$page['fields'][ $name ] = $grabber->filter($data, $fieldCfg);
						}
					}
					$pages[] = $page;
				}
			} else {
				foreach ($links as $link) {
					$page    = ['url' => $link, 'fields' => ['URL' => $link], 'conf' => $gcfg, 'refer' => $url];
					$pages[] = $page;
				}
			}
		}
	}

	//去重
	private function unique($pages) {
		$links = [];
		$pages = array_filter($pages, function ($page) use (&$links) {
			if (isset($links[ $page['url'] ])) {
				return false;
			}
			$links[ $page['url'] ] = 1;

			return true;
		});
		unset($links);

		return $pages;
	}

	//包含
	private function includes($pages, $includes) {
		if (!is_array($includes) || empty($includes)) {
			return $pages;
		}

		return array_filter($pages, function ($page) use ($includes) {
			foreach ($includes as $in) {
				if (strpos($page['url'], $in) !== false) {//只要有，就要它
					return true;
				}
			}

			return false;//默认不要
		});
	}

	//不包
	private function excludes($pages, $excludes) {
		if (!is_array($excludes) || empty($excludes)) {
			return $pages;
		}

		return array_filter($pages, function ($page) use ($excludes) {

			foreach ($excludes as $ex) {
				if (strpos($page['url'], $ex) !== false) {//只要有，就不要它
					return false;
				}
			}

			return true;//默认要
		});
	}

	/**
	 * 验证采集规则.
	 *
	 * @param array $conf
	 *
	 * @return bool|string 验证成功返回true，否则返回错误信息.
	 */
	public static function validate($conf) {
		if (!isset($conf['url']) || empty($conf['url'])) {
			return _tr('url is missed@crawler');
		}

		if (!isset($conf['list']) || empty($conf['list'])) {
			return _tr('list is missed@crawler');
		}

		if (!isset($conf['list']['pages']) && !isset($conf['list']['pages1'])) {
			return _tr('page is missed@crawler');
		}

		if (!isset($conf['conf']) || !is_array($conf['conf'])) {
			return _tr('conf is missed or conf is not array@crawler');
		}

		return true;
	}

	/**
	 * 解析列表页规则.
	 *
	 * @param $config
	 *
	 * @return array
	 */
	public static function parseListPageURL($config) {
		$lists = [];
		// 一个元素即为一个url.
		if (isset($config['entries']) && $config['entries']) {
			$es = $config['entries'];
			if (is_array($es)) {
				$lists += $es;
			} else {
				$ess   = explode("\n", trim($es));
				$lists += $ess;
			}
		}

		if (isset($config['expression'])) {
			$expression = $config['expression'];
			//正则
			if (preg_match('#\{\{\s*0\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(0|[1-9]\d*)\s*\}\}#', $expression, $tags)) {
				@list($all, $start, $end, $step, $pad) = $tags;
				$pad  = intval($pad);
				$step = intval($step);
				$step = $step === 0 ? 1 : $step;
				$nums = @range(intval($start), intval($end), $step);
				foreach ($nums as $num) {
					if ($pad > 1) {
						$num = str_pad($num, $pad, '0', STR_PAD_LEFT);
					}
					$lists[] = str_replace($all, $num, $expression);
				}
			}
		}

		return array_unique($lists);
	}
}