<?php

namespace Dwo\FlaggingBundle\Config;

use Dwo\Flagging\Exception\FlaggingException;
use Dwo\Flagging\Model\VoterManagerInterface;
use Dwo\Flagging\Voter\VoterInterface;

/**
 * @author Dave Www <davewwwo@gmail.com>
 */
class VoterManager implements VoterManagerInterface
{
    /**
     * @var VoterInterface[]
     */
    protected $voters;

    /**
     * @param array $voters
     */
    public function __construct(array $voters = array())
    {
        $this->voters = $voters;
    }

    /**
     * @param string $name
     *
     * @throws FlaggingException
     *
     * @return VoterInterface
     */
    public function getVoter($name)
    {
        if (!isset($this->voters[$name])) {
            throw new FlaggingException(sprintf('voter "%s" not found', $name));
        }

        return $this->voters[$name];
    }

    /**
     * @return VoterInterface[]
     */
    public function getAllVoters()
    {
        return $this->voters;
    }
}


<?php
namespace FelixOnline\Base;

/*
 * Base model class
 *
 * Creates dynamic getter functions for model fields
 */
class BaseModel
{
    public $fields = array(); // array that holds all the database fields
    protected $class;
    protected $item;

    public function __construct($fields, $item = null)
    {
        $this->class = get_class($this);
        $this->item = $item;

        $this->fields = $fields;

        return $this->fields;
    }

    /*
     * Create dynamic functions
     */
    public function __call($method, $arguments)
    {
        $meth = $this->from_camel_case(substr($method, 3, strlen($method)-3));
        $verb = substr($method, 0, 3);
        switch ($verb) {
            case 'get':
                if (array_key_exists($meth, $this->fields)) {
                    return $this->fields[$meth]->getValue();
                }
                throw new \FelixOnline\Exceptions\ModelConfigurationException(
                    'The requested field "'.$meth.'" does not exist',
                    $verb,
                    $meth,
                    $this->class,
                    $this->item
                );
                break;
            case 'set':
                $this->fields[$meth]->setValue($arguments[0]);
                return $this;
                break;
            case 'has':
                if (array_key_exists($meth, $this->fields)) {
                    return true;
                }
                return false;
                break;
            default:
                throw new \FelixOnline\Exceptions\ModelConfigurationException(
                    'The requested verb is not valid',
                    $verb,
                    $meth,
                    $this->class,
                    $this->item
                );
                break;
        }
    }

    /*
     * Convert camel case to underscore
     * http://www.paulferrett.com/2009/php-camel-case-functions/
     */
    protected function from_camel_case($str)
    {
        $str[0] = strtolower($str[0]);
        $func = create_function('$c', 'return "_" . strtolower($c[1]);');
        return preg_replace_callback('/([A-Z])/', $func, $str);
    }

    /*
     * Public: Get all fields
     */
    public function getFields()
    {
        return $this->fields;
    }
}


<?php

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

/**
 * Encryptor.php.
 *
 * Part of Overtrue\WeChat.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @author    mingyoung <mingyoungcheung@gmail.com>
 * @copyright 2016
 *
 * @see      https://github.com/overtrue
 * @see      http://overtrue.me
 */

namespace EasyWeChat\MiniProgram\Encryption;

use EasyWeChat\Encryption\EncryptionException;
use EasyWeChat\Encryption\Encryptor as BaseEncryptor;
use Exception;

class Encryptor extends BaseEncryptor
{
    /**
     * Decrypt data.
     *
     * @param string $sessionKey
     * @param string $iv
     * @param string $encrypted
     *
     * @return array
     */
    public function decryptData($sessionKey, $iv, $encrypted)
    {
        try {
            $decrypted = openssl_decrypt(
                base64_decode($encrypted, true), 'aes-128-cbc', base64_decode($sessionKey, true),
                OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, base64_decode($iv, true)
            );
        } catch (Exception $e) {
            throw new EncryptionException($e->getMessage(), EncryptionException::ERROR_DECRYPT_AES);
        }

        if (is_null($result = json_decode($this->decode($decrypted), true))) {
            throw new EncryptionException('ILLEGAL_BUFFER', EncryptionException::ILLEGAL_BUFFER);
        }

        return $result;
    }
}


<?php
/**
 * User: Alex Gusev <alex@flancer64.com>
 */

namespace Praxigento\BonusHybrid\Service\Calc\Bonus;

use Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent\Request as AGetPeriodRequest;
use Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent\Response as AGetPeriodResponse;
use Praxigento\BonusBase\Repo\Data\Log\Opers as ELogOper;
use Praxigento\BonusHybrid\Config as Cfg;
use Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Data\Bonus as DBonus;
use Praxigento\Downline\Repo\Data\Customer as ECustomer;

/**
 * Calculate Personal Bonus.
 */
class Personal
    implements \Praxigento\Core\Api\App\Service\Process
{
    /** @var \Praxigento\BonusHybrid\Repo\Dao\Downline */
    private $daoBonDwnl;
    /** @var \Praxigento\BonusBase\Repo\Dao\Calculation */
    private $daoCalc;
    /** @var \Praxigento\Downline\Repo\Dao\Customer */
    private $daoDwnl;
    /** @var \Praxigento\BonusBase\Repo\Dao\Level */
    private $daoLevel;
    /** @var \Praxigento\BonusBase\Repo\Dao\Log\Opers */
    private $daoLogOper;
    /** @var \Praxigento\BonusBase\Helper\Calc */
    private $hlpCalc;
    /** @var \Praxigento\Downline\Api\Helper\Tree */
    private $hlpDwnlTree;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Helper\CreateOper */
    private $hlpOper;
    /** @var  \Praxigento\Core\Api\Helper\Period */
    private $hlpPeriod;
    /** @var  \Praxigento\BonusHybrid\Api\Helper\Scheme */
    private $hlpScheme;
    /** @var  \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Helper\PrepareTrans */
    private $hlpTrans;
    /** @var \Praxigento\Core\Api\App\Logger\Main */
    private $logger;
    /** @var \Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent */
    private $servPeriodGet;

    public function __construct(
        \Praxigento\Core\Api\App\Logger\Main $logger,
        \Praxigento\Core\Api\Helper\Period $hlpPeriod,
        \Praxigento\BonusBase\Helper\Calc $hlpCalc,
        \Praxigento\BonusHybrid\Api\Helper\Scheme $hlpScheme,
        \Praxigento\Downline\Api\Helper\Tree $hlpDwnlTree,
        \Praxigento\Downline\Repo\Dao\Customer $daoDwnl,
        \Praxigento\BonusBase\Repo\Dao\Calculation $daoCalc,
        \Praxigento\BonusBase\Repo\Dao\Level $daoLevel,
        \Praxigento\BonusBase\Repo\Dao\Log\Opers $daoLogOper,
        \Praxigento\BonusHybrid\Repo\Dao\Downline $daoBonDwnl,
        \Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent $servPeriodGet,
        \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Helper\PrepareTrans $hlpTrans,
        \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Helper\CreateOper $hlpOper
    ) {
        $this->logger = $logger;
        $this->hlpPeriod = $hlpPeriod;
        $this->hlpCalc = $hlpCalc;
        $this->hlpScheme = $hlpScheme;
        $this->hlpDwnlTree = $hlpDwnlTree;
        $this->daoDwnl = $daoDwnl;
        $this->daoCalc = $daoCalc;
        $this->daoLevel = $daoLevel;
        $this->daoLogOper = $daoLogOper;
        $this->daoBonDwnl = $daoBonDwnl;
        $this->servPeriodGet = $servPeriodGet;
        $this->hlpTrans = $hlpTrans;
        $this->hlpOper = $hlpOper;
    }

    /**
     * Walk through the compressed downline tree and calculate Personal bonus for DEFAULT scheme.
     *
     * @param \Praxigento\Downline\Repo\Data\Customer[] $dwnlCurrent
     * @param \Praxigento\BonusHybrid\Repo\Data\Downline[] $dwnlCompress
     * @param array $levels percents for bonus levels ([level=>percent])
     *
     * @return DBonus[]
     */
    private function calcBonus($dwnlCurrent, $dwnlCompress, $levels)
    {
        $result = [];
        $mapCustomer = $this->hlpDwnlTree->mapById($dwnlCurrent, ECustomer::A_CUSTOMER_REF);
        /** @var \Praxigento\BonusHybrid\Repo\Data\Downline $one */
        foreach ($dwnlCompress as $one) {
            $custId = $one->getCustomerRef();
            $pvValue = $one->getPv();
            $customer = $mapCustomer[$custId];
            $scheme = $this->hlpScheme->getSchemeByCustomer($customer);
            if ($scheme == Cfg::SCHEMA_DEFAULT) {
                $bonusValue = $this->hlpCalc->calcForLevelPercent($pvValue, $levels);
                if ($bonusValue > 0) {
                    $entry = new DBonus();
                    $entry->setCustomerRef($custId);
                    $entry->setValue($bonusValue);
                    $result[] = $entry;
                }
            }
        }
        return $result;
    }

    public function exec(\Praxigento\Core\Data $ctx)
    {
        /**
         * perform processing
         */
        $ctx->set(self::CTX_OUT_SUCCESS, false);
        $this->logger->info("Personal bonus is started.");
        /* get dependent calculation data */
        /** @var \Praxigento\BonusBase\Repo\Data\Calculation $compressCalc */
        /** @var \Praxigento\BonusBase\Repo\Data\Period $persPeriod */
        /** @var \Praxigento\BonusBase\Repo\Data\Calculation $persCalc */
        list($compressCalc, $persPeriod, $persCalc) = $this->getCalcData();
        $baseCalcId = $compressCalc->getId();
        $depCalcId = $persCalc->getId();
        /* load downlines (compressed for period & current) */
        $dwnlCompress = $this->daoBonDwnl->getByCalcId($baseCalcId);
        $dwnlCurrent = $this->daoDwnl->get();
        /* get levels to calculate Personal bonus */
        $levels = $this->daoLevel->getByCalcTypeCode(Cfg::CODE_TYPE_CALC_BONUS_PERSONAL);
        /* calculate bonus*/
        $bonus = $this->calcBonus($dwnlCurrent, $dwnlCompress, $levels);
        /* convert calculated bonus to transactions */
        $trans = $this->getTransactions($bonus, $persPeriod);
        /* register bonus operation */
        $operRes = $this->hlpOper->exec(Cfg::CODE_TYPE_OPER_BONUS_PERSONAL, $trans, $persPeriod);
        $operId = $operRes->getOperationId();
        /* register operation in log */
        $this->saveLog($operId, $depCalcId);
        /* mark this calculation complete */
        $this->daoCalc->markComplete($depCalcId);
        /* mark process as successful */
        $ctx->set(self::CTX_OUT_SUCCESS, true);
        $this->logger->info("Personal bonus is completed.");
    }

    /**
     * Get data for dependent calculation.
     *
     * @return array [$periodData, $calcData]
     */
    private function getCalcData()
    {
        /**
         * Get period & calc data.
         */
        $req = new AGetPeriodRequest();
        $req->setBaseCalcTypeCode(Cfg::CODE_TYPE_CALC_COMPRESS_PHASE1);
        $req->setDepCalcTypeCode(Cfg::CODE_TYPE_CALC_BONUS_PERSONAL);
        /** @var AGetPeriodResponse $resp */
        $resp = $this->servPeriodGet->exec($req);
        /** @var \Praxigento\BonusBase\Repo\Data\Calculation $compressCalc */
        $compressCalc = $resp->getBaseCalcData();
        /** @var \Praxigento\BonusBase\Repo\Data\Period $persPeriod */
        $persPeriod = $resp->getDepPeriodData();
        /** @var \Praxigento\BonusBase\Repo\Data\Calculation $persCalc */
        $persCalc = $resp->getDepCalcData();
        /**
         * Compose result.
         */
        $result = [$compressCalc, $persPeriod, $persCalc];
        return $result;
    }

    /**
     * @param array $bonus [custId => bonusValue]
     * @param \Praxigento\BonusBase\Repo\Data\Period $period
     * @return \Praxigento\Accounting\Repo\Data\Transaction[]
     */
    private function getTransactions($bonus, $period)
    {
        $dsEnd = $period->getDstampEnd();
        $dateApplied = $this->hlpPeriod->getTimestampUpTo($dsEnd);
        $yyyymm = substr($dsEnd, 0, 6);
        $note = "Personal ($yyyymm)";
        $result = $this->hlpTrans->exec($bonus, $dateApplied, $note);
        return $result;
    }

    /**
     * Bind operation with calculation.
     *
     * @param int $operId
     * @param int $calcId
     */
    private function saveLog($operId, $calcId)
    {
        $entity = new ELogOper();
        $entity->setOperId($operId);
        $entity->setCalcId($calcId);
        $this->daoLogOper->create($entity);
    }

}


<?php
/**
 * Copyright (c)2014-2014 heiglandreas
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIBILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @category
 * @author    Andreas Heigl<andreas@heigl.org>
 * @copyright ©2014-2014 Andreas Heigl
 * @license   http://www.opesource.org/licenses/mit-license.php MIT-License
 * @version   0.0
 * @since     28.06.14
 * @link      https://github.com/heiglandreas/
 */

namespace OrgHeiglPiwik;

use Zend\EventManager\StaticEventManager;
use Zend\Mvc\MvcEvent;
use Zend\View\ViewEvent;
use Zend\View\View;

class Module
{
    protected $template = <<<EOT
  var _paq = _paq || [];
  _paq.push(['trackPageView']);
  _paq.push(['enableLinkTracking']);
  (function() {
    var u="//%%server%%/";
    _paq.push(['setTrackerUrl', u+'piwik.php']);
    _paq.push(['setSiteId', %%site_id%%]);
    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
    g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
  })();
EOT;

    protected $serviceManager = null;

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function onBootstrap(MvcEvent $e)
    {
        $this->serviceManager = $e->getApplication()->getServiceManager();
    }

    public function init()
    {
        // Attach Event to EventManager
        $events = StaticEventManager::getInstance ();

        // Add event of authentication before dispatch
        $events->attach('Zend\View\View', ViewEvent::EVENT_RENDERER_POST, array(
            $this,
            'addPiwikCode'
        ), 110 );
    }

    /**
     * Include the PIWIK-Tracking-code into every page.
     *
     * @param $event
     */
    public function addPiwikCode(ViewEvent $event)
    {
        $model = $event->getModel();
        if (! $model instanceof \Zend\View\Model\ViewModel) {
            return;
        }

        // Return if this is a subrenderer. Therefore we only render once!
        $options = $model->getOptions();
        if (array_key_exists('has_parent', $options) && $options['has_parent']) {
            return;
        }

        $renderer = $event->getRenderer();
        if (! $renderer instanceof \Zend\View\Renderer\PhpRenderer) {
            return;
        }

        $config         = $this->serviceManager->get('config');
        $piwikConfig    = $config['orgHeiglPiwik'];

        $code = str_replace(array_map(function($e){
            return '%%' . $e . '%%';
        }, array_keys($piwikConfig)), array_values($piwikConfig), $this->template);

        $renderer->headScript()->appendScript('//<![CDATA[' . "\n" . $code . "\n" . '//]]>');

        return $renderer;
    }
}


<?php

/*
 * This File is part of the Thapp\Jmg\Http\Psr7 package
 *
 * (c) iwyg <mail@thomas-appel.com>
 *
 * For full copyright and license information, please refer to the LICENSE file
 * that was distributed with this package.
 */

namespace Thapp\Jmg\Http\Psr7;

use DateTime;
use Psr\Http\Message\MessageInterface;
use Thapp\Jmg\Resource\CachedResourceInterface;
use Thapp\Jmg\Resource\ImageResourceInterface as ImageResource;

/**
 * @class ResponseFactory
 *
 * @package Thapp\Jmg\Http\Psr7
 * @version $Id$
 * @author iwyg <mail@thomas-appel.com>
 */
class ResponseFactory implements ImageResponseFactoryInterface
{
    /** @var bool */
    private $useXsend;

    /**
     * Constructor.
     *
     * @param bool $useXsend
     */
    public function __construct($useXsend = false)
    {
        $this->useXsend = (bool)$useXsend;
    }

    /**
     * {@inheritdoc}
     */
    public function getResponse(MessageInterface $request, ImageResource $resource)
    {
        $version = $request->getProtocolVersion();
        $etag    = $request->getHeaderLine('if-none-match');

        list($time, $lastMod, $mod, $modDate) = $this->getModTimes($request, $resource);
        $headers = $this->getDefaultHeaders($lastMod, $resource->getHash());

        if (0 === strcmp($etag, $headers['etag']) ||
            // not modified response
            (($resource instanceof CachedResourceInterface &&
            $resource->isFresh($time)) && $mod === $modDate)) {
            $response = (new NotModifiedImageResonse($resource, [], $version))
                ->withHeader('content-type', $resource->getMimeType())
                ->withHeader('cache-control', 'public');
        } else {
            // normal response
            if ($this->useXsend && !empty($request->getHeaderLine('x-sendfile-type'))) {
                $headers = $this->getXsendfileHeaders($resource, $headers);
            }

            $response = new ImageResponse($resource, $headers, $version);
        }

        return $response;
    }

    /**
     * getModTimes
     *
     * @param MessageInterface $request
     * @param ImageResource $resource
     *
     * @return array
     */
    private function getModTimes(MessageInterface $request, ImageResource $resource)
    {
        $time = time();
        return [
            $time,
            (new DateTime)->setTimestamp($modDate = $resource->getLastModified()),
            strtotime($request->getHeaderLine('if-modified-since')) ?: $time,
            $modDate
        ];
    }

    /**
     * getDefaultHeaders
     *
     * @param DateTime $lastMod
     * @param srting $resourceEtag
     *
     * @return array
     */
    private function getDefaultHeaders(DateTime $lastMod, $resourceEtag)
    {
        return [
            'last-modified' => $lastMod->format('D, d M Y H:i:s').' GMT',
            'etag' => $resourceEtag
        ];
    }

    /**
     * getXsendfileHeaders
     *
     * @param ImageResource $resource
     * @param array $originalHeaders
     *
     * @return array
     */
    private function getXsendfileHeaders(ImageResource $resource, array $originalHeaders = [])
    {
        return array_merge($originalHeaders, [
            'content-disposition' => sprintf('inline; filename="%s"', basename($file = $resource->getPath())),
            'content-lenght' => filesize($file),
            'x-sendfile' => $file
        ]);
    }
}


<?php
namespace core\manage\logic;

use cms\Logic;
use think\Cache;

class ConfigLogic extends Logic
{

    /**
     * 缓存key
     *
     * @var unknown
     */
    const CACHE_KEY = 'common_config_cache';

    /**
     * 配置分组
     *
     * @return array
     */
    public function getGroupList()
    {
        $list = $this->model->order('config_sort asc')->select();
        $res = [];
        foreach ($list as $vo) {
            $group = $vo['config_group'];
            if (! isset($res[$group])) {
                $res[$group] = [
                    'name' => $group,
                    'key' => md5($group),
                    'list' => []
                ];
            }
            $res[$group]['list'][] = $this->processGroupItem($vo);
        }
        return $res;
    }

    /**
     * 处理分组
     *
     * @param array $item
     * @return array
     */
    public function processGroupItem($item)
    {
        switch ($item['config_type']) {
            case 'array':
                $arr = empty($item['config_extra']) ? [] : explode(',', $item['config_extra']);
                $value = empty($item['config_value']) ? [] : json_decode($item['config_value'], true);
                foreach ($arr as $vo) {
                    if (! isset($value[$vo])) {
                        $value[$vo] = '';
                    }
                }
                $item['config_value'] = json_encode($value, JSON_UNESCAPED_UNICODE);
                break;
            case 'radio':
            case 'checkbox':
            case 'select':
                $arr = empty($item['config_extra']) ? [] : explode('|', $item['config_extra']);
                $extra = [];
                foreach ($arr as $vo) {
                    list ($value, $name) = explode(':', $vo);
                    $extra[] = [
                        'name' => $name,
                        'value' => $value
                    ];
                }
                $item['config_extra'] = $extra;
                break;
        }
        return $item;
    }

    /**
     * 获取配置
     *
     * @return array
     */
    public function getConfig()
    {
        $config = Cache::get(self::CACHE_KEY);
        if (empty($config)) {
            $list = $this->model->select();
            $config = [];
            foreach ($list as $vo) {
                switch ($vo['config_type']) {
                    case 'checkbox':
                    case 'array':
                        $vo['config_value'] = empty($vo['config_value']) ? [] : @json_decode($vo['config_value'], true);
                        break;
                }
                $config[$vo['config_name']] = $vo['config_value'];
            }

            // 处理变量
            $config = $this->processConfig($config);

            Cache::set(self::CACHE_KEY, $config);
        }
        return $config;
    }

    /**
     * 添加配置
     *
     * @param array $data
     * @return boolean
     */
    public function addConfig($data)
    {
        $this->model->add($data);

        return $this->clearCache();
    }

    /**
     * 保存配置
     *
     * @param array $data
     * @param mixed $map
     * @return boolean
     */
    public function saveConfig($data, $map)
    {
        $this->model->saveById($data, $map);

        return $this->clearCache();
    }

    /**
     * 更改配置
     *
     * @param number $id
     * @param string $field
     * @param string $value
     * @return boolean
     */
    public function modifyConfig($id, $field, $value)
    {
        $this->model->modify($id, $field, $value);

        return $this->clearCache();
    }

    /**
     * 删除配置
     *
     * @param mixed $map
     * @return boolean
     */
    public function delConfig($map)
    {
        $this->model->del($map);

        return $this->clearCache();
    }

    /**
     * 清除缓存
     *
     * @return boolean
     */
    public function clearCache()
    {
        return Cache::rm(self::CACHE_KEY);
    }

    /**
     * 处理配置
     *
     * @param array $config
     * @return array
     */
    public function processConfig($config)
    {
        $var_list = $this->getVariableList();
        foreach ($config as $co => $vo) {
            if (is_array($vo)) {
                $config[$co] = $this->processConfig($vo);
            } else {
                $config[$co] = str_replace($var_list[0], $var_list[1], $config[$co]);
            }
        }
        return $config;
    }

    /**
     * 变量列表
     *
     * @return array
     */
    public function getVariableList()
    {
        if (empty($this->var_list)) {
            $this->var_list = [
                [],
                []
            ];
            $list = [
                '{EXT}' => EXT,
                '{DS}' => DS,
                '{THINK_PATH}' => THINK_PATH,
                '{WEB_PATH}' => WEB_PATH,
                '{ROOT_PATH}' => ROOT_PATH,
                '{APP_PATH}' => APP_PATH,
                '{CONF_PATH}' => CONF_PATH,
                '{LIB_PATH}' => LIB_PATH,
                '{CORE_PATH}' => CORE_PATH,
                '{TRAIT_PATH}' => TRAIT_PATH,
                '{EXTEND_PATH}' => EXTEND_PATH,
                '{VENDOR_PATH}' => VENDOR_PATH,
                '{RUNTIME_PATH}' => RUNTIME_PATH,
                '{LOG_PATH}' => LOG_PATH,
                '{CACHE_PATH}' => CACHE_PATH,
                '{TEMP_PATH}' => TEMP_PATH
            ];
            foreach ($list as $co => $vo) {
                $this->var_list[0][] = $co;
                $this->var_list[1][] = $vo;
            }
        }
        return $this->var_list;
    }

    /**
     * 配置类型
     *
     * @return array
     */
    public function getConfigType()
    {
        return [
            [
                'name' => '文本',
                'value' => 'text'
            ],
            [
                'name' => '文本域',
                'value' => 'textarea'
            ],
            [
                'name' => '标签',
                'value' => 'tag'
            ],
            [
                'name' => '日期',
                'value' => 'date'
            ],
            [
                'name' => '颜色',
                'value' => 'color'
            ],
            [
                'name' => '图片',
                'value' => 'image'
            ],
            [
                'name' => '文件',
                'value' => 'file'
            ],
            [
                'name' => '多选',
                'value' => 'checkbox'
            ],
            [
                'name' => '单选',
                'value' => 'radio'
            ],
            [
                'name' => '下拉',
                'value' => 'select'
            ],
            [
                'name' => '数组',
                'value' => 'array'
            ],
            [
                'name' => '富文本',
                'value' => 'editor'
            ]
        ];
    }
}


<?php

namespace Wambo\Catalog;

use Wambo\Catalog\Exception\RepositoryException;
use Wambo\Catalog\Mapper\ProductMapper;
use Wambo\Catalog\Model\Product;
use Wambo\Core\Storage\StorageInterface;

/**
 * Class ProductRepository fetches Product models from the Storage and writes Products back to the Storage
 *
 * @package Wambo\Catalog
 */
class ProductRepository implements ProductRepositoryInterface
{
    /**
     * @var StorageInterface
     */
    private $productStorage;
    /**
     * @var ProductMapper
     */
    private $productMapper;

    /**
     * Creates a new ProductRepository instance.
     *
     * @param StorageInterface $productStorage A product storage for reading and writing product data
     * @param ProductMapper    $productMapper  A product mapper for mapping unstructured data to Product models and
     *                                         vice versa
     */
    public function __construct(StorageInterface $productStorage, ProductMapper $productMapper)
    {
        $this->productStorage = $productStorage;
        $this->productMapper = $productMapper;
    }

    /**
     * Get all products
     *
     * @return Product[]
     *
     * @throws RepositoryException If fetching the products failed
     */
    public function getProducts()
    {
        try {

            // read product data from storage
            $productDataArray = $this->productStorage->read();

            // deserialize the product data
            $products = [];
            foreach ($productDataArray as $productData) {
                $products[] = $this->productMapper->getProduct($productData);
            }

            return $products;

        } catch (\Exception $readException) {
            throw new RepositoryException("Failed to read products from storage provider.", $readException);
        }
    }

    public function getById(string $id)
    {
        throw new RepositoryException("Not implemented yet");
    }

    public function add(Product $product)
    {
        throw new RepositoryException("Not implemented yet");
    }

    public function remove(Product $product)
    {
        throw new RepositoryException("Not implemented yet");
    }
}


<?php

/**
 * @link http://framework.zend.com/manual/1.12/en/zend.application.html Zend_Application
 */
class Benri_Application extends Zend_Application
{
    /**
     * Singleton instance.
     *
     * @var Benri_Application
     */
    protected static $_instance;

    /**
     * Returns an instance of Benri_Application.
     *
     * Singleton pattern implementation
     *
     * @return Benri_Application
     */
    public static function getInstance()
    {
        return self::$_instance;
    }

    /**
     * Create and returns an instance of Benri_Application.
     */
    public static function createInstance($environment, $options = null)
    {
        if (!self::$_instance) {
            self::$_instance = new static($environment, $options, false);
        }

        return self::$_instance;
    }
}


<?php

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

/**
 * This class manage the Template
 *
 * @category  	Venus
 * @package     Venus\lib\Functions
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 3.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	3.0.0
 */
class Asset
{
	/**
	 * run before
	 *
	 * @access public
	 * @param  array $aParams parameters
	 * @return string
	 */
	public function replaceBy(array $aParams = array()) : string
	{
	    $aParams['template'] = trim(str_replace(["'", '"'], "", $aParams['template']));

		if (isset($aParams['template'])) {

		    $aTemplates = explode(';', $aParams['template']);
		    $sGetUrl = 'getCss?';

		    foreach ($aTemplates as $sTemplate) {

    		    if (strstr($sTemplate, 'css/')) {

    		        $sGetUrl .= $sTemplate.'&';
    		    }
    		    else if (strstr($sTemplate, 'js/')) {

    		        $sGetUrl .= $sTemplate.'&';
    		    }
		    }

		    if (defined('ASSET_VERSION') && ASSET_VERSION !== false) {

		        $sGetUrl .= ASSET_VERSION;
		    }

			return $sGetUrl;
		}
	}
}


<?php

namespace Gaufrette\Core\Operator;

use Gaufrette\Core\Adapter;
use Gaufrette\Core\File;

final class MetadataOperator extends AbstractOperator implements CanLoad, CanSave
{
    /**
     * {@inheritdoc}
     */
    public function supports(File $file, Adapter $adapter)
    {
        return $this->adapterHasBehavior($adapter, 'Gaufrette\Core\Adapter\KnowsMetadata');
    }

    /**
     * {@inheritdoc}
     */
    public function load(File $file, Adapter $adapter)
    {
        $file->setMetadata($adapter->readMetadata($file->getName()));
    }

    /**
     * {@inheritdoc}
     */
    public function save(File $file, Adapter $adapter)
    {
        $adapter->writeMetadata($file->getName(), $file->getMetadata());
    }
}


<?php
/**
 * CoolMS2 User Module (http://www.coolms.com/)
 *
 * @link      http://github.com/coolms/user for the canonical source repository
 * @copyright Copyright (c) 2006-2015 Altgraphic, ALC (http://www.altgraphic.com)
 * @license   http://www.coolms.com/license/new-bsd New BSD License
 * @author    Dmitry Popov <d.popov@altgraphic.com>
 */

namespace CmsUser\Factory\Validator;

use Zend\I18n\Validator\Alnum,
    Zend\ServiceManager\DelegatorFactoryInterface,
    Zend\ServiceManager\ServiceLocatorInterface,
    Zend\Validator\Callback,
    Zend\Validator\ValidatorChain,
    Zend\Validator\ValidatorInterface,
    CmsUser\Options\InputFilterOptionsInterface,
    CmsUser\Options\ModuleOptions;

class IdentityValidatorDelegatorFactory implements DelegatorFactoryInterface
{
    /**
     * {@inheritDoc}
     *
     * @return ValidatorInterface
     */
    public function createDelegatorWithName(
        ServiceLocatorInterface $validators,
        $name,
        $requestedName,
        $callback
    ) {
        $identityValidator = $callback();

        if (!$identityValidator instanceof ValidatorChain
            || $requestedName !== 'CmsAuthenticationIdentity'
        ) {
            return $identityValidator;
        }

        $services = $validators->getServiceLocator();

        /* @var $options InputFilterOptionsInterface */
        $options = $services->get(ModuleOptions::class);

        $identityFields = $options->getIdentityFields();
        if ($identityFields == ['email']) {
            $identityValidator->prependByName('EmailAddress', [], true);
        } elseif ($identityFields == ['username']) {
            $identityValidator->prependByName('Alnum', [
                'messages' => [
                    Alnum::NOT_ALNUM => 'Incorrect identity. ' .
                    'Identity must contain alphanumeric characters without spaces',
                ],
                'allowWhiteSpace' => false,
            ], true);
        }

        /* @var $userMapper \CmsUser\Persistence\UserMapperInterface */
        $userMapper = $services->get('MapperManager')->get($options->getUserEntityClass());

        $identityValidator->attachByName('Callback', [
            'messages' => [
                Callback::INVALID_VALUE => 'A record with the supplied identity could not be found',
            ],
            'callback' => function($value) use ($userMapper) {
                return (bool) $userMapper->findByIdentity($value);
            },
        ], true);

        return $identityValidator;
    }
}


<?php
namespace FelixOnline\Base;

use FelixOnline\Exceptions\InternalException;
use FelixOnline\Exceptions\ModelNotFoundException;
use FelixOnline\Exceptions\SQLException;

/**
 * Base DB class
 */
class BaseDB extends BaseModel
{
    public $fields = array(); // array that holds all the database fields
    public $dbtable; // name of database table
    public $pk;
    protected $initialFields;
    protected $constructorId;

    private $new;
    private $dontlog;

    public function __construct(
        $fields,
        $id = null,
        $dbtable = null,
        $dontlog = false,
        $rowData = null
    ) {
        $app = App::getInstance();

        if (!is_null($dbtable)) {
            $this->dbtable = $dbtable;
        }

        $this->dontlog = $dontlog;

        if (!is_array($fields) || empty($fields)) {
            throw new InternalException('No fields defined');
        }

        if (array_key_exists('deleted', $fields)) {
            throw new InternalException(
                'The column "deleted" is reserved by the database layer, and should not be specified.'
            );
        }

        $fields['deleted'] = new Type\BooleanField();

        if (!$this->dbtable) {
            throw new InternalException('No table specified');
        }

        $this->pk = $this->findPk($fields);

        $this->new = true;

        if (!is_null($id)) {
            $this->constructorId = $id;

            $fields[$this->pk]->setValue($id);

            $results = $this->getValues($fields, $rowData);

            foreach ($results as $column => $value) {
                $fields[$column]->setValue($value);
            }

            if ($fields['deleted']->getValue() == true) {
                throw new ModelNotFoundException(
                    'This model has been deleted',
                    $this->dbtable,
                    $this->constructorId
                );
            }

            $this->new = false;
        } else {
            $fields['deleted']->setValue(false);
        }

        // PHP passes all objects by reference so we need to clone the fields
        // so that the initial fields don't get updated when the fields change
        $_fields = array();
        foreach ($fields as $k => $f) {
            $_fields[$k] = clone $f;
        }
        $this->initialFields = $_fields;
        parent::__construct($fields);
    }

    /**
     * Query database and return results
     */
    protected function getValues($fields, $preCalculatedResult = false)
    {
        if ($preCalculatedResult) {
            return $preCalculatedResult;
        }

        $app = App::getInstance();

        $sql = $this->constructSelectSQL($fields);

        // get cache
        $item = $this->getCache($fields[$this->pk]);
        $results = $item->get(\Stash\Invalidation::PRECOMPUTE, 300);

        if ($item->isMiss()) {
            $results = $this->runGetRow($sql);

            if ($app['db']->last_error) {
                throw new SQLException(
                    $app['db']->last_error,
                    $app['db']->captured_errors
                );
            }

            if (is_null($results)) {
                throw new ModelNotFoundException(
                    'No model in database',
                    $this->dbtable,
                    $this->constructorId
                );
            }

            $app['cache']->save($item->set($results));
        }

        return $results;
    }

    /**
     * Get cache item
     *
     * pk - primary key column
     */
    protected function getCache($pk)
    {
        $app = App::getInstance();
        return $app['cache']->getItem($this->dbtable.'/'.$pk->getValue());
    }

    /**
     * Public: Delete the model. Restores instance of model back to if it was created with no ID
     */
    public function delete()
    {
        $app = App::getInstance();

        // update model
        if ($this->pk && $this->getPk()->getValue()) {
            $this->setDeleted(true)->save();

            // clear cache
            $item = $this->getCache($this->getPk());
            $item->clear();

            // clear model
            $this->constructorId = null;
            $this->pk = null;
            $this->initialFields = null;
        } else {
            throw new InternalException(
                'Trying to delete a model that does not yet exist'
            );
        }

        return true;
    }

    /**
     * Public: Actually delete the model (i.e. DELETE FROM query). Restores instance of model back to if it was created with no ID
     */
    public function purge($reason)
    {
        $app = App::getInstance();

        // update model
        if ($this->pk && $this->getPk()->getValue()) {
            $this->log('purge', "**PURGED FROM DATABASE** Reason: ".$reason);

            $sql = $app['safesql']->query(
                "DELETE FROM ".$this->dbtable." WHERE ".$this->pk." = '%s';",
                array($this->getPk()->getValue())
            );

            $this->runQuery($sql);

            // clear cache
            $item = $this->getCache($this->getPk());
            $item->clear();

            // clear model
            $this->constructorId = null;
            $this->pk = null;
            $this->initialFields = null;
        } else {
            throw new InternalException(
                'Trying to delete a model that does not yet exist'
            );
        }

        return true;
    }

    /**
     * Public: Save all fields to database
     *
     * Example:
     *      $obj = new Obj();
     *      $obj->setTable('comment');
     *      $obj->setUser('k.onions');
     *      $obj->setContent('hello');
     *      $obj->save();
     */
    public function save()
    {
        $app = App::getInstance();

        // update model
        if ($this->getPk()->getValue() && !$this->new) {
            // Determine what has been modified
            $changed = array();
            foreach ($this->initialFields as $column => $field) {
                if ($this->fields[$column]->getRawValue() !== $field->getRawValue()) {
                    $changed[$column] = $this->fields[$column];
                }
            }

            if (!empty($changed)) {
                $sql = $this->constructUpdateSQL($changed, $this->fields);

                $this->runQuery($sql);
                if ($app['db']->last_error) {
                    throw new SQLException(
                        $app['db']->last_error,
                        $app['db']->captured_errors
                    );
                }

                $this->constructorId = $this->getPk();

                // clear cache
                $item = $this->getCache($this->getPk());
                $item->clear();

                $this->log_update();
            }
        } else { // insert model
            $sql = $this->constructInsertSQL($this->fields);

            $this->runQuery($sql);
            if ($app['db']->last_error) {
                throw new SQLException(
                    $app['db']->last_error,
                    $app['db']->captured_errors
                );
            }

            $this->pk = $this->findPk($this->fields);

            if ($app['db']->insert_id) {
                $this->fields[$this->pk]->setValue($app['db']->insert_id);
            }

            $this->new = false;
            $this->constructorId = $this->getPk();

            $this->log_create();
        }

        $this->initialFields = $this->fields;

        return $this->getPk()->getValue(); // return new id
    }

    /**
     * Construct the select sql to retrive model from db
     */
    public function constructSelectSQL($fields)
    {
        $sql = array();

        $sql[] = "SELECT";

        $sql[] = "`" . implode("`, `", array_keys($fields)) . "`";

        $sql[] = "FROM `" . $this->dbtable . "`";
        $sql[] = "WHERE `" . $this->pk . "` = " . $fields[$this->pk]->getSQL();

        return implode(" ", $sql);
    }

    /**
     * Public: Construct SQL
     */
    public function constructInsertSQL($fields)
    {
        $sql = array();

        $sql[] = "INSERT INTO";
        $sql[] = "`" . $this->dbtable . "`";
        $sql[] = "(";

        $columns = array();
        foreach ($fields as $key => $value) {
            $columns[] = "`" . $key . "`";
        }

        $sql[] = implode(", ", $columns);

        $sql[] = ") VALUES (";

        $values = [];
        foreach ($fields as $key => $value) {
            $values[] = $value->getSQL();
        }

        $sql[] = implode(", ", $values);
        $sql[] = ")";

        return implode(" ", $sql);
    }

    /**
     * Public: Construct update SQL
     */
    public function constructUpdateSQL($changed, $fields)
    {
        $sql = array();

        $sql[] = "UPDATE";
        $sql[] = "`" . $this->dbtable . "`";
        $sql[] = "SET";

        $values = array();
        foreach ($changed as $key => $value) {
            $values[] = "`" . $key . "`=" . $value->getSQL();
        }
        $sql[] = implode(", ", $values);

        $sql[] = "WHERE `" . $this->pk . "`='" . $this->constructorId . "'";

        return implode(" ", $sql);
    }

    /**
     * Find pk
     */
    private function findPk(&$fields)
    {
        $pk = null;
        foreach ($fields as $column => $field) {
            if ($field->config['primary'] == true) {
                $pk = $column;
                break;
            }
        }

        // If there isn't a primary key defined then add a default one
        if (is_null($pk)) {
            $pk = 'id';
            $fields[$pk] = new Type\IntegerField(array('primary' => true));
        }

        return $pk;
    }

    /**
     * Get pk
     */
    public function getPk()
    {
        return $this->fields[$this->pk];
    }

    /**
     * Get data
     */
    public function getData()
    {
        $data = array();
        foreach ($this->fields as $key => $field) {
            if ($field instanceof Type\ForeignKey) { // foreign key exception
                $data[$key] = $field->getRawValue();
            } else {
                $data[$key] = $field->getValue();
            }
        }

        return $data;
    }

    /**
     * Audit log functions
     */
    private function log_create()
    {
        $this->log('create', array());
    }

    private function log_update()
    {
        $fields = array();

        foreach ($this->initialFields as $column => $field) {
            if ($this->fields[$column]->config['dont_log'] == true) {
                continue;
            }

            if ($this->fields[$column]->getRawValue() !== $field->getRawValue()) {
                $fields[$column] = array(
                    'old' => $field->getRawValue(),
                    'new' => $this->fields[$column]->getRawValue()
                );
            }
        }

        if (count($fields) == 0) {
            return;
        }

        $this->log('update', $fields);
    }

    private function log($action, $fields, $pk = null)
    {
        if ($this->dontlog) {
            return;
        }

        if (is_null($pk)) {
            $pk = $this->fields[$this->pk]->getValue();
        }

        $app = App::getInstance();

        if (isset($app['currentuser']) && $app['currentuser']->isLoggedIn()) {
            $user = $app['currentuser']->getUser();
        } else {
            $user = 'ANON';
        }

        $sql = $app['safesql']->query(
            "INSERT INTO audit_log (`id`,
                `timestamp`,
                `table`, `key`,
                `user`,
                `action`,
                `fields`
            ) VALUES (NULL, NOW(), '%s', '%s', '%s', '%s', '%s')",
            array($this->dbtable,
                $pk,
                $user,
                $action,
                json_encode($fields)));

        return $this->runQuery($sql);
    }

    public function runQuery($sql)
    {
        $app = App::getInstance();

        $time_start = time();
        $return = $app['db']->query($sql);
        $time_stop = time();

        $log = $app['db_log'];
        $log[] = array(
            'Query' => $sql,
            'Time' => $time_stop - $time_start
        );

        $app['db_log'] = $log;

        return $return;
    }

    public function runGetRow($sql)
    {
        $app = App::getInstance();

        $time_start = time();
        $return = $app['db']->get_row($sql);
        $time_stop = time();

        $log = $app['db_log'];
        $log[] = array(
            'Query' => $sql,
            'Time' => $time_stop - $time_start
        );

        $app['db_log'] = $log;

        return $return;
    }
}


<?php

namespace carlosV2\DumbsmartRepositoriesBundle\Configurer;

use carlosV2\DumbsmartRepositories\Exception\MetadataNotFoundException;
use carlosV2\DumbsmartRepositories\Exception\RepositoryNotFoundException;
use carlosV2\DumbsmartRepositories\MetadataManager;
use carlosV2\DumbsmartRepositories\RepositoryManager;
use carlosV2\DumbsmartRepositoriesBundle\Metadata\AliasedMetadataFactory;

class AliasesConfigurer
{
    /**
     * @var MetadataManager
     */
    private $mm;

    /**
     * @var RepositoryManager
     */
    private $rm;

    /**
     * @var AliasedMetadataFactory
     */
    private $amf;

    /**
     * @param MetadataManager        $mm
     * @param RepositoryManager      $rm
     * @param AliasedMetadataFactory $amf
     */
    public function __construct(
        MetadataManager $mm,
        RepositoryManager $rm,
        AliasedMetadataFactory $amf
    ) {
        $this->mm = $mm;
        $this->rm = $rm;
        $this->amf = $amf;
    }

    /**
     * @param array $aliases
     *
     * @throws MetadataNotFoundException
     * @throws RepositoryNotFoundException
     */
    public function configure(array $aliases)
    {
        foreach ($aliases as $alias => $config) {
            $this->mm->getMetadataForClassName($config['class'])->getObjectIdentifier()->setAlias($alias);

            $this->mm->addMetadata($alias, $this->amf->createMetadata($config));
            $this->rm->addRepository($alias, $this->rm->getRepositoryForClassName($config['class']));
        }
    }

}


<?php
namespace eMacros\Runtime\Arithmetic;

use eMacros\Runtime\GenericFunction;

class Subtraction extends GenericFunction {
	/**
	 * Obtains the result of subtracting the first element on a list by the rest of the elements.
	 * Usage: (- 120 30 50)
	 * Returns: number
	 * (non-PHPdoc)
	 * @see \eMacros\Runtime\GenericFunction::execute()
	 */
    public function execute(array $arguments) {
    	if (empty($arguments)) throw new \InvalidArgumentException("Subtraction: At least 1 argument is required");
    	//emulate CLISP: (- 3) = -3
    	if (!isset($arguments[1])) return -$arguments[0];
    	//obtain first argument
        $result = array_shift($arguments);
        foreach ($arguments as $value)
        	$result -= $value;
        return $result;
    }
}


<?php

declare (strict_types=1);

namespace Coshi\Variator;

use Coshi\Variator\Variation\AbstractVariation;
use Coshi\Variator\Exception\Helper;
use Coshi\Variator\Variation\VariationInterface;

class VariationsTreeBuilder
{
    public function __construct(VariationFactory $factory)
    {
        $this->factory = $factory;
    }

    /**
     * @param array $config
     *
     * @return VariationInterface
     *
     * @throws Exception\CircularDependencyException
     * @throws \InvalidArgumentException
     */
    public function build(array $config)
    {
        /** @var AbstractVariation[] $variations */
        $variations = [];

        foreach ($config as $name => $variation) {
            $variations[$name] = $this->factory->createNew($name, $variation);
        }

        return new ContainerVariation($this->buildTree($variations));
    }

    /**
     * @param AbstractVariation[] $variations
     *
     * @return AbstractVariation[]
     *
     * @throws Exception\CircularDependencyException
     */
    private function buildTree(array $variations)
    {
        $this->detectCircularDependencies($variations);
        $dependent = [];

        foreach ($variations as $root) {
            foreach ($variations as $key => $nested) {
                if ($nested->dependsOn($root->getName())) {
                    $dependent[] = $key;
                    $root->addNested($nested);
                }
            }
        }

        foreach ($dependent as $key) {
            unset($variations[$key]);
        }

        return $variations;
    }

    /**
     * @param array $variations
     *
     * @return array
     *
     * @throws Exception\CircularDependencyException
     */
    private function detectCircularDependencies(array $variations)
    {
        $tree = [];

        foreach ($variations as $variation) {
            $tree[$variation->getName()] = $this->detectCircular($variations, $variation, [$variation->getName()]);
        }

        return $tree;
    }

    /**
     * @param array             $variations
     * @param AbstractVariation $variation
     * @param array             $path
     *
     * @return bool
     *
     * @throws Exception\CircularDependencyException
     */
    private function detectCircular(array $variations, AbstractVariation $variation, array $path)
    {
        foreach ($variations as $item) {
            if ($item->dependsOn($variation->getName())) {
                if ($item === $variation
                    || $variation->dependsOn($item->getName())
                    || in_array($item->getName(), $path, true)) {
                    $path[] = $item->getName();
                    throw Helper::fromPath(implode('.', $path));
                }
                $this->detectCircular($variations, $item, $path);
            }
        }

        return false;
    }
}


<?php

declare(strict_types=1);

namespace Ruwork\AnnotationTools\Factory;

use Psr\Cache\CacheItemPoolInterface;
use Ruwork\AnnotationTools\Metadata\ClassMetadata;

final class CachedMetadataFactory implements MetadataFactoryInterface
{
    private $factory;
    private $cache;
    private $metadatas = [];

    public function __construct(MetadataFactoryInterface $factory, CacheItemPoolInterface $cache)
    {
        $this->factory = $factory;
        $this->cache = $cache;
    }

    /**
     * {@inheritdoc}
     */
    public function getMetadata(string $class): ClassMetadata
    {
        if (isset($this->metadatas[$class])) {
            return $this->metadatas[$class];
        }

        $item = $this->cache->getItem(str_replace('\\', '.', $class));

        if ($item->isHit()) {
            return $this->metadatas[$class] = $item->get();
        }

        $metadata = $this->metadatas[$class] = $this->factory->getMetadata($class);
        $item->set($metadata);

        $this->cache->save($item);

        return $metadata;
    }
}


<?php

declare(strict_types=1);

namespace Chubbyphp\Translation;

final class TranslationTwigExtension extends \Twig_Extension
{
    /**
     * @var TranslatorInterface
     */
    private $translator;

    /**
     * @param TranslatorInterface $translator
     */
    public function __construct(TranslatorInterface $translator)
    {
        $this->translator = $translator;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'translation';
    }

    /**
     * {@inheritdoc}
     */
    public function getFilters()
    {
        return [
            new \Twig_SimpleFilter('translate', [$this, 'translate']),
        ];
    }

    /**
     * @param string $key
     * @param string $locale
     * @param array  $args
     *
     * @return string
     */
    public function translate(string $key, string $locale, array $args = []): string
    {
        return $this->translator->translate($locale, $key, $args);
    }
}


<?php
namespace eMacros\Runtime\Type;

use eMacros\Applicable;
use eMacros\Symbol;
use eMacros\Scope;
use eMacros\GenericList;

class IsInstanceOf implements Applicable {
	/**
	 * Determines if a value is an instance of a given class
	 * Usage: (instance-of Acme\CustomClass _obj)
	 * Returns: boolean
	 * (non-PHPdoc)
	 * @see \eMacros\Applicable::apply()
	 */
	public function apply(Scope $scope, GenericList $arguments) {
		//check number of parameters
		if (count($arguments) == 0) throw new \BadFunctionCallException("IsInstanceOf: No arguments found.");
		if (count($arguments) == 1) throw new \BadFunctionCallException("IsInstanceOf: No class specified.");
		//obtain instance
		$instance = $arguments[0]->evaluate($scope);
		if (!is_object($instance)) return false;
		if (!($arguments[1] instanceof Symbol))
			throw new \InvalidArgumentException(sprintf("InstanceOf: Expected symbol as second argument but %s was found instead.", substr(strtolower(strstr(get_class($arguments[1]), '\\')), 1)));
		return (new \ReflectionClass($arguments[1]->symbol))->isInstance($instance);
	}
}
?>


<?php
namespace eMacros\Runtime\Logical;

use eMacros\Applicable;
use eMacros\GenericList;
use eMacros\Scope;

class Cond implements Applicable {
	/**
	 * Returns a value depending on a condition
	 * Usage: (cond ((is-integer? (%0)) 'Integer') ((is-string? (%0)) 'String') (true 'Unexpected type'))
	 * Returns: mixed
	 * (non-PHPdoc)
	 * @see \eMacros\Applicable::apply()
	 */
	public function apply(Scope $scope, GenericList $arguments) {
		foreach ($arguments as $pair) {
			list($condition, $body) = $pair;
			if ($condition->evaluate($scope)) return $body->evaluate($scope);
		}
	}
}
?>


<?php

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

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

namespace EasyWeChat\User;

use EasyWeChat\Core\AbstractAPI;

/**
 * Class User.
 */
class User extends AbstractAPI
{
    const API_GET = 'https://api.weixin.qq.com/cgi-bin/user/info';
    const API_BATCH_GET = 'https://api.weixin.qq.com/cgi-bin/user/info/batchget';
    const API_LIST = 'https://api.weixin.qq.com/cgi-bin/user/get';
    const API_GROUP = 'https://api.weixin.qq.com/cgi-bin/groups/getid';
    const API_REMARK = 'https://api.weixin.qq.com/cgi-bin/user/info/updateremark';
    const API_OAUTH_GET = 'https://api.weixin.qq.com/sns/userinfo';
    const API_GET_BLACK_LIST = 'https://api.weixin.qq.com/cgi-bin/tags/members/getblacklist';
    const API_BATCH_BLACK_LIST = 'https://api.weixin.qq.com/cgi-bin/tags/members/batchblacklist';
    const API_BATCH_UNBLACK_LIST = 'https://api.weixin.qq.com/cgi-bin/tags/members/batchunblacklist';

    /**
     * Fetch a user by open id.
     *
     * @param string $openId
     * @param string $lang
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function get($openId, $lang = 'zh_CN')
    {
        $params = [
                   'openid' => $openId,
                   'lang' => $lang,
                  ];

        return $this->parseJSON('get', [self::API_GET, $params]);
    }

    /**
     * Batch get users.
     *
     * @param array  $openIds
     * @param string $lang
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function batchGet(array $openIds, $lang = 'zh_CN')
    {
        $params = [];

        $params['user_list'] = array_map(function ($openId) use ($lang) {
            return [
                    'openid' => $openId,
                    'lang' => $lang,
                    ];
        }, $openIds);

        return $this->parseJSON('json', [self::API_BATCH_GET, $params]);
    }

    /**
     * List users.
     *
     * @param string $nextOpenId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function lists($nextOpenId = null)
    {
        $params = ['next_openid' => $nextOpenId];

        return $this->parseJSON('get', [self::API_LIST, $params]);
    }

    /**
     * Set user remark.
     *
     * @param string $openId
     * @param string $remark
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function remark($openId, $remark)
    {
        $params = [
                   'openid' => $openId,
                   'remark' => $remark,
                  ];

        return $this->parseJSON('json', [self::API_REMARK, $params]);
    }

    /**
     * Get user's group id.
     *
     * @param string $openId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function group($openId)
    {
        return $this->getGroup($openId);
    }

    /**
     * Get user's group.
     *
     * @param string $openId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function getGroup($openId)
    {
        $params = ['openid' => $openId];

        return $this->parseJSON('json', [self::API_GROUP, $params]);
    }

    /**
     * Get black list.
     *
     * @param string|null $beginOpenid
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function blacklist($beginOpenid = null)
    {
        $params = ['begin_openid' => $beginOpenid];

        return $this->parseJSON('json', [self::API_GET_BLACK_LIST, $params]);
    }

    /**
     * Batch block user.
     *
     * @param array $openidList
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function batchBlock(array $openidList)
    {
        $params = ['openid_list' => $openidList];

        return $this->parseJSON('json', [self::API_BATCH_BLACK_LIST, $params]);
    }

    /**
     * Batch unblock user.
     *
     * @param array $openidList
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function batchUnblock(array $openidList)
    {
        $params = ['openid_list' => $openidList];

        return $this->parseJSON('json', [self::API_BATCH_UNBLACK_LIST, $params]);
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: lvinkim
 * Date: 23/09/2018
 * Time: 7:10 AM
 */

namespace Lvinkim\SwimKernel\Utility;

use HaydenPierce\ClassFinder\ClassFinder;

class DirectoryScanner
{

    /**
     * @param $directory
     * @param $namespace
     * @return array
     */
    public static function getClassesRecursion($directory, $namespace)
    {
        try {
            $classes = ClassFinder::getClassesInNamespace($namespace);

            $subDirectories = DirectoryScanner::scanChildNamespaces($directory);
            foreach ($subDirectories as $subDirectory) {
                $subClasses = ClassFinder::getClassesInNamespace($namespace . $subDirectory);
                $classes = array_merge($classes, $subClasses);
            }
        } catch (\Exception $exception) {
            $classes = [];
        }

        return $classes;
    }

    /**
     * 获取目录下的所有子命名空间
     * @param $directory
     * @param string $root
     * @return array
     */
    public static function scanChildNamespaces($directory, $root = "")
    {
        $allChildDirectories = [];
        if (is_dir($directory)) {

            $childFiles = scandir($directory);

            foreach ($childFiles as $childFile) {
                if ($childFile != '.' && $childFile != '..') {
                    $childDirectoryFullPath = $directory . DIRECTORY_SEPARATOR . $childFile;
                    if (is_dir($childDirectoryFullPath)) {

                        $childDirectory = $root . "\\" . $childFile;
                        $allChildDirectories[] = $childDirectory;

                        $childDirectories = self::scanChildNamespaces($childDirectoryFullPath, $childDirectory);
                        $allChildDirectories = array_merge($allChildDirectories, $childDirectories);

                    }
                }
            }
        }

        return $allChildDirectories;
    }

}


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

namespace RedKiteCms\Core\RedKiteCms\Core\Form\PageCollection;

use RedKiteCms\Bridge\Form\BaseType;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * Class SeoType is the object deputed to handle the seo values
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Core\RedKiteCms\Core\Form\Page
 */
class SeoType extends BaseType
{
    /**
     * Builds the form
     *
     * @see FormTypeExtensionInterface::buildForm()
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);

        $builder->add(
            'permalink',
            null,
            array(
                'attr' => array(
                    'data-bind' => 'value: permalink, event: {change: $root.editSeo}',
                    'class' => 'form-control input-sm',
                ),
            )
        );
        $builder->add(
            'title',
            'textarea',
            array(
                'attr' => array(
                    'data-bind' => 'value: title, event: {change: $root.editSeo}',
                    'class' => 'form-control input-sm',
                    'rows' => '3',
                ),
            )
        );
        $builder->add(
            'description',
            'textarea',
            array(
                'attr' => array(
                    'data-bind' => 'value: description, event: {change: $root.editSeo}',
                    'class' => 'form-control input-sm',
                    'rows' => '3',
                ),
            )
        );
        $builder->add(
            'keywords',
            'textarea',
            array(
                'attr' => array(
                    'data-bind' => 'value: keywords, event: {change: $root.editSeo}',
                    'class' => 'form-control input-sm',
                    'rows' => '3',
                ),
            )
        );
        $builder->add(
            'sitemap_frequency',
            'choice',
            array(
                'label' => 'Frequency',
                'choices' => array(
                    'always' => 'always',
                    'hourly' => 'hourly',
                    'daily' => 'daily',
                    'weekly' => 'weekly',
                    'monthly' => 'monthly',
                    'yearly' => 'yearly',
                    'never' => 'never',
                ),
                'attr' => array(
                    'data-bind' => 'value: sitemapFrequency, event: {change: $root.editSeo}',
                    'class' => 'form-control input-sm',
                ),
            )
        );
        $builder->add(
            'sitemap_priority',
            'choice',
            array(
                'label' => 'Priority',
                'choices' => array(
                    '0,0' => '0,0',
                    '0,1' => '0,1',
                    '0,2' => '0,2',
                    '0,3' => '0,3',
                    '0,4' => '0,4',
                    '0,5' => '0,5',
                    '0,6' => '0,6',
                    '0,7' => '0,7',
                    '0,8' => '0,8',
                    '0,9' => '0,9',
                    '1' => '1',
                ),
                'attr' => array(
                    'data-bind' => 'value: sitemapPriority, event: {change: $root.editSeo}',
                    'class' => 'form-control input-sm',
                ),
            )
        );
    }
}


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

namespace RedKiteCms\Bridge\Security;

use RedKiteCms\Configuration\ConfigurationHandler;
use RedKiteCms\Configuration\SiteMatcher;
use RedKiteCms\Tools\FilesystemTools;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;

/**
 * This object is assigned to implement the RedKite CMS user provider
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Bridge\Security
 */
class UserProvider implements UserProviderInterface
{
    /**
     * @var ConfigurationHandler
     */
    private $configurationHandler;

    /**
     * Constructor
     *
     * @param $rootDir
     * @param $siteName
     */
    public function __construct(ConfigurationHandler $configurationHandler)
    {
        $this->configurationHandler = $configurationHandler;
    }

    /**
     * {@inheritdoc}
     */
    public function refreshUser(UserInterface $user)
    {
        if (!$user instanceof User) {
            throw new UnsupportedUserException(
                sprintf('Instances of "%s" are not supported.', get_class($user))
            );
        }

        return $this->loadUserByUsername($user->getUsername());
    }

    /**
     * {@inheritdoc}
     */
    public function loadUserByUsername($username)
    {
        $json = FilesystemTools::readFile(sprintf('%s/users/users.json', $this->configurationHandler->siteDir()));
        $users = json_decode($json, true);

        if (array_key_exists($username, $users)) {
            $userData = $users[$username];

            return new User($username, $userData["password"], $userData["salt"], $userData["roles"]);
        }

        throw new UsernameNotFoundException(
            sprintf('Username "%s" does not exist.', $username)
        );
    }

    /**
     * {@inheritdoc}
     *
     * @codeCoverageIgnore
     */
    public function supportsClass($class)
    {
        return $class === 'Symfony\Component\Security\Core\User\User';
    }
}


<?php
/**
 * (c) Joffrey Demetz <joffrey.demetz@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace JDZ\Tree;

/**
 * Tree group base
 *
 * @author Joffrey Demetz <joffrey.demetz@gmail.com>
 */
abstract class TreeGroup
{
  use \JDZ\Utilities\Traits\Get,
      \JDZ\Utilities\Traits\Set;

   /**
   * Is it a valid group
   *
   * @var    bool
   */
  protected $valid;

  /**
   * Group value
   *
   * @var    mixed
   */
  protected $value;

  /**
   * Group label
   *
   * @var    string
   */
  protected $text;

  /**
   * Children groups
   *
   * @var    array
   */
  protected $groups;

  /**
   * Children items
   *
   * @var    array
   */
  protected $items;

  /**
   * Constructor
   *
   * @param   array    $properties     Key/Value pairs
   */
  public function __construct(array $properties=[])
  {
    if ( !empty($properties) ){
      $this->setProperties($properties);
    }

    if ( !isset($this->value) ){
      $this->value = null;
    }

    if ( !isset($this->text) ){
      $this->text = null;
    }

    $this->valid  = false;
    $this->type   = 'group';
    $this->groups = [];
    $this->items  = [];

    $this->load();
  }

  /**
   * Checks if the group is valid.
   *
   * Checks if group contains children categories or pages.
   *
   * @return   bool
   */
  public function isValid()
  {
    return ( $this->valid === true );
  }

  /**
   * Export group to an object
   *
   * @return   object
   */
  public function toObject()
  {
    $groups = $this->groups;
    foreach($groups as &$group){
      $group = $group->toObject();
    }

    $items = $this->items;
    foreach($items as &$item){
      $item = $item->toObject();
    }

    return (object)[
      'type'   => $this->type,
      'value'  => $this->value,
      'text'   => $this->text,
      'groups' => $groups,
      'items'  => $items,
    ];
  }

  /**
   * Export group infos for an optgrouped select
   *
   * @return   void
   */
  public function toSelect(array &$optgroups=[], $level=1, $root=true)
  {
    $options = [];
    foreach($this->items as $item){
      $options[] = $item->toSelect();
    }

    if ( $root === true ){
      $text = $this->text;
    }
    else {
      $text = '|'.str_repeat('-', $level).' '.$this->text;
    }

    $optgroups[] = [
      'text' => $text,
      'options' => $options,
    ];

    foreach($this->groups as $group){
      $group->toSelect($optgroups, $level+1, false);
    }
  }

  /**
   * Load group
   *
   * @return   void
   */
  abstract protected function load();
}


<?php

namespace C33s\ContactFormBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('c33s_contact_form');

        $rootNode
	    ->children()
		->arrayNode('email')
		    ->canBeEnabled()
		    ->children()
			->scalarNode('subject')
			    ->isRequired()
			    ->cannotBeEmpty()
			->end()
			->scalarNode('sender_email')
			    ->isRequired()
			    ->cannotBeEmpty()
			->end()
			->arrayNode('recipients')
			    ->defaultValue(array())
			    ->useAttributeAsKey('email')
			    ->prototype('scalar')
				->isRequired()
				->cannotBeEmpty()
			    ->end()
			->end()
			->booleanNode('send_copy_to_user')
			    ->defaultValue(false)
			->end()
		    ->end()
		->end()
		->arrayNode('database')
		    ->canBeEnabled()
		->end()
	    ->end()
	;

        return $treeBuilder;
    }
}


<?php

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

namespace Temp\MetaReader;

use Temp\MetaReader\Value\MetaValue;
use Temp\MetaReader\Value\ValueBag;

/**
 * Zip extension reader.
 *
 * @author Stephan Wentz <stephan@wentz.it>
 */
class ZipExtensionReader implements ReaderInterface
{
    /**
     * {@inheritdoc}
     */
    public function available()
    {
        return extension_loaded('zip');
    }

    /**
     * {@inheritdoc}
     */
    public function supports($filename)
    {
        $zip = new \ZipArchive();

        return $zip->open($filename) === true;
    }

    /**
     * {@inheritdoc}
     */
    public function read($filename)
    {
        $meta = new ValueBag();

        try {
            $zip = new \ZipArchive();
            $result = $zip->open($filename);

            if ($result === true) {
                if ($zip->comment) {
                    $meta->set('zip.comment', new MetaValue($zip->comment));
                }

                if ($zip->numFiles) {
                    $meta->set('zip.numFiles', new MetaValue($zip->numFiles));
                }

                if ($zip->status) {
                    $meta->set('zip.status', new MetaValue($zip->status));
                }

                $zip->close();
            }
        } catch (\Exception $e) {
        }

        return $meta;
    }
}


<?php declare(strict_types=1);
/**
 * The application's front controller
 *
 * PHP version 7.0
 *
 * @category   CodeCollab
 * @package    Router
 * @author     Pieter Hordijk <info@pieterhordijk.com>
 * @copyright  Copyright (c) 2015 Pieter Hordijk <https://github.com/PeeHaa>
 * @license    See the LICENSE file
 * @version    1.0.0
 */
namespace CodeCollab\Router;

use CodeCollab\Http\Response\Response;
use CodeCollab\Http\Session\Session;
use CodeCollab\Http\Request\Request;
use FastRoute\Dispatcher;

/**
 * The application's front controller
 *
 * @category   CodeCollab
 * @package    Router
 * @author     Pieter Hordijk <info@pieterhordijk.com>
 */
class FrontController
{
    /**
     * @var \CodeCollab\Router\Router The router
     */
    private $router;

    /**
     * @var \CodeCollab\Http\Response\Response The HTTP response
     */
    private $response;

    /**
     * @var \CodeCollab\Http\Session\Session The session handler
     */
    private $session;

    /**
     * @var \CodeCollab\Router\Injector The DI injector
     */
    private $injector;

    /**
     * Creates instance
     *
     * @param \CodeCollab\Router\Router          $router   The router
     * @param \CodeCollab\Http\Response\Response $response The HTTP response
     * @param \CodeCollab\Http\Session\Session   $session  The session handler
     * @param \CodeCollab\Router\Injector        $injector The DI injector
     */
    public function __construct(Router $router, Response $response, Session $session, Injector $injector)
    {
        $this->router   = $router;
        $this->response = $response;
        $this->session  = $session;
        $this->injector = $injector;
    }

    /**
     * Runs the application
     *
     * This method gets the correct route for the current request and runs the callback of the route
     *
     * @param \CodeCollab\Http\Request\Request $request The current request
     */
    public function run(Request $request)
    {
        $dispatcher = $this->router->getDispatcher();
        $routeInfo  = $dispatcher->dispatch($request->server('REQUEST_METHOD'), $request->server('REQUEST_URI_PATH'));

        switch ($routeInfo[0]) {
            case Dispatcher::NOT_FOUND:
                $routeInfo = $this->getNotFoundRoute($dispatcher);
                break;

            case Dispatcher::METHOD_NOT_ALLOWED:
                $routeInfo = $this->runMethodNotAllowed($dispatcher);
                break;

            case Dispatcher::FOUND:
                break;
        }

        $response = $this->runRoute($routeInfo);

        $response->send();
    }

    /**
     * Runs a route
     *
     * @param array $routeInfo The info of the active route
     *
     * @return \CodeCollab\Http\Response\Response The HTTP response
     *
     * @throws \CodeCollab\Router\ControllerNotFoundException When trying to instantiate a non existent controller
     * @throws \CodeCollab\Router\ActionNotFoundException When trying to call a non existent action
     */
    private function runRoute(array $routeInfo): Response
    {
        /** @noinspection PhpUnusedLocalVariableInspection */
        list($_, $callback, $vars) = $routeInfo;

        $vars = array_filter($vars, function($var) {
            return strpos($var, '_') !== 0;
        }, ARRAY_FILTER_USE_KEY);

        if (!class_exists($callback[0])) {
            throw new ControllerNotFoundException(
                'Trying to instantiate a non existent controller (`' . $callback[0] . '`)'
            );
        }

        $controller = new $callback[0]($this->response, $this->session);

        if (!method_exists($controller, $callback[1])) {
            throw new ActionNotFoundException(
                'Trying to call a non existent action (`' . $callback[0] . '::' . $callback[1] . '`)'
            );
        }

        return $this->injector->execute([$controller, $callback[1]], array_map('urldecode', $vars));
    }

    /**
     * Gets the "not found (404)" route
     *
     * @param \FastRoute\Dispatcher $dispatcher The request dispatcher
     *
     * @return array The route
     */
    private function getNotFoundRoute(Dispatcher $dispatcher): array
    {
        return $dispatcher->dispatch('GET', '/not-found');
    }

    /**
     * Gets the "method not allowed (405)" route
     *
     * @param \FastRoute\Dispatcher $dispatcher The request dispatcher
     *
     * @return array The route
     */
    private function runMethodNotAllowed(Dispatcher $dispatcher): array
    {
        return $dispatcher->dispatch('GET', '/method-not-allowed');
    }
}


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

namespace cascade\components\web\widgets\section;

use canis\helpers\ArrayHelper;
use canis\helpers\Html;
use Yii;

/**
 * Section [[@doctodo class_description:cascade\components\web\widgets\section\Section]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class Section extends \cascade\components\web\widgets\Widget
{
    /**
     * @inheritdoc
     */
    public $gridClass = 'canis\web\grid\Grid';
    /**
     * @var [[@doctodo var_type:defaultWidgetDecoratorClass]] [[@doctodo var_description:defaultWidgetDecoratorClass]]
     */
    public $defaultWidgetDecoratorClass = 'cascade\components\web\widgets\decorator\PanelDecorator';
    /**
     * @inheritdoc
     */
    public $section;

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
        if (isset($this->section)) {
            $this->icon = $this->section->icon;
            $this->title = $this->section->sectionTitle;
        }
        if (isset($this->collectorItem)) {
            $this->collectorItem->registerMultiple($this, $this->defaultItems());
        }
    }

    /**
     * Get widget decorator class.
     *
     * @return [[@doctodo return_type:getWidgetDecoratorClass]] [[@doctodo return_description:getWidgetDecoratorClass]]
     */
    public function getWidgetDecoratorClass()
    {
        return $this->defaultWidgetDecoratorClass;
    }

    /**
     * [[@doctodo method_description:generateStart]].
     *
     * @return [[@doctodo return_type:generateStart]] [[@doctodo return_description:generateStart]]
     */
    public function generateStart()
    {
        $parts = [];
        $parts[] = Html::tag('div', '', ['id' => 'section-' . $this->systemId, 'class' => 'scroll-mark']);
        $parts[] = parent::generateStart();

        return implode('', $parts);
    }

    /**
     * [[@doctodo method_description:widgetCellSettings]].
     *
     * @return [[@doctodo return_type:widgetCellSettings]] [[@doctodo return_description:widgetCellSettings]]
     */
    public function widgetCellSettings()
    {
        return [
            'mediumDesktopColumns' => 12,
            'tabletColumns' => 12,
            'baseSize' => 'tablet',
        ];
    }

    /**
     * @inheritdoc
     */
    public function generateContent()
    {
        $items = [];
        foreach ($this->widgets as $widget) {
            $cell = Yii::$app->collectors['widgets']->build($this, $widget->object);
            if (!$cell) {
                \d($widget);
                exit;
                continue;
            }
            $items[] = $cell;
            Yii::configure($cell, $this->widgetCellSettings());
        }
        $grid = Yii::createObject(['class' => $this->gridClass, 'cells' => $items]);

        return $grid->generate();
    }

    /**
     * Get widgets.
     *
     * @return [[@doctodo return_type:getWidgets]] [[@doctodo return_description:getWidgets]]
     */
    public function getWidgets()
    {
        $widgets = $this->collectorItem->getAll();
        ArrayHelper::multisort($widgets, ['object.priority', 'object.name'], [SORT_ASC, SORT_ASC]);

        return $widgets;
    }

    /**
     * [[@doctodo method_description:defaultItems]].
     *
     * @param [[@doctodo param_type:parent]] $parent [[@doctodo param_description:parent]] [optional]
     *
     * @return [[@doctodo return_type:defaultItems]] [[@doctodo return_description:defaultItems]]
     */
    public function defaultItems($parent = null)
    {
        return [];
    }
}


<?php

namespace Cpwc\Lta\Api;

use Cpwc\Lta\Client;
use Cpwc\Lta\HttpClient\Message\ResponseMediator;

/**
 * Abstract class for Api classes.
 *
 * @author Poh Wei Cheng <calvinpohwc@gmail.com>
 */
abstract class AbstractApi implements ApiInterface
{
    /**
     * The client.
     *
     * @var Client
     */
    protected $client;

    /**
     * @param Client $client
     */
    public function __construct(Client $client)
    {
        $this->client = $client;
    }

    public function configure()
    {
    }

    /**
     * Send a GET request with query parameters.
     *
     * @param string $path           Request path.
     * @param array  $parameters     GET parameters.
     * @param array  $requestHeaders Request Headers.
     *
     * @return \Guzzle\Http\EntityBodyInterface|mixed|string
     */
    protected function get($path, array $parameters = array(), $requestHeaders = array())
    {
        if (array_key_exists('ref', $parameters) && is_null($parameters['ref'])) {
            unset($parameters['ref']);
        }
        $response = $this->client->getHttpClient()->get($path, $parameters, $requestHeaders);

        return ResponseMediator::getContent($response);
    }

    /**
     * Send a HEAD request with query parameters.
     *
     * @param string $path           Request path.
     * @param array  $parameters     HEAD parameters.
     * @param array  $requestHeaders Request headers.
     *
     * @return \Guzzle\Http\Message\Response
     */
    protected function head($path, array $parameters = array(), $requestHeaders = array())
    {
        if (array_key_exists('ref', $parameters) && is_null($parameters['ref'])) {
            unset($parameters['ref']);
        }

        $response = $this->client->getHttpClient()->request($path, null, 'HEAD', $requestHeaders, array(
            'query' => $parameters
        ));

        return $response;
    }

    /**
     * Send a POST request with JSON-encoded parameters.
     *
     * @param string $path           Request path.
     * @param array  $parameters     POST parameters to be JSON encoded.
     * @param array  $requestHeaders Request headers.
     */
    protected function post($path, array $parameters = array(), $requestHeaders = array())
    {
        return $this->postRaw(
            $path,
            $this->createJsonBody($parameters),
            $requestHeaders
        );
    }

    /**
     * Send a POST request with raw data.
     *
     * @param string $path                     Request path.
     * @param        $body                     Request body.
     * @param array  $requestHeaders           Request headers.
     *
     * @return \Guzzle\Http\EntityBodyInterface|mixed|string
     */
    protected function postRaw($path, $body, $requestHeaders = array())
    {
        $response = $this->client->getHttpClient()->post(
            $path,
            $body,
            $requestHeaders
        );

        return ResponseMediator::getContent($response);
    }

    /**
     * Send a PATCH request with JSON-encoded parameters.
     *
     * @param string $path           Request path.
     * @param array  $parameters     POST parameters to be JSON encoded.
     * @param array  $requestHeaders Request headers.
     */
    protected function patch($path, array $parameters = array(), $requestHeaders = array())
    {
        $response = $this->client->getHttpClient()->patch(
            $path,
            $this->createJsonBody($parameters),
            $requestHeaders
        );

        return ResponseMediator::getContent($response);
    }

    /**
     * Send a PUT request with JSON-encoded parameters.
     *
     * @param string $path           Request path.
     * @param array  $parameters     POST parameters to be JSON encoded.
     * @param array  $requestHeaders Request headers.
     */
    protected function put($path, array $parameters = array(), $requestHeaders = array())
    {
        $response = $this->client->getHttpClient()->put(
            $path,
            $this->createJsonBody($parameters),
            $requestHeaders
        );

        return ResponseMediator::getContent($response);
    }

    /**
     * Send a DELETE request with JSON-encoded parameters.
     *
     * @param string $path           Request path.
     * @param array  $parameters     POST parameters to be JSON encoded.
     * @param array  $requestHeaders Request headers.
     */
    protected function delete($path, array $parameters = array(), $requestHeaders = array())
    {
        $response = $this->client->getHttpClient()->delete(
            $path,
            $this->createJsonBody($parameters),
            $requestHeaders
        );

        return ResponseMediator::getContent($response);
    }

    /**
     * Create a JSON encoded version of an array of parameters.
     *
     * @param array $parameters Request parameters
     *
     * @return null|string
     */
    protected function createJsonBody(array $parameters)
    {
        return (count($parameters) === 0) ? null : json_encode($parameters, empty($parameters) ? JSON_FORCE_OBJECT : 0);
    }
}


<?php

declare(strict_types=1);

namespace Ruwork\SynchronizerBundle\DependencyInjection;

use Doctrine\Bundle\DoctrineBundle\DoctrineBundle;
use Ruwork\Synchronizer\Event\Doctrine\FlushListener;
use Ruwork\Synchronizer\Type\TypeInterface;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;

final class RuworkSynchronizerExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        (new PhpFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')))
            ->load('services.php');

        $container->registerForAutoconfiguration(TypeInterface::class)
            ->setPublic(false)
            ->addTag('ruwork_synchronizer.synchronization_type');

        if (!class_exists(DoctrineBundle::class)) {
            $container->removeDefinition(FlushListener::class);
        }
    }
}


<?php

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

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

namespace EasyWeChat\Semantic;

use EasyWeChat\Core\AbstractAPI;

/**
 * Class Semantic.
 */
class Semantic extends AbstractAPI
{
    const API_SEARCH = 'https://api.weixin.qq.com/semantic/semproxy/search';

    /**
     * Get the semantic content of giving string.
     *
     * @param string       $keyword
     * @param array|string $categories
     * @param array        $other
     *
     * @return array
     */
    public function query($keyword, $categories, array $other = [])
    {
        $params = [
                   'query' => $keyword,
                   'category' => implode(',', (array) $categories),
                   'appid' => $this->getAccessToken()->getAppId(),
                  ];

        return $this->parseJSON('json', [self::API_SEARCH, array_merge($params, $other)]);
    }
}


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

namespace RedKiteCms\Bridge\Translation\Loader;

use Symfony\Component\Finder\Finder;
use Symfony\Component\Translation\Loader\XliffFileLoader;
use Symfony\Component\Translation\Translator;

/**
 * This object extends the XliffFileLoader object to register RedKite CMS translation resources
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Bridge\Translation
 */
class TranslationLoader extends XliffFileLoader
{
    /**
     * Register the translation resources read from the given folders
     *
     * @param Translator $translator
     * @param array               $dirs
     */
    public function registerResources(Translator $translator, array $dirs)
    {
        $finder = new Finder();
        $files = $finder->files()->depth(0)->ignoreUnreadableDirs()->in($dirs);
        foreach ($files as $file) {
            $file = (string)$file;
            preg_match_all('/[^.]+/', basename($file), $match);

            $translator->addResource('xliff', $file, $match[0][1], "RedKiteCms");
        }
    }
}


<?php
namespace eMacros\Runtime\HTML;

use eMacros\Applicable;
use eMacros\Scope;
use eMacros\GenericList;
use eMacros\Symbol;

class ParseString implements Applicable {
	/**
	 * Parses an input string
	 * Usage: (HTML::parse-string "first=value&arr[]=foo+bar&arr[]=baz" _output)
	 * Returns: NULL
	 * (non-PHPdoc)
	 * @see \eMacros\Applicable::apply()
	 */
	public function apply(Scope $scope, GenericList $arguments) {
		if (count($arguments) == 0) throw new \BadFunctionCallException("ParseString: No parameters found.");
		$arr = [];
		parse_str($arguments[0]->evaluate($scope), $arr);
		return $arr;
	}
}
?>


<?php

namespace Dothiv\Bundle\ContentfulBundle\Output;

use Dothiv\Bundle\ContentfulBundle\Adapter\ContentfulContentAdapter;
use Dothiv\Bundle\ContentfulBundle\Exception\InvalidArgumentException;
use Dothiv\Bundle\ContentfulBundle\Item\ContentfulEntry;

class Content implements ContentInterface
{

    /**
     * @var ContentfulContentAdapter
     */
    private $contentAdapter;

    /**
     * @var ViewBuilder
     */
    private $viewBuilder;

    /**
     * @var string
     */
    private $spaceId;

    /**
     * @param ContentfulContentAdapter $contentAdapter
     * @param ViewBuilder              $viewBuilder
     * @param string                   $spaceId
     */
    public function __construct(ContentfulContentAdapter $contentAdapter, ViewBuilder $viewBuilder, $spaceId)
    {
        $this->contentAdapter = $contentAdapter;
        $this->viewBuilder    = $viewBuilder;
        $this->spaceId        = $spaceId;
    }

    /**
     * {@inheritdoc}
     */
    public function buildEntry($contentTypeName, $entryName, $locale)
    {
        /** @var ContentfulEntry $entry */
        $entry = $this->contentAdapter->findByContentTypeNameAndEntryName($this->spaceId, $contentTypeName, $entryName)->getOrCall(
            function () use ($contentTypeName, $entryName) {
                throw new InvalidArgumentException(
                    sprintf(
                        'Failed to find entry named "%s" with content type "%s" in space "%s"!',
                        $entryName,
                        $contentTypeName,
                        $this->spaceId
                    )
                );
            }
        );
        return $this->viewBuilder->buildView($entry, $locale);
    }

    /**
     * {@inheritdoc}
     */
    public function buildEntries($contentTypeName, $locale)
    {
        /** @var ContentfulEntry $entry */
        $entries = $this->contentAdapter->findByContentTypeName($this->spaceId, $contentTypeName);
        $view    = array();
        foreach ($entries as $entry) {
            $view[] = $this->viewBuilder->buildView($entry, $locale);
        }
        return $view;
    }

    /**
     * @return ViewBuilder
     */
    public function getViewBuilder()
    {
        return $this->viewBuilder;
    }

    /**
     * {@inheritdoc}
     */
    public function getSpaceId()
    {
        return $this->spaceId;
    }
}


<?php

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

/**
 * This class manage the Cache by file
 *
 * @category  	lib
 * @package		lib\Cache
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */
class File implements CacheInterface
{
    /**
     * var containe this folder of cache
     *
     * @access private
     * @var    string
     */
    private $_sFolder = '';

    /**
     * constructor
     *
     * @access public
     */
    public function __construct()
    {
        $this->_sFolder = str_replace('bundles'.DIRECTORY_SEPARATOR.'lib'.DIRECTORY_SEPARATOR.'Cache', CACHE_DIR, __DIR__).DIRECTORY_SEPARATOR;
    }

    /**
     * set a value
     *
     * @access public
     * @param  string $sName name of the session
     * @param  mixed $mValue value of this sesion var
     * @param  int $iFlag flags
     * @param  int $iExpire expiration of cache
     * @return \Venus\lib\Cache\File
     */
    public function set(string $sName, $mValue, int $iFlag, int $iExpire)
    {
        file_put_contents($this->_sFolder.$this->_getSubDirectory($sName).md5($sName).'.fil.cac', serialize($mValue));
        return $this;
    }

    /**
     * get a value
     *
     * @access public
     * @param  string $sName name of the session
     * @param  int $iFlags flags
     * @param  int $iTimeout expiration of cache
     * @return mixed
     */
    public function get(string $sName, int &$iFlags = null, int $iTimeout = 0)
    {
        if ($iTimeout > 0 && file_exists($this->_sFolder.$this->_getSubDirectory($sName).md5($sName).'.fil.cac')
            && time() - filemtime($this->_sFolder.$this->_getSubDirectory($sName).md5($sName).'.fil.cac') > $iTimeout) {

            unlink($this->_sFolder.$this->_getSubDirectory($sName).md5($sName).'.fil.cac');
        }

        if (file_exists($this->_sFolder.$this->_getSubDirectory($sName).md5($sName).'.fil.cac')) {

            return unserialize(file_get_contents($this->_sFolder . $this->_getSubDirectory($sName) . md5($sName) . '.fil.cac'));
        } else {

            return false;
        }
    }

    /**
     * delete a value
     *
     * @access public
     * @param  string $sName name of the session
     * @return mixed
     */
    public function delete(string $sName)
    {
        return unlink($this->_sFolder.$this->_getSubDirectory($sName).md5($sName).'.fil.cac');
    }

    /**
     * flush the cache
     *
     * @access public
     * @param  string $sName name of the session
     * @return mixed
     */
    public function flush()
    {
        $this->_removeDirectory($this->_sFolder);
    }

    /**
     *
     *
     * @access public
     * @param  string $sName name of the session
     * @return mixed
     */
    private function _getSubDirectory($sName)
    {
        if (!file_exists($this->_sFolder.substr(md5($sName), 0, 2).DIRECTORY_SEPARATOR.substr(md5($sName), 2, 2))) {

            mkdir($this->_sFolder.substr(md5($sName), 0, 2).DIRECTORY_SEPARATOR.substr(md5($sName), 2, 2), 0777, true);
        }

        return substr(md5($sName), 0, 2).DIRECTORY_SEPARATOR.substr(md5($sName), 2, 2).DIRECTORY_SEPARATOR;
    }

    /**
     * remove a directory recursivly
     *
     * @access private
     * @param  string $sName nom du répertoire
     * @return void
     */
    private function _removeDirectory($sName)
    {
        if ($rDirectory = opendir($sName)) {

            while (($sFile = readdir($rDirectory)) !== false) {

                if ($sFile > '0' && filetype($sName.$sFile) == "file") { unlink($sName.$sFile); } elseif ($sFile > '0' && filetype($sName.$sFile) == "dir") { remove_dir($sName.$sFile."\\"); }
            }

            closedir($rDirectory);
            rmdir($sName);
        }
    }
}