<?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.
 */

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

namespace EasyWeChat\Payment;

use Doctrine\Common\Cache\Cache;
use Doctrine\Common\Cache\FilesystemCache;
use EasyWeChat\Core\AbstractAPI;
use EasyWeChat\Core\Exception;
use EasyWeChat\Support\Collection;
use EasyWeChat\Support\XML;
use Psr\Http\Message\ResponseInterface;

/**
 * Class API.
 */
class API extends AbstractAPI
{
    /**
     * Merchant instance.
     *
     * @var Merchant
     */
    protected $merchant;

    /**
     * Sandbox box mode.
     *
     * @var bool
     */
    protected $sandboxEnabled = false;

    /**
     * Sandbox sign key.
     *
     * @var string
     */
    protected $sandboxSignKey;

    /**
     * Cache.
     *
     * @var Cache
     */
    protected $cache;

    const API_HOST = 'https://api.mch.weixin.qq.com';

    // api
    const API_PAY_ORDER = '/pay/micropay';
    const API_PREPARE_ORDER = '/pay/unifiedorder';
    const API_QUERY = '/pay/orderquery';
    const API_CLOSE = '/pay/closeorder';
    const API_REVERSE = '/secapi/pay/reverse';
    const API_REFUND = '/secapi/pay/refund';
    const API_QUERY_REFUND = '/pay/refundquery';
    const API_DOWNLOAD_BILL = '/pay/downloadbill';
    const API_REPORT = '/payitil/report';

    const API_URL_SHORTEN = 'https://api.mch.weixin.qq.com/tools/shorturl';
    const API_AUTH_CODE_TO_OPENID = 'https://api.mch.weixin.qq.com/tools/authcodetoopenid';
    const API_SANDBOX_SIGN_KEY = 'https://api.mch.weixin.qq.com/sandboxnew/pay/getsignkey';

    // order id types.
    const TRANSACTION_ID = 'transaction_id';
    const OUT_TRADE_NO = 'out_trade_no';
    const OUT_REFUND_NO = 'out_refund_no';
    const REFUND_ID = 'refund_id';

    // bill types.
    const BILL_TYPE_ALL = 'ALL';
    const BILL_TYPE_SUCCESS = 'SUCCESS';
    const BILL_TYPE_REFUND = 'REFUND';
    const BILL_TYPE_REVOKED = 'REVOKED';

    /**
     * API constructor.
     *
     * @param \EasyWeChat\Payment\Merchant   $merchant
     * @param \EasyWeChat\Payment\Cache|null $cache
     */
    public function __construct(Merchant $merchant, Cache $cache = null)
    {
        $this->merchant = $merchant;
        $this->cache = $cache;
    }

    /**
     * Pay the order.
     *
     * @param Order $order
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function pay(Order $order)
    {
        return $this->request($this->wrapApi(self::API_PAY_ORDER), $order->all());
    }

    /**
     * Prepare order to pay.
     *
     * @param Order $order
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function prepare(Order $order)
    {
        $order->notify_url = $order->get('notify_url', $this->merchant->notify_url);
        if (is_null($order->spbill_create_ip)) {
            $order->spbill_create_ip = ($order->trade_type === Order::NATIVE) ? get_server_ip() : get_client_ip();
        }

        return $this->request($this->wrapApi(self::API_PREPARE_ORDER), $order->all());
    }

    /**
     * Query order.
     *
     * @param string $orderNo
     * @param string $type
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function query($orderNo, $type = self::OUT_TRADE_NO)
    {
        $params = [
            $type => $orderNo,
        ];

        return $this->request($this->wrapApi(self::API_QUERY), $params);
    }

    /**
     * Query order by transaction_id.
     *
     * @param string $transactionId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function queryByTransactionId($transactionId)
    {
        return $this->query($transactionId, self::TRANSACTION_ID);
    }

    /**
     * Close order by out_trade_no.
     *
     * @param $tradeNo
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function close($tradeNo)
    {
        $params = [
            'out_trade_no' => $tradeNo,
        ];

        return $this->request($this->wrapApi(self::API_CLOSE), $params);
    }

    /**
     * Reverse order.
     *
     * @param string $orderNo
     * @param string $type
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function reverse($orderNo, $type = self::OUT_TRADE_NO)
    {
        $params = [
            $type => $orderNo,
        ];

        return $this->safeRequest($this->wrapApi(self::API_REVERSE), $params);
    }

    /**
     * Reverse order by transaction_id.
     *
     * @param int $transactionId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function reverseByTransactionId($transactionId)
    {
        return $this->reverse($transactionId, self::TRANSACTION_ID);
    }

    /**
     * Make a refund request.
     *
     * @param string $orderNo
     * @param string $refundNo
     * @param float  $totalFee
     * @param float  $refundFee
     * @param string $opUserId
     * @param string $type
     * @param string $refundAccount
     * @param string $refundReason
     *
     * @return Collection
     */
    public function refund(
        $orderNo,
        $refundNo,
        $totalFee,
        $refundFee = null,
        $opUserId = null,
        $type = self::OUT_TRADE_NO,
        $refundAccount = 'REFUND_SOURCE_UNSETTLED_FUNDS',
        $refundReason = ''
        ) {
        $params = [
            $type => $orderNo,
            'out_refund_no' => $refundNo,
            'total_fee' => $totalFee,
            'refund_fee' => $refundFee ?: $totalFee,
            'refund_fee_type' => $this->merchant->fee_type,
            'refund_account' => $refundAccount,
            'refund_desc' => $refundReason,
            'op_user_id' => $opUserId ?: $this->merchant->merchant_id,
        ];

        return $this->safeRequest($this->wrapApi(self::API_REFUND), $params);
    }

    /**
     * Refund by transaction id.
     *
     * @param string $orderNo
     * @param string $refundNo
     * @param float  $totalFee
     * @param float  $refundFee
     * @param string $opUserId
     * @param string $refundAccount
     * @param string $refundReason
     *
     * @return Collection
     */
    public function refundByTransactionId(
        $orderNo,
        $refundNo,
        $totalFee,
        $refundFee = null,
        $opUserId = null,
        $refundAccount = 'REFUND_SOURCE_UNSETTLED_FUNDS',
        $refundReason = ''
        ) {
        return $this->refund($orderNo, $refundNo, $totalFee, $refundFee, $opUserId, self::TRANSACTION_ID, $refundAccount, $refundReason);
    }

    /**
     * Query refund status.
     *
     * @param string $orderNo
     * @param string $type
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function queryRefund($orderNo, $type = self::OUT_TRADE_NO)
    {
        $params = [
            $type => $orderNo,
        ];

        return $this->request($this->wrapApi(self::API_QUERY_REFUND), $params);
    }

    /**
     * Query refund status by out_refund_no.
     *
     * @param string $refundNo
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function queryRefundByRefundNo($refundNo)
    {
        return $this->queryRefund($refundNo, self::OUT_REFUND_NO);
    }

    /**
     * Query refund status by transaction_id.
     *
     * @param string $transactionId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function queryRefundByTransactionId($transactionId)
    {
        return $this->queryRefund($transactionId, self::TRANSACTION_ID);
    }

    /**
     * Query refund status by refund_id.
     *
     * @param string $refundId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function queryRefundByRefundId($refundId)
    {
        return $this->queryRefund($refundId, self::REFUND_ID);
    }

    /**
     * Download bill history as a table file.
     *
     * @param string $date
     * @param string $type
     *
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function downloadBill($date, $type = self::BILL_TYPE_ALL)
    {
        $params = [
            'bill_date' => $date,
            'bill_type' => $type,
        ];

        return $this->request($this->wrapApi(self::API_DOWNLOAD_BILL), $params, 'post', [\GuzzleHttp\RequestOptions::STREAM => true], true)->getBody();
    }

    /**
     * Convert long url to short url.
     *
     * @param string $url
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function urlShorten($url)
    {
        return $this->request(self::API_URL_SHORTEN, ['long_url' => $url]);
    }

    /**
     * Report API status to WeChat.
     *
     * @param string $api
     * @param int    $timeConsuming
     * @param string $resultCode
     * @param string $returnCode
     * @param array  $other         ex: err_code,err_code_des,out_trade_no,user_ip...
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function report($api, $timeConsuming, $resultCode, $returnCode, array $other = [])
    {
        $params = array_merge([
            'interface_url' => $api,
            'execute_time_' => $timeConsuming,
            'return_code' => $returnCode,
            'return_msg' => null,
            'result_code' => $resultCode,
            'user_ip' => get_client_ip(),
            'time' => time(),
        ], $other);

        return $this->request($this->wrapApi(self::API_REPORT), $params);
    }

    /**
     * Get openid by auth code.
     *
     * @param string $authCode
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function authCodeToOpenId($authCode)
    {
        return $this->request(self::API_AUTH_CODE_TO_OPENID, ['auth_code' => $authCode]);
    }

    /**
     * Merchant setter.
     *
     * @param Merchant $merchant
     *
     * @return $this
     */
    public function setMerchant(Merchant $merchant)
    {
        $this->merchant = $merchant;
    }

    /**
     * Merchant getter.
     *
     * @return Merchant
     */
    public function getMerchant()
    {
        return $this->merchant;
    }

    /**
     * Set sandbox mode.
     *
     * @param bool $enabled
     *
     * @return $this
     */
    public function sandboxMode($enabled = false)
    {
        $this->sandboxEnabled = $enabled;

        return $this;
    }

    /**
     * Make a API request.
     *
     * @param string $api
     * @param array  $params
     * @param string $method
     * @param array  $options
     * @param bool   $returnResponse
     *
     * @return \EasyWeChat\Support\Collection|\Psr\Http\Message\ResponseInterface
     */
    protected function request($api, array $params, $method = 'post', array $options = [], $returnResponse = false)
    {
        $params = array_merge($params, $this->merchant->only(['sub_appid', 'sub_mch_id']));

        $params['appid'] = $this->merchant->app_id;
        $params['mch_id'] = $this->merchant->merchant_id;
        $params['device_info'] = $this->merchant->device_info;
        $params['nonce_str'] = uniqid();
        $params = array_filter($params);

        $params['sign'] = generate_sign($params, $this->getSignkey($api), 'md5');

        $options = array_merge([
            'body' => XML::build($params),
        ], $options);

        $response = $this->getHttp()->request($api, $method, $options);

        return $returnResponse ? $response : $this->parseResponse($response);
    }

    /**
     * Return key to sign.
     *
     * @param string $api
     *
     * @return string
     */
    protected function getSignkey($api)
    {
        return $this->sandboxEnabled && $api !== self::API_SANDBOX_SIGN_KEY ? $this->getSandboxSignKey() : $this->merchant->key;
    }

    /**
     * Request with SSL.
     *
     * @param string $api
     * @param array  $params
     * @param string $method
     *
     * @return \EasyWeChat\Support\Collection
     */
    protected function safeRequest($api, array $params, $method = 'post')
    {
        $options = [
            'cert' => $this->merchant->get('cert_path'),
            'ssl_key' => $this->merchant->get('key_path'),
        ];

        return $this->request($api, $params, $method, $options);
    }

    /**
     * Parse Response XML to array.
     *
     * @param ResponseInterface $response
     *
     * @return \EasyWeChat\Support\Collection
     */
    protected function parseResponse($response)
    {
        if ($response instanceof ResponseInterface) {
            $response = $response->getBody();
        }

        return new Collection((array) XML::parse($response));
    }

    /**
     * Wrap API.
     *
     * @param string $resource
     *
     * @return string
     */
    protected function wrapApi($resource)
    {
        return self::API_HOST.($this->sandboxEnabled ? '/sandboxnew' : '').$resource;
    }

    /**
     * Get sandbox sign key.
     *
     * @return string
     */
    protected function getSandboxSignKey()
    {
        if ($this->sandboxSignKey) {
            return $this->sandboxSignKey;
        }

        // Try to get sandbox_signkey from cache
        $cacheKey = 'sandbox_signkey.'.$this->merchant->merchant_id.$this->merchant->sub_merchant_id;

        /** @var \Doctrine\Common\Cache\Cache $cache */
        $cache = $this->getCache();

        $this->sandboxSignKey = $cache->fetch($cacheKey);

        if (!$this->sandboxSignKey) {
            // Try to acquire a new sandbox_signkey from WeChat
            $result = $this->request(self::API_SANDBOX_SIGN_KEY, []);

            if ($result->return_code === 'SUCCESS') {
                $cache->save($cacheKey, $result->sandbox_signkey, 24 * 3600);

                return $this->sandboxSignKey = $result->sandbox_signkey;
            }

            throw new Exception($result->return_msg);
        }

        return $this->sandboxSignKey;
    }

    /**
     * Return the cache manager.
     *
     * @return \Doctrine\Common\Cache\Cache
     */
    public function getCache()
    {
        return $this->cache ?: $this->cache = new FilesystemCache(sys_get_temp_dir());
    }
}


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

namespace cascade\controllers;

use cascade\models\LoginForm;
use cascade\models\Registry;
use canis\web\Controller;
use Yii;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;

/**
 * AppController [[@doctodo class_description:cascade\controllers\AppController]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class AppController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                    [
                        'actions' => ['refresh', 'stream', 'index', 'activity'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                    [
                        'allow' => false,
                        'roles' => ['?'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'refresh' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    /**
     * [[@doctodo method_description:actionIndex]].
     *
     * @return [[@doctodo return_type:actionIndex]] [[@doctodo return_description:actionIndex]]
     */
    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * [[@doctodo method_description:actionLogin]].
     *
     * @return [[@doctodo return_type:actionLogin]] [[@doctodo return_description:actionLogin]]
     */
    public function actionLogin()
    {
        $this->params['model'] = $model = new LoginForm();
        if ($model->load($_POST) && $model->login()) {
            //Yii::$app->response->redirect = Yii::$app->getUser()->getReturnUrl();
            Yii::$app->session->setFlash('delayed-instructions', json_encode(['pauseTimer' => false]));

            return $this->goBack();
        } else {
            Yii::$app->response->task = 'dialog';
            Yii::$app->response->taskOptions = ['title' => 'Log In'];
            Yii::$app->response->view = 'login';
            Yii::$app->response->baseInstructions['pauseTimer'] = true;
        }
    }

    /**
     * [[@doctodo method_description:actionLogout]].
     *
     * @return [[@doctodo return_type:actionLogout]] [[@doctodo return_description:actionLogout]]
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    /**
     * [[@doctodo method_description:actionActivity]].
     */
    public function actionActivity()
    {
        // Yii::$app->response->baseInstructions['timestamp'] = time();
        Yii::$app->response->forceInstructions = true;
        Yii::$app->response->task = 'status';

        $auditClass = Yii::$app->classes['Audit'];
        $provider = $auditClass::activityDataProvider();
        $provider->handleInstructions($_POST);
        if (Yii::$app->request->object) {
            $provider->context = Yii::$app->request->object->primaryKey;
        }
        Yii::$app->response->baseInstructions = $provider->package->toArray();
    }

    /**
     * [[@doctodo method_description:actionRefresh]].
     *
     * @return [[@doctodo return_type:actionRefresh]] [[@doctodo return_description:actionRefresh]]
     */
    public function actionRefresh()
    {
        $refreshed = [];
        Yii::$app->response->baseInstructions['requests'] = &$refreshed;
        Yii::$app->response->forceInstructions = true;
        Yii::$app->response->task = 'status';

        if (empty($_POST['requests'])) {
            return;
        }
        $baseInstrictions = (isset($_POST['baseInstructions']) ? $_POST['baseInstructions'] : []);
        foreach ($_POST['requests'] as $requestId => $request) {
            $refreshed[$requestId] = false;
            $instructions = $baseInstrictions;
            if (isset($request['instructions'])) {
                $instructions = array_merge($instructions, $request['instructions']);
            }
            if (empty($instructions['type']) || empty($instructions['type'])) {
                continue;
            }
            if (isset($request['state'])) {
                foreach ($request['state'] as $key => $value) {
                    Yii::$app->webState->set($key, $value);
                }
            }

            if (isset($instructions['objectId'])) {
                $object = Yii::$app->request->object = Registry::getObject($instructions['objectId']);
                if (!$object) {
                    $refreshed[$requestId] = ['error' => 'Invalid object ' . $instructions['objectId'] . ''];
                    continue;
                }
                $type = $object->objectType;
            }

            $settings = (isset($instructions['settings'])) ? $instructions['settings'] : [];
            switch ($instructions['type']) {
                case 'widget':
                    $widget = false;
                    if (isset($object)) {
                        $widgets = $object->objectTypeItem->widgets;
                        if (isset($widgets[$instructions['systemId']])) {
                            $widget = $widgets[$instructions['systemId']]->object;
                        }
                    } else {
                        $widget = Yii::$app->collectors['widgets']->getOne($instructions['systemId']);
                    }
                    if (!$widget) {
                        $refreshed[$requestId] = ['error' => 'Unknown widget'];

                        return;
                    }
                    $widgetObject = $widget->object;
                    if (isset($instructions['section'])
                        && ($sectionItem = Yii::$app->collectors['sections']->getOne($instructions['section']))
                        && ($section = $sectionItem->object)) {
                        $widgetObject->attachDecorator($section->widgetDecoratorClass);
                        $widgetObject->section = $section;
                    }
                    $widgetObject->owner = $widget->owner;
                    $refreshed[$requestId] = ['content' => $widgetObject->generate()];
                break;
            }
        }
    }

    /**
     * [[@doctodo method_description:actionStream]].
     *
     * @return [[@doctodo return_type:actionStream]] [[@doctodo return_description:actionStream]]
     */
    public function actionStream()
    {
        header("Content-type: text/plain");
        header("Access-Control-Allow-Origin: *");
        ob_implicit_flush(1);

        Yii::$app->response->task = false;
        $refreshed = [];
        $source = $_POST;
        $stream = false;
        if (!empty($source['__TODO_FIGURE_OUT_VIBE_STREAM_HINT__'])) { // @todo figure out this vibe hint thing
            $stream = true;
        }
        if (isset($source['when']) && $source['when'] === 'handshake') {
            echo json_encode(['id' => md5(microtime(true)), 'transports' => ['stream']]);

            return;
        }
        if (empty($source['requests'])) {
            echo json_encode([]);
            return;
        }
        $nonStreamResult = [];
        $baseInstrictions = (isset($source['baseInstructions']) ? $source['baseInstructions'] : []);
        foreach ($source['requests'] as $requestId => $request) {
            $refreshed[$requestId] = false;
            $instructions = $baseInstrictions;
            if (isset($request['instructions'])) {
                $instructions = array_merge($instructions, $request['instructions']);
            }
            if (empty($instructions['type']) || empty($instructions['type'])) {
                continue;
            }
            if (isset($request['state'])) {
                foreach ($request['state'] as $key => $value) {
                    Yii::$app->webState->set($key, $value);
                }
            }

            if (isset($instructions['objectId'])) {
                $object = Yii::$app->request->object = Registry::getObject($instructions['objectId']);
                if (!$object) {
                    $refreshed[$requestId] = ['error' => 'Invalid object ' . $instructions['objectId'] . ''];
                    continue;
                }
                $type = $object->objectType;
            }

            $settings = (isset($instructions['settings'])) ? $instructions['settings'] : [];
            switch ($instructions['type']) {
                case 'widget':
                    $widget = false;
                    if (isset($object)) {
                        $widgets = $object->objectTypeItem->widgets;
                        if (isset($widgets[$instructions['systemId']])) {
                            $widget = $widgets[$instructions['systemId']]->object;
                        }
                    } else {
                        $widget = Yii::$app->collectors['widgets']->getOne($instructions['systemId']);
                    }
                    if (!$widget) {
                        $refreshed[$requestId] = ['error' => 'Unknown widget'];

                        return;
                    }
                    $widgetObject = $widget->object;
                    if (isset($instructions['section'])
                        && ($sectionItem = Yii::$app->collectors['sections']->getOne($instructions['section']))
                        && ($section = $sectionItem->object)) {
                        $widgetObject->attachDecorator($section->widgetDecoratorClass);
                        $widgetObject->section = $section;
                    }
                    $widgetObject->owner = $widget->owner;
                    $refreshed[$requestId] = ['content' => $widgetObject->generate()];
                break;
            }
            if ($refreshed[$requestId]) {
                if ($stream) {
                    echo "data: " . json_encode(['type' => 'handleRequests', 'data' => [$requestId => $refreshed[$requestId]], 'id' => round(microtime(true) * 100)]);
                    echo "\n\n";
                } else {
                    $nonStreamResult[$requestId] = $refreshed[$requestId];
                }
                //echo str_repeat("\n\n",1024*4);
            }
        }
        if (!$stream) {
            echo json_encode(['requests' => $nonStreamResult]);
        }
        ob_implicit_flush(0);
        ob_start();
        Yii::$app->end();
        ob_end_clean();
    }
}


<?php

namespace Weew\Container;

use Weew\Container\Definitions\ValueDefinition;
use Weew\Container\Exceptions\ClassNotFoundException;
use Weew\Container\Exceptions\ImplementationNotFoundException;
use Weew\Container\Exceptions\InvalidCallableFormatException;
use Weew\Container\Exceptions\MissingDefinitionIdentifierException;
use Weew\Container\Exceptions\MissingDefinitionValueException;
use Weew\Container\Exceptions\TypeMismatchException;
use Weew\Container\Exceptions\UnresolveableArgumentException;
use Weew\Container\Exceptions\ValueNotFoundException;

class Container implements IContainer {
    /**
     * @var Reflector
     */
    protected $reflector;

    /**
     * @var Registry
     */
    protected $registry;

    /**
     * @var Resolver
     */
    protected $resolver;

    /**
     * Container constructor.
     *
     * @param bool $strictMode
     */
    public function __construct($strictMode = true) {
        $this->reflector = $this->createReflector();
        $this->registry = $this->createRegistry();
        $this->resolver = $this->createResolver();

        $this->setStrictMode($strictMode);
        $this->shareContainerInstance();
    }

    /**
     * @param string $id
     * @param array $args
     *
     * @return mixed
     * @throws ImplementationNotFoundException
     * @throws TypeMismatchException
     * @throws UnresolveableArgumentException
     * @throws ValueNotFoundException
     */
    public function get($id, array $args = []) {
        return $this->rethrowExceptions(function () use ($id, $args) {
            $value = null;
            $definition =  $this->registry->getDefinition($id);

            if ($definition instanceof IDefinition) {
                $value = $this->resolver->resolveDefinition($definition, $id, $args);
                $this->processSingletonDefinition($definition, $id, $value);
            }

            if ($value === null) {
                return $this->resolver->resolveWithoutDefinition($id, $args);
            }

            return $value;
        });
    }

    /**
     * @param $id
     * @param array $args
     *
     * @return mixed
     * @throws ClassNotFoundException
     * @throws ImplementationNotFoundException
     * @throws ValueNotFoundException
     */
    public function instantiate($id, array $args = []) {
        return $this->rethrowExceptions(function() use ($id, $args) {
            if ( ! class_exists($id)) {
                throw new ClassNotFoundException(s(
                    'Class "%s" not found.', $id
                ));
            }

            return $this->resolver->resolveWithoutDefinition($id, $args);
        });
    }

    /**
     * @param string $id
     * @param $value
     *
     * @return IDefinition
     */
    public function set($id, $value = null) {
        $args = func_get_args();

        return $this->rethrowExceptions(function() use ($args) {
            return call_user_func_array([$this->registry, 'createDefinition'], $args);
        });
    }

    /**
     * @param string $id
     *
     * @return bool
     */
    public function has($id) {
        return $this->registry->hasDefinition($id);
    }

    /**
     * @param string $id
     */
    public function remove($id) {
        $this->registry->removeDefinition($id);
    }

    /**
     * @param $callable
     * @param array $args
     *
     * @return mixed
     */
    public function call($callable, array $args = []) {
        return $this->rethrowExceptions(function () use ($callable, $args) {
            return $this->reflector
                ->resolveCallable($this, $callable, $args);
        });
    }

    /**
     * @param $function
     * @param array $args
     *
     * @return mixed
     * @throws ImplementationNotFoundException
     * @throws TypeMismatchException
     * @throws UnresolveableArgumentException
     * @throws ValueNotFoundException
     */
    public function callFunction($function, array $args = []) {
        return $this->rethrowExceptions(function () use ($function, $args) {
            return $this->reflector
                ->resolveFunction($this, $function, $args);
        });
    }

    /**
     * @param $instance
     * @param $method
     * @param array $args
     *
     * @return mixed
     */
    public function callMethod($instance, $method, array $args = []) {
        return $this->rethrowExceptions(function () use ($instance, $method, $args) {
            return $this->reflector
                ->resolveMethod($this, $instance, $method, $args);
        });
    }

    /**
     * @param $class
     * @param $method
     * @param array $args
     *
     * @return mixed
     */
    public function callStaticMethod($class, $method, array $args = []) {
        return $this->rethrowExceptions(function () use ($class, $method, $args) {
            return $this->reflector
                ->resolveMethod($this, $class, $method, $args);
        });
    }

    /**
     * @param bool $strictMode
     */
    public function setStrictMode($strictMode) {
        $this->resolver->setStrictMode($strictMode);
    }

    /**
     * @return bool
     */
    public function isInStrictMode() {
        return $this->resolver->isInStrictMode();
    }

    /**
     * Rethrow controlled exceptions, those that get thrown by the container
     * or the resolver, to shorten the call stack and make it more readable.
     *
     * @param callable $callable
     *
     * @return mixed
     * @throws ClassNotFoundException
     * @throws ImplementationNotFoundException
     * @throws InvalidCallableFormatException
     * @throws MissingDefinitionIdentifierException
     * @throws MissingDefinitionValueException
     * @throws TypeMismatchException
     * @throws UnresolveableArgumentException
     * @throws ValueNotFoundException
     */
    protected function rethrowExceptions(callable $callable) {
        try {
            return $callable();
        } catch (ImplementationNotFoundException $ex) {
            throw new ImplementationNotFoundException($ex->getMessage());
        } catch (TypeMismatchException $ex) {
            throw new TypeMismatchException($ex->getMessage());
        } catch (UnresolveableArgumentException $ex) {
            throw new UnresolveableArgumentException($ex->getMessage());
        } catch (ValueNotFoundException $ex) {
            throw new ValueNotFoundException($ex->getMessage());
        } catch (InvalidCallableFormatException $ex) {
            throw new InvalidCallableFormatException($ex->getMessage());
        } catch (MissingDefinitionIdentifierException $ex) {
            throw new MissingDefinitionIdentifierException($ex->getMessage());
        } catch (MissingDefinitionValueException $ex) {
            throw new MissingDefinitionValueException($ex->getMessage());
        } catch (ClassNotFoundException $ex) {
            throw new ClassNotFoundException($ex->getMessage());
        }
    }

    /**
     * @param IDefinition $definition
     * @param $id
     * @param $value
     */
    protected function processSingletonDefinition(IDefinition $definition, $id, $value) {
        if ($definition->isSingleton() && ! $definition instanceof ValueDefinition) {
            $newDefinition = new ValueDefinition($id, $value);
            $this->registry->addDefinition($newDefinition);

            foreach ($definition->getAliases() as $alias) {
                $alias->setValue($newDefinition);
            }
        }
    }

    /**
     * @return Reflector
     */
    protected function createReflector() {
        return new Reflector();
    }

    /**
     * @return Registry
     */
    protected function createRegistry() {
        return new Registry();
    }

    /**
     * @return Resolver
     */
    protected function createResolver() {
        return new Resolver($this, $this->reflector);
    }

    /**
     * Put current container instance in the container.
     */
    protected function shareContainerInstance() {
        $this->set([IContainer::class, static::class], $this);
    }
}


<?php declare(strict_types=1);

namespace Ellipse\Middleware;

use Psr\Container\ContainerInterface;

use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

use Ellipse\Middleware\Exceptions\ContainedMiddlewareTypeException;

class ContainerMiddleware implements MiddlewareInterface
{
    /**
     * The container.
     *
     * @var \Psr\Container\ContainerInterface
     */
    private $container;

    /**
     * The container id to use to retrieve the middleware.
     *
     * @var string
     */
    private $middleware;

    /**
     * Set up a container middleware with the given container and container id.
     *
     * @param \Psr\Container\ContainerInterface $container
     * @param string                            $middleware
     */
    public function __construct(ContainerInterface $container, string $middleware)
    {
        $this->container = $container;
        $this->middleware = $middleware;
    }

    /**
     * Get a middleware from the container then proxy its ->process() method.
     *
     * @param \Psr\Http\Message\ServerRequestInterface  $request
     * @param \Psr\Http\Server\RequestHandlerInterface  $handler
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Ellipse\Middleware\Exceptions\ContainedMiddlewareTypeException
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $middleware = $this->container->get($this->middleware);

        if ($middleware instanceof MiddlewareInterface) {

            return $middleware->process($request, $handler);

        }

        throw new ContainedMiddlewareTypeException($this->middleware, $middleware);
    }
}


<?php

namespace PeterColes\Cluster\Contracts;

abstract class Factory
{
    /**
     * The adapter being constructed by the factory
     */
    protected $adapter;

    /**
     * Initialise the adapter, including injecting an http client
     *
     * @param object $adapter
     * @param object $client
     * @return void
     */
    public function init($adapter, $client = null)
    {
        // set the server adapter
        $this->adapter = $adapter;

        // for ease of use we can fallback to a default http client
        if (!$client) {
            $client = new \PeterColes\Cluster\HttpClients\GuzzleHttp;
        }

        // initialise the http client with the authentication header options
        $client->initClient($this->adapter->getHeaders());

        // make the initialised http client available to the adapter
        $this->adapter->setClient($client);
    }
}


<?php

namespace NajiDev\Common\JavaScriptData;

use
	\NajiDev\Common\Exception\ElementNotFoundException,
	\NajiDev\Common\Exception\InvalidArgumentException,
	\NajiDev\Common\Exception\UnsupportedException,
	\NajiDev\Common\Helper\ArrayHelper
;

class Container
{
	protected $data = array();

	/**
	 * Sets the value, if the does not exists yet
	 *
	 * @param $key string
	 * @param $value mixed
	 * @throws InvalidArgumentException
	 * @throws UnsupportedException
	 * @return void
	 */
	public function add($key, $value)
	{
		try
		{
			$this->getRecursive($key, $this->data);
		}
		catch (ElementNotFoundException $e)
		{
			$this->set($key, $value);
		}
	}

	/**
	 * Sets the value, not regarding whether the key does exist yet or it does not
	 *
	 * @param $key string
	 * @param $value mixed
	 * @throws InvalidArgumentException
	 * @throws UnsupportedException
	 * @return void
	 */
	public function set($key, $value)
	{
		if (!is_string($key))
			throw new InvalidArgumentException('First parameter has to be a string');

		if (!$this->isTypeSupported(gettype($value)))
			throw new UnsupportedException('First parameter has to be an int, a double, a bool or a string');

		try
		{
			// try to find the key, and set the value if this succeeds
			$this->getRecursive($key, $this->data);
			$this->data = $this->setRecursive($key, $value);
		}
		catch (ElementNotFoundException $e)
		{
			$this->data = array_merge_recursive($this->data, $this->setRecursive($key, $value));
		}
	}

	/**
	 * Returns the value of $key, if $key exists. Otherwise $defaultValue will be returned
	 *
	 * @param $key string
	 * @param $defaultValue
	 * @return mixed
	 */
	public function get($key, $defaultValue = null)
	{
		try
		{
			return $this->getRecursive($key, $this->data);
		}
		catch (ElementNotFoundException $e)
		{
			return $defaultValue;
		}
	}

	/**
	 * Removes the element with $key. The method does just nothing, if the key does not exist
	 *
	 * @param $key
	 * @return mixed
	 */
	public function remove($key)
	{
		try
		{
			$this->getRecursive($key, $this->data);

			$data = $this->removeRecursive($key, $this->data);
			$this->data = ArrayHelper::array_filter_recursive($data, function ($value)
			{
				return !empty($value);
			});
		}
		catch (ElementNotFoundException $e) { }
	}

	/**
	 * @return string json encoded string
	 */
	public function getTransformedData()
	{
		return json_encode($this->data);
	}

	/**
	 * Returns all stored data
	 *
	 * @return array
	 */
	public function getData()
	{
		return $this->data;
	}

	private function removeRecursive($key, $data)
	{
		$key = explode('.', $key);

		if (1 === count($key))
		{
			unset($data[$key[0]]);
			return $data;
		}

		$first = array_shift($key);
		$data[$first] = $this->removeRecursive(implode('.', $key), $data[$first]);

		return $data;
	}

	private function setRecursive($key, $value)
	{
		$key = explode('.', $key);
		$data = array();

		if (1 === count($key))
			$data[$key[0]] = $value;
		else
		{
			$first = array_shift($key);
			$data[$first] = $this->setRecursive(implode('.', $key), $value);
		}

		return $data;
	}

	private function getRecursive($key, $data)
	{
		$key = explode('.', $key);

		if (1 === count($key))
		{
			if (!array_key_exists($key[0], $data))
				throw new ElementNotFoundException();

			return $data[$key[0]];
		}

		$first = array_shift($key);
		if (!array_key_exists($first, $data))
			throw new ElementNotFoundException;

		return $this->getRecursive(implode('.', $key), $data[$first]);
	}

	protected function isTypeSupported($type)
	{
		if ('string' === $type)
			return true;

		if ('boolean' === $type)
			return true;

		if ('integer' === $type)
			return true;

		if ('double' === $type)
			return true;

		return false;
	}
}


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

namespace cascade\components\web\widgets;

use cascade\components\helpers\StringHelper;
use canis\base\ComponentTrait;
use canis\base\ObjectTrait;
use canis\web\grid\CellContentTrait;
use canis\web\RenderTrait;
use Yii;

/**
 * BaseWidget [[@doctodo class_description:cascade\components\web\widgets\BaseWidget]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
abstract class BaseWidget extends \yii\bootstrap\Widget
{
    use ObjectTrait;
    use ComponentTrait;
    use CellContentTrait;
    use RenderTrait;

    /**
     * @var [[@doctodo var_type:owner]] [[@doctodo var_description:owner]]
     */
    public $owner;
    /**
     * @var [[@doctodo var_type:instanceSettings]] [[@doctodo var_description:instanceSettings]]
     */
    public $instanceSettings;

    /**
     * @var [[@doctodo var_type:defaultDecoratorClass]] [[@doctodo var_description:defaultDecoratorClass]]
     */
    public $defaultDecoratorClass = 'cascade\components\web\widgets\decorator\PanelDecorator';

    /**
     * @var [[@doctodo var_type:params]] [[@doctodo var_description:params]]
     */
    public $params = [];
    /**
     * @var [[@doctodo var_type:htmlOptions]] [[@doctodo var_description:htmlOptions]]
     */
    public $htmlOptions = [];

    /**
     * @var [[@doctodo var_type:_systemId]] [[@doctodo var_description:_systemId]]
     */
    protected $_systemId;
    /**
     * @var [[@doctodo var_type:_settings]] [[@doctodo var_description:_settings]]
     */
    protected $_settings;
    /**
     * @var [[@doctodo var_type:_decorator]] [[@doctodo var_description:_decorator]]
     */
    protected $_decorator;

    /**
     * [[@doctodo method_description:generateContent]].
     */
    abstract public function generateContent();
    /**
     * [[@doctodo method_description:generate]].
     */
    abstract public function generate();

    /**
     * [[@doctodo method_description:ensureDecorator]].
     */
    public function ensureDecorator()
    {
        if (!$this->hasDecorator()) {
            $this->attachDecorator($this->defaultDecoratorClass);
        }
    }

    /**
     * [[@doctodo method_description:hasDecorator]].
     *
     * @return [[@doctodo return_type:hasDecorator]] [[@doctodo return_description:hasDecorator]]
     */
    public function hasDecorator()
    {
        return $this->_decorator !== null;
    }

    /**
     * [[@doctodo method_description:attachDecorator]].
     *
     * @param [[@doctodo param_type:decorator]] $decorator [[@doctodo param_description:decorator]]
     *
     * @return [[@doctodo return_type:attachDecorator]] [[@doctodo return_description:attachDecorator]]
     */
    public function attachDecorator($decorator)
    {
        if ($this->hasDecorator()) {
            $this->detachBehavior('__decorator');
        }

        return $this->_decorator = $this->attachBehavior('__decorator', ['class' => $decorator]);
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'CellBehavior' => [
                'class' => 'cascade\components\web\widgets\base\CellBehavior',
            ],
        ];
    }

    /**
     * [[@doctodo method_description:output]].
     */
    public function output()
    {
        echo $this->generate();
    }

    /**
     * @inheritdoc
     */
    public function run()
    {
        echo $this->generate();
    }

    /**
     * [[@doctodo method_description:parseText]].
     *
     * @param [[@doctodo param_type:text]] $text [[@doctodo param_description:text]]
     *
     * @return [[@doctodo return_type:parseText]] [[@doctodo return_description:parseText]]
     */
    public function parseText($text)
    {
        return StringHelper::parseText($text, $this->variables);
    }

    /**
     * Get variables.
     *
     * @return [[@doctodo return_type:getVariables]] [[@doctodo return_description:getVariables]]
     */
    public function getVariables()
    {
        return [];
    }

    /**
     * Get settings.
     *
     * @return unknown
     */
    public function getSettings()
    {
        return $this->_settings;
    }

    /**
     * Set settings.
     *
     * @param [[@doctodo param_type:settings]] $settings [[@doctodo param_description:settings]]
     */
    public function setSettings($settings)
    {
        $this->_settings = $settings;
    }

    /**
     * Get widget.
     *
     * @return unknown
     */
    public function getWidgetId()
    {
        if (!is_null($this->_widgetId)) {
            return $this->_widgetId;
        }

        return $this->_widgetId = 'ic-widget-' . md5(microtime() . mt_rand());
    }

    /**
     * Set widget.
     *
     * @param [[@doctodo param_type:value]] $value [[@doctodo param_description:value]]
     */
    public function setWidgetId($value)
    {
        $this->_widgetId = $value;
    }

    /**
     * Get system.
     *
     * @return unknown
     */
    public function getSystemId()
    {
        if (!isset($this->_systemId)) {
            if (isset($this->collectorItem) && isset($this->collectorItem->systemId)) {
                $this->_systemId = $this->collectorItem->systemId;
            }
        }

        return $this->_systemId;
    }

    /**
     * Set system.
     *
     * @param [[@doctodo param_type:value]] $value [[@doctodo param_description:value]]
     */
    public function setSystemId($value)
    {
        $this->_systemId = $value;
    }
}


<?php

/*
 * Copyright (c) 2013, Flaming Code
 *
 */

namespace FlamingBase\Form\View\Helper;

use CoreBootstrap\Form\View\Helper\FormRow as BootstrapFormRow;

use Zend\Form\ElementInterface;

/**
 * FormRow
 *
 * Makes translation of form element labels possible.
 * Also makes it possible to use icons for the prepend and append features of Twitter Bootstrap
 *
 * @author Flemming Andersen <flemming@flamingcode.com>
 * @copyright (c) 2013, Flaming Code
 * @link https://github.com/FlamingCode/FlamingBase for the canonical source repository
 * @license http://opensource.org/licenses/MIT MIT
 */
class FormRow extends BootstrapFormRow
{
	/**
	 * This annoying hack is necessary in order to support translation of form element labels
	 *  - The person who made the CoreBootstrap module didn't think about this
	 *
	 * @param ElementInterface $element
	 * @return string
	 */
	public function render(ElementInterface $element)
	{
		$label = $element->getLabel();

		if (isset($label) && '' !== $label) {
			// Translate the label
			if (null !== ($translator = $this->getTranslator())) {
				$label = $translator->translate(
					$label, $this->getTranslatorTextDomain()
				);
				$element->setLabel($label);
			}
		}

		return parent::render($element);
	}

	/**
	 *
	 * @param string $elementString
	 * @param array $options
	 * @return string
	 */
	public function renderBootstrapOptions($elementString, $options)
	{
		$escapeHtmlHelper = $this->getEscapeHtmlHelper();

		if (isset($options['prepend']) || isset($options['append'])) {
			$template = $this->bootstrapTemplates['prependAppend'];
			$class = '';
			$prepend = '';
			$append = '';
			if (isset($options['prepend'])) {
				$class .= 'input-prepend ';
				if (!is_array($options['prepend'])) {
					$options['prepend'] = (array) $options['prepend'];
				}
				foreach ($options['prepend'] as $p) {
					if (is_array($p)) {
						$attrStr = '';
						foreach ($p as $attr => $attrVal)
							$attrStr .= ' ' . $attr . '="' . $attrVal . '"';

						$prepend .= '' . sprintf('', $attrStr) . '';
					} else
						$prepend .= '' . $escapeHtmlHelper($p) . '';
				}
			}
			if (isset($options['append'])) {
				$class .= 'input-append ';
				if (!is_array($options['append'])) {
					$options['append'] = (array) $options['append'];
				}
				foreach ($options['append'] as $a) {
					if (is_array($a)) {
						$attrStr = '';
						foreach ($a as $attr => $attrVal)
							$attrStr .= ' ' . $attr . '="' . $attrVal . '"';

						$append .= '' . sprintf('', $attrStr) . '';
					} else
						$append .= '' . $escapeHtmlHelper($a) . '';
				}
			}

			$elementString = sprintf($template, $class, $prepend, $elementString, $append);
		}
		if (isset($options['help'])) {
			$help = $options['help'];
			$template = $this->bootstrapTemplates['help'];
			$style = 'inline';
			$content = '';
			if (is_array($help)) {
				if (isset($help['style'])) {
					$style = $help['style'];
				}
				if (isset($help['content'])) {
					$content = $help['content'];
					if (null !== ($translator = $this->getTranslator())) {
						$content = $translator->translate(
							$content, $this->getTranslatorTextDomain()
						);
					}
				}
			} else {

				$content = $help;
			}

			$tag = $style == 'block' ? 'p' : 'span';

			$elementString .= sprintf(
				$template, $tag, $style, $content
			);
		}

		return $elementString;
	}
}


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

namespace Controller\Cms;

use RedKiteCms\Rendering\Controller\Cms\FrontendController as BaseFrontendController;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;

/**
 * This object implements the Silex controller to render RedKite CMS frontend
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package Controller\Cms
 */
class FrontendController extends BaseFrontendController
{
    /**
     * Show frontend action
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param \Silex\Application                        $app
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function showAction(Request $request, Application $app)
    {
        $options = $this->options($request, $app);

        return parent::show($options);
    }

    /**
     * Sets the options required by parent class
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param \Silex\Application                        $app
     * @return array
     */
    protected function options(Request $request, Application $app)
    {
        return array(
            "root_dir" => $app["red_kite_cms.root_dir"],
            "request" => $request,
            "twig" => $app["twig"],
            "red_kite_cms_config" => $app["red_kite_cms.configuration_handler"],
            "page" => $app["red_kite_cms.page"],
            "plugin_manager" => $app["red_kite_cms.plugin_manager"],
            "template_assets" => $app["red_kite_cms.template_assets"],
            "page_renderer" => $app["red_kite_cms.page_renderer_production"],
            "username" => null,
        );
    }
}


<?php
namespace eMacros\Runtime\Type;

use eMacros\Runtime\GenericFunction;

class IsEmpty extends GenericFunction {
	/**
	 * Determines if a value evaluates to empty
	 * Usage: (empty value)
	 * Returns: boolean
	 * (non-PHPdoc)
	 * @see \eMacros\Runtime\GenericFunction::execute()
	 */
	public function execute(array $arguments) {
		if (empty($arguments)) throw new \BadFunctionCallException('IsEmpty: No parameters found.');

		foreach ($arguments as $arg) {
			if (!empty($arg)) return false;
		}

		return true;
	}
}
?>


<?php namespace Kharanenka\Helper;

/**
 * Generate universal result answer
 *
 * Class ResultStore
 * @package Kharanenka\Helper
 * @author  Andrey Kharanenka, kharanenka@gmail.com
 */
class ResultStore
{
    /** @var bool Status of result (true|false) */
    private $bStatus = true;

    /** @var mixed Data of result */
    private $obData;

    /** @var string Error message */
    private $sErrorMessage = null;

    /** @var string Error code */
    private $sErrorCode = null;

    /** @var ResultStore */
    private static $obThis = null;

    private function __construct()
    {
    }

    /**
     * @return ResultStore
     */
    public static function getInstance()
    {
        if (empty(self::$obThis)) {
            self::$obThis = new ResultStore();
        }

        return self::$obThis;
    }

    /**
     * Set data value and status of result in true
     * @param mixed $obData
     * @return ResultStore
     */
    public function setData($obData)
    {
        $this->obData = $obData;

        return $this;
    }

    /**
     * Set data value and status of result in true
     * @param mixed $obData
     * @return ResultStore
     */
    public function setTrue($obData = null)
    {
        $this->bStatus = true;
        $this->obData = $obData;

        return $this;
    }

    /**
     * Set data value and status of result in false
     * @param mixed $obData
     * @return ResultStore
     */
    public function setFalse($obData = null)
    {
        $this->bStatus = false;
        $this->obData = $obData;

        return $this;
    }

    /**
     * Set error message value
     * @param string $sMessage
     * @return ResultStore
     */
    public function setMessage($sMessage)
    {
        $this->sErrorMessage = $sMessage;

        return $this;
    }

    /**
     * Set error code value
     * @param string $sCode
     * @return ResultStore
     */
    public function setCode($sCode)
    {
        $this->sErrorCode = $sCode;

        return $this;
    }

    /**
     * @return bool
     */
    public function status()
    {
        return $this->bStatus;
    }

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

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

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

    /**
     * Get result array
     * @return array
     */
    public function get()
    {
        $arResult = [
            'status'  => $this->status(),
            'data'    => $this->data(),
            'message' => $this->message(),
            'code'    => $this->code(),
        ];

        return $arResult;
    }

    /**
     * Generate result JSON string
     * @return string
     */
    public function getJSON()
    {
        return json_encode($this->get());
    }
}


<?php
namespace eMacros\Runtime\Property;

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

class PropertyGet implements Applicable {
	/**
	 * Property to obtain
	 * @var mixed
	 */
	public $property;

	public function __construct($property = null) {
		$this->property = $property;
	}

	/**
	 * Obtains a key/property in an array/object
	 * Usage: (# 'name' _obj) (# 3 _array) (#name _obj)
	 * Returns: Key/property value
	 * (non-PHPdoc)
	 * @see \eMacros\Applicable::apply()
	 */
	public function apply(Scope $scope, GenericList $arguments) {
		//get index and value
		if (is_null($this->property)) {
			if (count($arguments) == 0) throw new \BadFunctionCallException("PropertyGet: No parameters found.");
			$key = $arguments[0]->evaluate($scope);

			if (count($arguments) == 1) {
				if (!array_key_exists(0, $scope->arguments)) throw new \BadFunctionCallException("PropertyGet: Expected value of type array/object as second parameter but none found.");
				$value = $scope->arguments[0];
			}
			else $value = $arguments[1]->evaluate($scope);
		}
		else {
			$key = $this->property;

			if (count($arguments) == 0) {
				if (!array_key_exists(0, $scope->arguments)) throw new \BadFunctionCallException("PropertyGet: Expected value of type array/object as first parameter but none found.");
				$value = $scope->arguments[0];
			}
			else $value = $arguments[0]->evaluate($scope);
		}

		//get index/property
		if (is_array($value)) {
			if (!array_key_exists($key, $value)) {
				if (is_int($key)) throw new \OutOfBoundsException(sprintf("PropertyGet: Key %s does not exists.", strval($key)));
				throw new \InvalidArgumentException(sprintf("PropertyGet: Key '%s' does not exists.", strval($key)));
			}

			return $value[$key];
		}
		elseif ($value instanceof \ArrayObject || $value instanceof \ArrayAccess) {
			if (!$value->offsetExists($key)) {
				if (is_int($key)) throw new \OutOfBoundsException(sprintf("PropertyGet: Key %s does not exists.", strval($key)));
				throw new \InvalidArgumentException(sprintf("PropertyGet: Key '%s' does not exists.", strval($key)));
			}

			return $value[$key];
		}
		elseif (is_object($value)) {
			//check property existence
			if (!property_exists($value, $key)) {
				//check existence through __isset
				if (method_exists($value, '__isset') && !$value->__isset($key)) throw new \InvalidArgumentException(sprintf("PropertyGet: Property '%s' not found.", strval($key)));
				//try calling __get
				if (method_exists($value, '__get')) return $value->__get($key);
				throw new \InvalidArgumentException(sprintf("PropertyGet: Property '%s' not found.", strval($key)));
			}

			//check property access
			$rp = new \ReflectionProperty($value, $key);
			if (!$rp->isPublic()) $rp->setAccessible(true);
			return $rp->getValue($value);
		}

		throw new \InvalidArgumentException(sprintf("PropertyGet: Expected value of type array/object but %s found instead", gettype($value)));
	}
}
?>


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

use Assetic\AssetManager;
use Assetic\Factory\AssetFactory;
use Assetic\Filter\FilterInterface;
use Assetic\FilterManager;
use RedKiteCms\Configuration\ConfigurationHandler;

/**
 * This object is assigned to build an AssetFactory object
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Bridge\Assetic
 */
class AsseticFactoryBuilder
{
    /**
     * @type ConfigurationHandler
     */
    private $configurationHandler;
    /**
     * @type array
     */
    private $filters = array();

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

    /**
     * Builds the AssetFactory object
     *
     * @return \Assetic\Factory\AssetFactory
     */
    public function build()
    {
        $assetManager = new AssetManager();
        $filterManager = new FilterManager();
        foreach ($this->filters as $filterName => $filter) {
            $filterManager->set($filterName, $filter);
        }
        $assetsFactory = new AssetFactory($this->configurationHandler->webDir());
        $assetsFactory->setAssetManager($assetManager);
        $assetsFactory->setFilterManager($filterManager);

        return $assetsFactory;
    }

    /**
     * Adds a filter to the AssetFactory object
     *
     * @param string                          $filterName
     * @param \Assetic\Filter\FilterInterface $filter
     * @return \RedKiteCms\Bridge\Assetic\AsseticFactoryBuilder
     */
    public function addFilter($filterName, FilterInterface $filter)
    {
        $this->filters[$filterName] = $filter;

        return $this;
    }
}


<?php
/**
 * Definition of class Text
 *
 * @copyright  2014-today Justso GmbH
 * @author     j.schirrmacher@justso.de
 * @package    justso\model
 */

namespace justso\justtexts;

use justso\justapi\SystemEnvironmentInterface;

/**
 * Class Text
 * @package justso\model
 */
class Text implements TextInterface
{
    protected $languages = null;
    protected $baseLang;
    protected $extraLangs;
    protected $baseDir;
    protected $outdatedDir;

    /**
     * @var SystemEnvironmentInterface
     */
    protected $env;

    protected $pageName;
    protected $contents = array();

    /**
     * Initializes a text page.
     *
     * @param SystemEnvironmentInterface $env
     * @param string $pageName Name of page
     */
    public function __construct(SystemEnvironmentInterface $env, $pageName)
    {
        $this->env = $env;
        $this->pageName = $pageName;
        if ($this->languages === null) {
            $bootstrap = $env->getBootstrap();
            $configuration = $bootstrap->getConfiguration();
            $this->extraLangs = $this->languages = $configuration['languages'];
            $this->baseLang = array_shift($this->extraLangs);
            $appRoot = $bootstrap->getAppRoot();
            $this->baseDir = $appRoot . '/htdocs/nls/';
            $this->outdatedDir = $appRoot . '/content/outdateInfo/';
        }
    }

    /**
     * Reads the contents of a language file and returns it.
     *
     * @param string $language language code
     * @return array
     */
    protected function readFileContents($language)
    {
        $fileName = $this->getFileName($language);
        $fs = $this->env->getFileSystem();
        if (!$fs->fileExists($fileName)) {
            return array();
        }
        $content = json_decode(preg_replace('/^.*?define\((.*)\);\s*/s', '$1', $fs->getFile($fileName)), true);
        if ($language === $this->baseLang) {
            $content = $content['root'];
        }

        $outdateInfo = [];
        $fileName = $this->getOutdateInfoFileName($language);
        if ($fs->fileExists($fileName)) {
            $outdateInfo = json_decode($fs->getFile($fileName), true);
        }
        foreach ($content as $id => $text) {
            $outdated = isset($outdateInfo[$id]) ? $outdateInfo[$id] : true;
            $content[$id] = array('id' => $id, 'name' => $id, 'content' => $text, 'outdated' => $outdated);
        }

        return $content;
    }

    /**
     * Writes the current texts of the specified language to the file system.
     *
     * @param string $language
     */
    private function writeTextsToFile($language)
    {
        $textInfo = array();
        $outdateInfo = array();
        foreach ($this->contents[$language] as $id => $info) {
            $textInfo[$id] = $info['content'];
            $outdateInfo[$id] = $info['outdated'];
        }
        if ($language === $this->baseLang) {
            $content = array('root' => $textInfo) + array_fill_keys($this->extraLangs, true);
        } else {
            $content = $textInfo;
        }
        $encodeFlags = JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES;
        $content = "'use strict';\n/*global define*/\ndefine(" . json_encode($content, $encodeFlags) . ");\n";
        $fs = $this->env->getFileSystem();
        $fs->putFile($this->getFileName($language), $content);
        $fs->putFile($this->getOutdateInfoFileName($language), json_encode($outdateInfo, $encodeFlags));
    }

    /**
     * Returns all texts of a page in the specified language.
     *
     * @param $language
     * @return mixed
     */
    public function getPageTexts($language)
    {
        if (!isset($this->contents[$language])) {
            $this->contents[$language] = $this->readFileContents($language);
        }
        return $this->contents[$language];
    }

    /**
     * Returns the texts including an information about the text in the base language.
     *
     * @param $language
     * @return array
     */
    public function getTextsWithBaseTexts($language)
    {
        $texts = $this->getPageTexts($language);

        if ($language !== $this->baseLang) {
            $baseTexts = $this->getPageTexts($this->baseLang);

            $texts = array_map(
                function ($text, $baseText) {
                    return $text + array("basecontent" => $baseText['content']);
                },
                $texts,
                $baseTexts
            );
        }

        return $texts;
    }

    /**
     * Returns the text of a container in the specified language.
     * If the text is not defined, null is returned.
     *
     * @param string $name
     * @param string $language
     * @return array
     */
    public function getText($name, $language)
    {
        $allTexts = $this->getPageTexts($language);
        if (isset($allTexts[$name])) {
            return $allTexts[$name];
        } else {
            return null;
        }
    }

    /**
     * Adds a new text container.
     *
     * @param string $name
     * @param string $content
     * @param string $language
     * @return array
     * @throws \Exception
     */
    public function addTextContainer($name, $content, $language)
    {
        $allTexts = $this->getPageTexts($language);
        if (isset($allTexts[$name])) {
            throw new \Exception("Text container name already used.");
        }
        $this->contents[$language][$name] = array(
            'id'       => $name,
            'name'     => $name,
            'content'  => $content,
            'outdated' => false
        );
        $this->writeTextsToFile($language);
        if ($language === $this->baseLang) {
            $this->setExtraLanguagesOutdated($name, $content);
        }

        return $this->contents[$language][$name];
    }

    /**
     * Modifies the content and optionally the name of a text container.
     * If the base language text is changed, the corresponding texts of other languages are invalidated.
     *
     * @param string $oldName
     * @param string $newName
     * @param string $content
     * @param string $language
     * @return array
     * @throws \Exception
     */
    public function modifyTextContainer($oldName, $newName, $content, $language)
    {
        foreach ($this->languages as $lang) {
            $modified = false;
            $allTexts = $this->getPageTexts($lang);
            if (!isset($allTexts[$oldName])) {
                throw new \Exception("Text container unknown.");
            }
            if ($oldName !== $newName) {
                if (isset($allTexts[$newName])) {
                    throw new \Exception("Text container already exists");
                }
                $this->contents[$lang][$newName] = $this->contents[$lang][$oldName];
                $this->contents[$lang][$newName]['id'] = $newName;
                $this->contents[$lang][$newName]['name'] = $newName;
                unset($this->contents[$lang][$oldName]);
                $modified = true;
            }
            if ($language === $lang) {
                $this->contents[$lang][$newName]['content'] = $content;
                $this->contents[$lang][$newName]['outdated'] = false;
                $modified = true;
            } elseif ($language === $this->baseLang) {
                $this->contents[$lang][$newName]['outdated'] = true;
                $modified = true;
            }
            if ($modified) {
                $this->writeTextsToFile($lang);
            }
        }
        return $this->contents[$language][$newName];
    }

    /**
     * Deletes a single text container
     *
     * @param $name
     */
    public function deleteTextContainer($name)
    {
        foreach ($this->languages as $lang) {
            $this->getPageTexts($lang);
            unset($this->contents[$lang][$name]);
            $this->writeTextsToFile($lang);
        }
    }

    /**
     * Returns the name of the file containing the texts.
     *
     * @param $language
     * @return string
     */
    private function getFileName($language)
    {
        if ($language === $this->baseLang) {
            return $this->baseDir . $this->pageName . '.js';
        } else {
            return $this->baseDir . $language . '/' . $this->pageName . '.js';
        }
    }

    /**
     * Sets all extra language texts to 'outdated'
     *
     * @param $name
     * @param $content
     */
    private function setExtraLanguagesOutdated($name, $content)
    {
        foreach ($this->extraLangs as $lang) {
            $this->getPageTexts($lang);
            $this->contents[$lang][$name]['outdated'] = true;
            if (!isset($this->contents[$lang][$name]['content'])) {
                $this->contents[$lang][$name]['content'] = $content;
            }
            $this->writeTextsToFile($lang);
        }
    }

    /**
     * @param $language
     * @return string
     */
    private function getOutdateInfoFileName($language)
    {
        return $this->outdatedDir . $language . '/' . $this->pageName . '.json';
    }

    /**
     * Removes all files related to a text page
     */
    public function removeAll()
    {
        $fs = $this->env->getFileSystem();
        $fs->deleteFile($this->baseDir . $this->pageName . '.js');
        $fs->deleteFile($this->outdatedDir . $this->baseLang . '/' . $this->pageName . '.json');
        foreach ($this->extraLangs as $language) {
            $fs->deleteFile($this->baseDir . $language . '/' . $this->pageName . '.js');
            $fs->deleteFile($this->outdatedDir . $language . '/' . $this->pageName . '.json');
        }
    }
}


<?php

/*
 * This file is part of the Fuel Menu package.
 *
 * (c) Indigo Development Team
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Knp\Menu\Provider;

use Fuel\Dependency\Container;

/**
 * Fuel Menu Provider using Dependency Container
 *
 * @author Márk Sági-Kazár <mark.sagikazar@gmail.com>
 */
class FuelProvider implements MenuProviderInterface
{
	/**
	 * @var Container
	 */
	private $container;

	/**
	 * @var array
	 */
	private $menus = [];

	/**
	 * @param Container $container
	 */
	public function __construct(Container $container, array $menus = [])
	{
		$this->container = $container;
		$this->menus = $menus;
	}

	/**
	 * Adds a menu
	 *
	 * @param string $menu
	 * @param string $name
	 */
	public function add($menu, $name)
	{
		$this->menus[$menu] = $name;
	}

	/**
	 * {@inheritdoc}
	 */
	public function get($name, array $options = [])
	{
		if (isset($this->menus[$name]))
		{
			$name = $this->menus[$name];
		}

		return $this->container->multiton('menu', $name);
	}

	/**
	 * {@inheritdoc}
	 */
	public function has($name, array $options = [])
	{
		return isset($this->menus[$name]) or $this->container->isInstance('menu', $name);
	}
}


<?php

namespace Esockets\Socket;

use Esockets\Base\AbstractAddress;
use Esockets\Base\AbstractConnectionResource;
use Esockets\Base\Exception\SendException;

/**
 * Класс костыльного UDP соединения.
 * Todo избавиться от такого костыля.
 */
final class VirtualUdpConnection extends AbstractConnectionResource
{
    use SocketTrait;

    private $connectionResource;
    private $id;
    private $peerAddress;
    private $buffer = [];

    /**
     * VirtualUdpConnection constructor.
     *
     * @param int $socketDomain
     * @param SocketConnectionResource $connectionResource
     * @param $peerAddress AbstractAddress|Ipv4Address|UnixAddress
     * @param array $buffer
     */
    public function __construct(
        int $socketDomain,
        SocketConnectionResource $connectionResource,
        AbstractAddress $peerAddress,
        array $buffer
    )
    {
        static $id = 0;
        $this->id = ++$id;
        $this->socketDomain = $socketDomain;
        $this->connectionResource = $connectionResource;
        $this->peerAddress = $peerAddress;
        $this->buffer = $buffer;
    }

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

    /**
     * @return resource Socket resource
     */
    public function getResource()
    {
        return $this->connectionResource->getResource();
    }

    /**
     * @return AbstractAddress|Ipv4Address|UnixAddress
     */
    public function getPeerAddress(): AbstractAddress
    {
        return $this->peerAddress;
    }

    public function addToBuffer($data)
    {
        array_push($this->buffer, $data);
    }

    public function getBufferLength(): int
    {
        return count($this->buffer);
    }

    public function read()
    {
        if (count($this->buffer) === 0) {
            return null;
        }
        return array_shift($this->buffer);
    }

    /**
     * @param $data
     *
     * @return bool
     * @throws SendException
     */
    public function send($data): bool
    {
        $dataLength = strlen($data);
        if ($dataLength === 0) {
            throw new \RuntimeException('Can not send an empty package.');
        }
        if ($this->isIpAddress()) {
            $address = $this->peerAddress->getIp();
            $port = $this->peerAddress->getPort();
        } else {
            $address = $this->peerAddress->getSockPath();
            $port = 0;
        }
        $wrote = socket_sendto($this->connectionResource->getResource(), $data, strlen($data), 0, $address, $port);
        if ($wrote === false || $wrote === 0) {
//            throw new SendException('I don\'t send :(');
            return false;
        } elseif ($wrote < $dataLength) {
            throw new SendException('Could not send the whole package.');
        }
        return true;
    }
}


<?php
namespace app\manage\controller;

use think\Url;
use think\Request;
use core\manage\logic\MenuLogic;

class Menu extends Base
{

    /**
     * 菜单列表
     *
     * @param Request $request
     * @return string
     */
    public function index(Request $request)
    {
        $this->site_title = '菜单管理';
        $menu_model = MenuLogic::model();

        // 上级
        $menu_pid = $request->param('menu_pid', 0);
        $this->assign('menu_pid', $menu_pid);

        $map = [
            'menu_pid' => $menu_pid
        ];

        // 分组列表
        $group_list = $menu_model->field('id, menu_group')
            ->where($map)
            ->group('menu_group')
            ->order('menu_sort asc')
            ->select();
        $this->assign('group_list', $group_list);

        // 分组
        $group_name = $request->param('group', '');
        if (! empty($group_name)) {
            $map['menu_group'] = $group_name;
        }
        $this->assign('group', $group_name);

        // 列表
        $list = $menu_model->where($map)
            ->order('menu_sort asc')
            ->select();
        $this->assign('list', $list);

        return $this->fetch();
    }

    /**
     * 添加菜单
     *
     * @param Request $request
     * @return mixed
     */
    public function addMenu(Request $request)
    {
        $menu_logic = MenuLogic::instance();
        if ($request->isPost()) {
            $data = [
                'menu_name' => $request->param('menu_name'),
                'menu_url' => $request->param('menu_url'),
                'menu_pid' => $request->param('menu_pid', 0),
                'menu_group' => $request->param('menu_group', ''),
                'menu_sort' => $request->param('menu_sort', 0),
                'menu_target' => $request->param('menu_target', ''),
                'menu_build' => $request->param('menu_build', 0),
                'menu_status' => $request->param('menu_status', 0)
            ];

            // 验证菜单
            $res = $menu_logic->validate->scene('add')->check($data);
            if (! $res) {
                return $this->error($menu_logic->validate->getError());
            }

            // 添加菜单
            $menu_logic->addMenu($data);

            return $this->success('添加菜单成功', Url::build('menu/index', [
                'menu_pid' => $request->param('menu_pid')
            ]));
        } else {
            $this->site_title = '新增菜单';

            // 上级，返回用
            $menu_pid = $request->param('menu_pid', 0);
            $this->assign('menu_pid', intval($menu_pid));

            // 上级菜单下拉选择
            $menu_select = $menu_logic->getMenuSelect();
            $this->assign('menu_select', $menu_select);

            // 打开方式
            $menu_target = $menu_logic->menuTarget();
            $this->assign('menu_target', $menu_target);

            // 是否build
            $menu_build = $menu_logic->menuBuild();
            $this->assign('menu_build', $menu_build);

            // 菜单状态
            $menu_status = $menu_logic->menuStatus();
            $this->assign('menu_status', $menu_status);

            return $this->fetch();
        }
    }

    /**
     * 编辑菜单
     *
     * @param Request $request
     * @return mixed
     */
    public function editMenu(Request $request)
    {
        $menu_id = $request->param('menu_id');
        if (empty($menu_id)) {
            return $this->error('菜单ID为空');
        }

        $menu_logic = MenuLogic::instance();
        if ($request->isPost()) {
            $data = [
                'menu_name' => $request->param('menu_name'),
                'menu_url' => $request->param('menu_url'),
                'menu_pid' => $request->post('menu_pid', 0),
                'menu_group' => $request->param('menu_group', ''),
                'menu_sort' => $request->param('menu_sort', 0),
                'menu_target' => $request->param('menu_target', ''),
                'menu_build' => $request->param('menu_build', 0),
                'menu_status' => $request->param('menu_status', 0)
            ];

            // 验证菜单
            $res = $menu_logic->validate->scene('edit')->check($data);
            if (! $res) {
                return $this->error($menu_logic->validate->getError());
            }

            // 保存菜单
            $menu_logic->saveMenu($data, $menu_id);

            return $this->success('修改菜单成功', Url::build('menu/index', [
                'menu_pid' => $request->param('menu_pid')
            ]));
        } else {
            $this->site_title = '编辑菜单';
            $this->assign('menu_id', $menu_id);

            // 菜单
            $menu = $menu_logic->model->get($menu_id);
            $this->assign('menu', $menu);

            // 上级菜单下拉选择
            $menu_select = $menu_logic->getMenuSelect();
            $this->assign('menu_select', $menu_select);

            // 打开方式
            $menu_target = $menu_logic->menuTarget();
            $this->assign('menu_target', $menu_target);

            // 是否build
            $menu_build = $menu_logic->menuBuild();
            $this->assign('menu_build', $menu_build);

            // 菜单状态
            $menu_status = $menu_logic->menuStatus();
            $this->assign('menu_status', $menu_status);

            return $this->fetch();
        }
    }

    /**
     * 删除菜单
     *
     * @param Request $request
     * @return mixed
     */
    public function delMenu(Request $request)
    {
        $menu_id = $request->param('menu_id');
        if (empty($menu_id)) {
            return $this->error('菜单ID为空');
        }
        $menu_model = MenuLogic::model();

        // 检查子菜单
        $map = [
            'menu_pid' => $menu_id
        ];
        $menu = $menu_model->where($map)->find();
        if (! empty($menu)) {
            return $this->error('请先删除该菜单下的子菜单');
        }

        // 删除菜单
        $menu_model->del($menu_id);

        return $this->success('删除菜单成功');
    }

    /**
     * 更改菜单
     *
     * @param Request $request
     * @return mixed
     */
    public function modifyMenu(Request $request)
    {
        $id = $request->param('id');
        if (empty($id)) {
            return $this->error('ID为空');
        }

        $field_arr = [
            'menu_group',
            'menu_sort',
            'menu_status'
        ];
        $field = $request->param('field');
        if (! in_array($field, $field_arr)) {
            return $this->error('非法的字段');
        }

        $value = $request->param('value', '');
        MenuLogic::model()->modify($id, $field, $value);

        return $this->success('更改成功');
    }
}


<?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.
 */

/**
 * OpenPlatform.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\OpenPlatform;

use EasyWeChat\Support\Traits\PrefixedContainer;

/**
 * Class OpenPlatform.
 *
 * @property \EasyWeChat\OpenPlatform\Api\BaseApi $api
 * @property \EasyWeChat\OpenPlatform\Api\PreAuthorization $pre_auth
 * @property \EasyWeChat\OpenPlatform\Guard $server
 * @property \EasyWeChat\OpenPlatform\AccessToken $access_token
 *
 * @method \EasyWeChat\Support\Collection getAuthorizationInfo($authCode = null)
 * @method \EasyWeChat\Support\Collection getAuthorizerInfo($authorizerAppId)
 * @method \EasyWeChat\Support\Collection getAuthorizerOption($authorizerAppId, $optionName)
 * @method \EasyWeChat\Support\Collection setAuthorizerOption($authorizerAppId, $optionName, $optionValue)
 * @method \EasyWeChat\Support\Collection getAuthorizerList($offset = 0, $count = 500)
 */
class OpenPlatform
{
    use PrefixedContainer;

    /**
     * Create an instance of the EasyWeChat for the given authorizer.
     *
     * @param string $appId        Authorizer AppId
     * @param string $refreshToken Authorizer refresh-token
     *
     * @return \EasyWeChat\Foundation\Application
     */
    public function createAuthorizerApplication($appId, $refreshToken)
    {
        $this->fetch('authorizer', function ($authorizer) use ($appId, $refreshToken) {
            $authorizer->setAppId($appId);
            $authorizer->setRefreshToken($refreshToken);
        });

        return $this->fetch('app', function ($app) {
            $app['access_token'] = $this->fetch('authorizer_access_token');
            $app['oauth'] = $this->fetch('oauth');
            $app['server'] = $this->fetch('server');
        });
    }

    /**
     * Quick access to the base-api.
     *
     * @param string $method
     * @param array  $args
     *
     * @return mixed
     */
    public function __call($method, $args)
    {
        return call_user_func_array([$this->api, $method], $args);
    }
}


<?php

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

namespace Predis\Protocol\Text;

use Predis\Command\CommandInterface;
use Predis\CommunicationException;
use Predis\Connection\CompositeConnectionInterface;
use Predis\Protocol\ProtocolException;
use Predis\Protocol\ProtocolProcessorInterface;
use Predis\Response\Error as ErrorResponse;
use Predis\Response\Iterator\MultiBulk as MultiBulkIterator;
use Predis\Response\Status as StatusResponse;

/**
 * Protocol processor for the standard Redis wire protocol.
 *
 * @link http://redis.io/topics/protocol
 *
 * @author Daniele Alessandri <suppakilla@gmail.com>
 */
class ProtocolProcessor implements ProtocolProcessorInterface
{
    protected $mbiterable;
    protected $serializer;

    /**
     *
     */
    public function __construct()
    {
        $this->mbiterable = false;
        $this->serializer = new RequestSerializer();
    }

    /**
     * {@inheritdoc}
     */
    public function write(CompositeConnectionInterface $connection, CommandInterface $command)
    {
        $request = $this->serializer->serialize($command);
        $connection->writeBuffer($request);
    }

    /**
     * {@inheritdoc}
     */
    public function read(CompositeConnectionInterface $connection)
    {
        $chunk = $connection->readLine();
        $prefix = $chunk[0];
        $payload = substr($chunk, 1);

        switch ($prefix) {
            case '+':
                return new StatusResponse($payload);

            case '$':
                $size = (int) $payload;
                if ($size === -1) {
                    return;
                }

                return substr($connection->readBuffer($size + 2), 0, -2);

            case '*':
                $count = (int) $payload;

                if ($count === -1) {
                    return;
                }
                if ($this->mbiterable) {
                    return new MultiBulkIterator($connection, $count);
                }

                $multibulk = array();

                for ($i = 0; $i < $count; ++$i) {
                    $multibulk[$i] = $this->read($connection);
                }

                return $multibulk;

            case ':':
                $integer = (int) $payload;

                return $integer == $payload ? $integer : $payload;

            case '-':
                return new ErrorResponse($payload);

            default:
                CommunicationException::handle(new ProtocolException(
                    $connection, "Unknown response prefix: '$prefix' [{$connection->getParameters()}]"
                ));

                return;
        }
    }

    /**
     * Enables or disables returning multibulk responses as specialized PHP
     * iterators used to stream bulk elements of a multibulk response instead
     * returning a plain array.
     *
     * Streamable multibulk responses are not globally supported by the
     * abstractions built-in into Predis, such as transactions or pipelines.
     * Use them with care!
     *
     * @param bool $value Enable or disable streamable multibulk responses.
     */
    public function useIterableMultibulk($value)
    {
        $this->mbiterable = (bool) $value;
    }
}


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

namespace cascade\components\db\behaviors;

use Yii;

/**
 * QueryTaxonomy [[@doctodo class_description:cascade\components\db\behaviors\QueryTaxonomy]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class QueryTaxonomy extends \canis\db\behaviors\ActiveRecord
{
    /**
     * @var [[@doctodo var_type:viaModelClass]] [[@doctodo var_description:viaModelClass]]
     */
    public $viaModelClass = 'ObjectTaxonomy';
    /**
     * @var [[@doctodo var_type:relationKey]] [[@doctodo var_description:relationKey]]
     */
    public $relationKey = 'object_id';
    /**
     * @var [[@doctodo var_type:taxonomyKey]] [[@doctodo var_description:taxonomyKey]]
     */
    public $taxonomyKey = 'taxonomy_id';

    /**
     * [[@doctodo method_description:filterByTaxonomy]].
     *
     * @param [[@doctodo param_type:value]] $value  [[@doctodo param_description:value]]
     * @param array                         $params [[@doctodo param_description:params]] [optional]
     */
    public function filterByTaxonomy($value, $params = [])
    {
        $queryAlias = isset($params['queryAlias']) ? $params['queryAlias'] : $this->owner->primaryAlias;
        $queryPk = isset($params['queryPk']) ? $params['queryPk'] : $this->owner->primaryTablePk;
        $taxonomyAlias = isset($params['taxonomyAlias']) ? $params['taxonomyAlias'] : 'tax';

        $pivotTableClass = Yii::$app->classes[$this->viaModelClass];
        $pivotTable = $pivotTableClass::tableName();
        $taxonomy = static::parseTaxonomyValue($value);
        $params = [];
        $this->owner->andWhere(['{{' . $taxonomyAlias . '}}.[[' . $this->taxonomyKey . ']]' => $taxonomy]);
        $conditions = ['and', '{{' . $queryAlias . '}}.[[' . $queryPk . ']]={{' . $taxonomyAlias . '}}.[[' . $this->relationKey . ']]'];
        $this->owner->leftJoin([$taxonomyAlias => $pivotTable], $conditions, $params);
    }

    /**
     * [[@doctodo method_description:parseTaxonomyValue]].
     *
     * @param [[@doctodo param_type:value]] $value [[@doctodo param_description:value]]
     *
     * @return [[@doctodo return_type:parseTaxonomyValue]] [[@doctodo return_description:parseTaxonomyValue]]
     */
    public static function parseTaxonomyValue($value)
    {
        if (!is_array($value)) {
            $value = [$value];
        }
        foreach ($value as $k => $v) {
            if (is_object($v)) {
                $value[$k] = $v->primaryKey;
            } elseif (is_array($v)) {
                unset($value[$k]);
                if (isset($v['systemId']) && isset($v['taxonomyType'])) {
                    $taxonomyType = Yii::$app->collectors['taxonomies']->getOne($v['taxonomyType']);
                    if (isset($taxonomyType) && ($taxonomy = $taxonomyType->getTaxonomy($v['systemId']))) {
                        $value[$k] = $taxonomy->primaryKey;
                    }
                }
            }
        }
        if (empty($value)) {
            $value = [0];
        }

        return $value;
    }
}


<?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\Content\PageCollection;

use RedKiteCms\Bridge\Dispatcher\Dispatcher;
use RedKiteCms\Configuration\ConfigurationHandler;
use RedKiteCms\EventSystem\Event\Event;
use RedKiteCms\Exception\General\LogicException;
use RedKiteCms\Tools\Utils;

/**
 * Class PageCollectionBase is a base object assigned to handle common methods for pages management
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Content\Page
 */
abstract class PageCollectionBase
{
    /**
     * @type string
     */
    protected $username;
    /**
     * @type string
     */
    protected $pageFile = 'page.json';
    /**
     * @type string
     */
    protected $seoFile = 'seo.json';
    /**
     * @type string
     */
    protected $baseDir;
    /**
     * @type string
     */
    protected $pagesRootDir;
    /**
     * @type string
     */
    protected $pagesDir;
    /**
     * @type string
     */
    protected $pagesRemovedDir;

    /**
     * Constructor
     *
     * @param \RedKiteCms\Configuration\ConfigurationHandler $configurationHandler
     */
    public function __construct(ConfigurationHandler $configurationHandler)
    {
        $this->configurationHandler = $configurationHandler;
        $this->baseDir = $this->configurationHandler->siteDir();
        $this->pagesRootDir = $this->configurationHandler->pagesRootDir();
        $this->pagesDir = $this->configurationHandler->pagesDir();
        $this->pagesRemovedDir = $this->configurationHandler->pagesRemovedDir();
    }

    /**
     * Sets the page contributor
     * @param string $username
     *
     * @return $this
     */
    public function contributor($username)
    {
        $this->username = $username;
        $this->pageFile = 'page.json';
        $this->seoFile = 'seo.json';
        if (null !== $this->username) {
            $this->pageFile = $this->seoFile = $this->username . '.json';
        }

        return $this;
    }

    /**
     * Checks the page contributor has been set
     */
    protected function contributorDefined()
    {
        if (null === $this->username && !$this->configurationHandler->isTheme()) {
            $exception = array(
                "message" => 'exception_contributor_not_defined',
                "show_exception" => true,
            );
            throw new LogicException(json_encode($exception));
        }
    }
}


<?php
/**
 * This file is part of the Bruery Platform.
 *
 * (c) Viktore Zara <viktore.zara@gmail.com>
 * (c) Mell Zamora <mellzamora@outlook.com>
 *
 * Copyright (c) 2016. For the full copyright and license information, please view the LICENSE  file that was distributed with this source code.
 */

namespace Bruery\AdminBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class OverrideCompilerPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        //override admin pool class
        if ($container->hasParameter('bruery.admin.pool.base_admin.class')) {
            $definition = $container->getDefinition('sonata.admin.pool');
            $definition->setClass($container->getParameter('bruery.admin.pool.base_admin.class'));
            if ($container->hasParameter('bruery.admin.options.use_footable') && $container->hasParameter('bruery.admin.settings.footable')) {
                $definition->addMethodCall('setOption', array('use_footable', $container->getParameter('bruery.admin.options.use_footable')));
                $definition->addMethodCall('setOption', array('footable_settings', $container->getParameter('bruery.admin.settings.footable')));
            }
            $definition->addMethodCall('setOption', array('skin', $container->getParameter('bruery.admin.settings.skin')));
            $definition->addMethodCall('setOption', array('sidebar_collapse', $container->getParameter('bruery.admin.settings.sidebar_collapse')));
        }
    }
}


<?php

namespace Extlib\Http;

/**
 * Http response class from http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
 *
 * @category    Extlib
 * @author      Lukasz Ciolecki <ciolecki.lukasz@gmail.com>
 * @copyright   Copyright (c) Lukasz Ciolecki (mart)
 */
class Response
{
    // Informational 1xx
    const CODE_CONTINUE = 100;
    const CODE_SWITCHING_PROTOCOLS = 101;
    const CODE_PROCESSING = 102;

    // Success 2xx
    const CODE_OK = 200;
    const CODE_CREATED = 201;
    const CODE_ACCEPTED = 202;
    const CODE_NONAUTHORITATIVE_INFORMATION = 203;
    const CODE_NO_CONTENT = 204;
    const CODE_RESET_CONTENT = 205;
    const CODE_PARTIAL_CONTENT = 206;
    const CODE_MULTI_STATUS = 207;
    const CODE_ALREADY_REPORTED = 208;
    const CODE_IM_USED = 226;

    // Redirection 3xx
    const CODE_MULTIPLE_CHOICES = 300;
    const CODE_MOVED_PERMANENTLY = 301;
    const CODE_FOUND = 302;
    const CODE_SEE_OTHER = 303;
    const CODE_NOT_MODIFIED = 304;
    const CODE_USE_PROXY = 305;
    const CODE_SWITCH_PROXY = 306;
    const CODE_TEMPORARY_REDIRECT = 307;
    const CODE_PERMANENT_REDIRECT = 308;

    // Client Error 4xx
    const CODE_BAD_REQUEST = 400;
    const CODE_UNAUTHORIZED = 401;
    const CODE_PAYMENT_REQUIRED = 402;
    const CODE_FORBIDDEN = 403;
    const CODE_NOT_FOUND = 404;
    const CODE_METHOD_NOT_ALLOWED = 405;
    const CODE_NOT_ACCEPTABLE = 406;
    const CODE_PROXY_AUTHENTICATION_REQUIRED = 407;
    const CODE_REQUEST_TIMEOUT = 408;
    const CODE_CONFLICT = 409;
    const CODE_GONE = 410;
    const CODE_LENGTH_REQUIRED = 411;
    const CODE_PRECONDITION_FAILED = 412;
    const CODE_REQUEST_ENTITY_TOO_LARGE = 413;
    const CODE_REQUEST_URI_TOO_LONG = 414;
    const CODE_UNSUPORTED_MEDIA_TYPE = 415;
    const CODE_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
    const CODE_EXPECTATION_FAILED = 417;

    // Server Error 5xx
    const CODE_INTERNAL_SERVER_ERROR = 500;
    const CODE_NOT_IMPLEMENTED = 501;
    const CODE_BAD_GATWAY = 502;
    const CODE_SERVICE_UNAVAILABLE = 503;
    const CODE_GATEWAY_TIMEOUT = 504;
    const CODE_HTTP_VERSION_NOT_SUPPORTED = 505;
    const CODE_VARIANT_ALSO_NEGOTIATES = 506;
    const CODE_INSUFFICIENT_STORAGE = 507;
    const CODE_LOOP_DETECTED = 508;
    const CODE_BANDWIDTH_LIMIT_EXCEEDED = 509;
    const CODE_NOT_EXTENDED = 510;
    const CODE_NETWORK_AUTHENTICATION = 511;
    const CODE_ORIGIN_ERROR = 520;
    const CODE_CONNECTION_TIME_OUT = 522;
    const CODE_PROXY_DECLINED_REQUEST = 523;
    const CODE_A_TIMEOUT_OCCURED = 524;
    const CODE_NETWORK_READ_TIMEOUT_ERROR = 598;
    const CODE_NETWORK_CONNECT_TIMEOUT_ERROR = 599;

    static public $messages = array(
        self::CODE_CONTINUE => 'Continue',
        self::CODE_SWITCHING_PROTOCOLS => 'Switching Protocols',
        self::CODE_PROCESSING => 'Processing',
        self::CODE_OK => 'OK',
        self::CODE_CREATED => 'Created',
        self::CODE_ACCEPTED => 'Accepted',
        self::CODE_NONAUTHORITATIVE_INFORMATION => ' Non-Authoritative Information',
        self::CODE_NO_CONTENT => 'No Content',
        self::CODE_RESET_CONTENT => 'Reset Content',
        self::CODE_PARTIAL_CONTENT => 'Partial Content',
        self::CODE_MULTI_STATUS => 'Multi-Status',
        self::CODE_ALREADY_REPORTED => 'Already Reported',
        self::CODE_IM_USED => 'IM Used',
        self::CODE_MULTIPLE_CHOICES => 'Multiple Choices',
        self::CODE_MOVED_PERMANENTLY => 'Moved Permanently',
        self::CODE_FOUND => 'Found',
        self::CODE_SEE_OTHER => 'See Other',
        self::CODE_NOT_MODIFIED => 'Not Modified',
        self::CODE_USE_PROXY => 'Use Proxy',
        self::CODE_SWITCH_PROXY => 'Switch Proxy',
        self::CODE_TEMPORARY_REDIRECT => 'Temporary Redirect',
        self::CODE_PERMANENT_REDIRECT => 'Permanent Redirect',
        self::CODE_BAD_REQUEST => 'Bad Request',
        self::CODE_UNAUTHORIZED => 'Unauthorized',
        self::CODE_PAYMENT_REQUIRED => 'Payment Required',
        self::CODE_FORBIDDEN => 'Forbidden',
        self::CODE_NOT_FOUND => 'Not Found',
        self::CODE_METHOD_NOT_ALLOWED => 'Method Not Allowed',
        self::CODE_NOT_ACCEPTABLE => 'Not Acceptable',
        self::CODE_PROXY_AUTHENTICATION_REQUIRED => 'Proxy Authentication Required',
        self::CODE_REQUEST_TIMEOUT => 'Request Timeout',
        self::CODE_CONFLICT => 'Conflict',
        self::CODE_GONE => 'Gone',
        self::CODE_LENGTH_REQUIRED => 'Length Required',
        self::CODE_PRECONDITION_FAILED => 'Precondition Failed',
        self::CODE_REQUEST_ENTITY_TOO_LARGE => 'Request Entity Too Large',
        self::CODE_REQUEST_URI_TOO_LONG => 'Request-URI Too Long',
        self::CODE_UNSUPORTED_MEDIA_TYPE => 'Unsupported Media Type',
        self::CODE_REQUESTED_RANGE_NOT_SATISFIABLE => 'Requested Range Not Satisfiable',
        self::CODE_EXPECTATION_FAILED => 'Expectation Failed',
        self::CODE_INTERNAL_SERVER_ERROR => 'Internal Server Error',
        self::CODE_NOT_IMPLEMENTED => 'Not Implemented',
        self::CODE_BAD_GATWAY => 'Bad Gateway',
        self::CODE_SERVICE_UNAVAILABLE => 'Service Unavailable',
        self::CODE_GATEWAY_TIMEOUT => 'Gateway Timeout',
        self::CODE_HTTP_VERSION_NOT_SUPPORTED => 'HTTP Version Not Supported',
        self::CODE_BANDWIDTH_LIMIT_EXCEEDED => 'Bandwidth Limit Exceeded'
    );

    /**
     * Get code message
     *
     * @param int $code
     * @return string
     */
    static public function getMessage($code = self::CODE_INTERNAL_SERVER_ERROR)
    {
        if (isset(self::$messages[$code])) {
            return self::$messages[$code];
        }

        return self::$messages[self::CODE_INTERNAL_SERVER_ERROR];
    }
}