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

namespace cascade\components\db\behaviors;

use cascade\components\helpers\Gravatar;
use canis\base\FileInterface;
use canis\base\RawFile;
use Yii;
use yii\helpers\Url;
use yii\imagine\Image;

/**
 * Photo [[@doctodo class_description:cascade\components\db\behaviors\Photo]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class Photo extends \cascade\components\storageHandlers\StorageBehavior
{
    /**
     * @inheritdoc
     */
    public $storageAttribute = 'photo_storage_id';
    /**
     * @inheritdoc
     */
    public $required = false;

    /**
     * [[@doctodo method_description:badFields]].
     *
     * @return [[@doctodo return_type:badFields]] [[@doctodo return_description:badFields]]
     */
    public function badFields()
    {
        return [$this->storageAttribute];
    }

    /**
     * @inheritdoc
     */
    public function safeAttributes()
    {
        return ['rawPhoto', 'photo'];
    }

    /**
     * Set photo.
     *
     * @param [[@doctodo param_type:photo]] $photo [[@doctodo param_description:photo]]
     *
     * @return [[@doctodo return_type:setPhoto]] [[@doctodo return_description:setPhoto]]
     */
    public function setPhoto($photo)
    {
        return $this->setStorage($photo);
    }

    /**
     * Set raw photo.
     *
     * @param [[@doctodo param_type:photo]] $photo [[@doctodo param_description:photo]]
     *
     * @return [[@doctodo return_type:setRawPhoto]] [[@doctodo return_description:setRawPhoto]]
     */
    public function setRawPhoto($photo)
    {
        if (empty($photo)) {
            return true;
        }
        if (!($photo instanceof FileInterface)) {
            $photo = RawFile::createRawInstance($photo);
        }

        return $this->setStorage($photo);
    }

    /**
     * Get raw photo.
     *
     * @return [[@doctodo return_type:getRawPhoto]] [[@doctodo return_description:getRawPhoto]]
     */
    public function getRawPhoto()
    {
        return $this->getStorage();
    }

    /**
     * Get photo.
     *
     * @return [[@doctodo return_type:getPhoto]] [[@doctodo return_description:getPhoto]]
     */
    public function getPhoto()
    {
        return $this->getStorage();
    }

    /**
     * @inheritdoc
     */
    public function beforeValidate($event)
    {
        if (!parent::beforeValidate($event)) {
            return false;
        }

        return true;
    }

    /**
     * Get photo url.
     *
     * @param integer $size [[@doctodo param_description:size]] [optional]
     *
     * @return [[@doctodo return_type:getPhotoUrl]] [[@doctodo return_description:getPhotoUrl]]
     */
    public function getPhotoUrl($size = 200)
    {
        $storage = $this->storageObject;
        if ($storage) {
            // yay! we have a local image
            return Url::to(['/object/photo', 'id' => $this->owner->primaryKey, 'size' =>  $size]);
        }
        if ($this->owner->photoEmail) {
            $gravatar = new Gravatar();
            if ($gravatar->test($this->owner->photoEmail)) {
                $gravatar->setAvatarSize($size);

                return $gravatar->get($this->owner->photoEmail);
            }
        }

        return false;
    }

    /**
     * @inheritdoc
     */
    public function serve($options = [])
    {
        if (empty($options)) {
            return parent::serve();
        }
        $path = $this->storagePath;
        if (!$path || !file_exists($path)) {
            return false;
        }
        $imagine = Image::getImagine();
        if (!$imagine) {
            return false;
        }
        $cacheKey = ['photo', $path, $options];
        $content = Yii::$app->fileCache->get($cacheKey);
        if (!$content) {
            if (!($image = $imagine->open($path))) {
                return false;
            }
            if (isset($options['rotate'])) {
                $image->rotate($options['rotate']);
            }
            $currentSize = $size = $image->getSize();
            if (isset($options['width']) || isset($options['height'])) {
                if (!isset($options['width'])) {
                    $currentWidth = (int) $currentSize->getWidth();
                    $newHeight = (int) $options['height'];
                    $oldHeight = (int) $currentSize->getHeight();
                    $options['width'] = $currentWidth * ($newHeight/$oldHeight);
                }
                if (!isset($options['height'])) {
                    $currentHeight = (int) $currentSize->getHeight();
                    $newWidth = (int) $options['width'];
                    $oldWidth = (int) $currentSize->getWidth();
                    $options['height'] = $currentHeight * ($newWidth/$oldWidth);
                }
                $size = new \Imagine\Image\Box((int) $options['width'], (int) $options['height']);
            }
            $mode = \Imagine\Image\ImageInterface::THUMBNAIL_OUTBOUND;
            $image = $image->thumbnail($size, $mode);
            $newSize = $image->getSize();
            if ($newSize->getWidth() < $size->getWidth()
                || $newSize->getHeight() < $size->getHeight()) {
                $color = null;
                // $palette = new \Imagine\Image\Palette\RGB;
                // $color = $palette->color('#fff', 100);
                $frameImage = $imagine->create($size, $color);
                $widthCoord = ($size->getWidth() / 2) - ($newSize->getWidth() / 2);
                $heightCoord = ($size->getHeight() / 2) - ($newSize->getHeight() / 2);
                $coord = new \Imagine\Image\Point($widthCoord, $heightCoord);
                $frameImage->paste($image, $coord);
                $image = $frameImage;
            }
            $content = $image->get('png');
            Yii::$app->fileCache->set($cacheKey, $content, 3600, new \yii\caching\FileDependency(['fileName' => $path]));
        }

        if (!$content) {
            return false;
        }
        Yii::$app->response->sendContentAsFile($content, trim($this->storageObject->file_name), 'image/png');

        return true;
    }

    /**
     * Get photo email.
     *
     * @return [[@doctodo return_type:getPhotoEmail]] [[@doctodo return_description:getPhotoEmail]]
     */
    public function getPhotoEmail()
    {
        return false;
    }
}


<?php

namespace Litecms\Forum\Providers;

use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Routing\Router;
use Litecms\Forum\Models\Forum;
use Request;
use Route;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to the controller routes in your routes file.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'Litecms\Forum\Http\Controllers';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @param   \Illuminate\Routing\Router  $router
     * @return void
     */
    public function boot()
    {
        parent::boot();

        if (Request::is('*/forum/category/*')) {
            Route::bind('category', function ($category) {
                $categoryrepo = $this->app->make('Litecms\Forum\Interfaces\CategoryRepositoryInterface');
                return $categoryrepo->findorNew($category);
            });
        }

        if (Request::is('*/forum/question/*')) {
            Route::bind('question', function ($question) {
                $questionrepo = $this->app->make('Litecms\Forum\Interfaces\QuestionRepositoryInterface');
                return $questionrepo->findorNew($question);
            });
        }

        if (Request::is('*/forum/response/*')) {
            Route::bind('response', function ($response) {
                $responserepo = $this->app->make('Litecms\Forum\Interfaces\ResponseRepositoryInterface');
                return $responserepo->findorNew($response);
            });
        }

    }

    /**
     * Define the routes for the package.
     *
     * @return void
     */
    public function map()
    {
        $this->mapWebRoutes();
    }

    /**
     * Define the "web" routes for the package.
     *
     * These routes all receive session state, CSRF protection, etc.
     *
     * @return void
     */
    protected function mapWebRoutes()
    {
        if (request()->segment(1) == 'api' || request()->segment(2) == 'api') {
            return;
        }

        Route::group([
            'middleware' => 'web',
            'namespace'  => $this->namespace,
            'prefix'     => trans_setlocale(),
        ], function ($router) {
            require (__DIR__ . '/../../routes/web.php');
        });
    }

}


<?php
/**
 * BSD 3-Clause License
 *
 * Copyright (c) 2019, TASoft Applications
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 *
 *  Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 *  Neither the name of the copyright holder nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

namespace Skyline\Compiler\Predef;

use Skyline\Compiler\AbstractCompiler;
use Skyline\Compiler\CompilerConfiguration;
use Skyline\Compiler\CompilerContext;
use Skyline\Compiler\Helper\ComposerPackageDependencyCollection;

/**
 * Searches in vendor directories for all composer packages and brings them into the right order, respecting the dependencies
 *
 * @package Skyline\Compiler\Predef
 */
class ComposerPackagesOrderCompiler extends AbstractCompiler
{
    private $jsonCache = [];
    private $files = [];

    private $scanDir = [];
    private $storeLocal = true;

    const CACHE_PACKAGES_NAME = 'ordered-packages';
    const PACKAGES_FILENAME = 'composer-packages.php';

    /**
     * Reads the composer.json file directly or from directory and adds it to cache.
     *
     * @param $fileOrPackage
     * @return mixed|null
     */
    private function getComposer($fileOrPackage) {
        if(isset($this->jsonCache[$fileOrPackage]))
            return $this->jsonCache[$fileOrPackage];

        if($file = $this->files[$fileOrPackage] ?? NULL) {
            return $this->getComposer($file);
        }

        if(is_dir($fileOrPackage))
            $fileOrPackage .= "/composer.json";

        if(is_file($fileOrPackage)) {
            $json = json_decode( file_get_contents($fileOrPackage), true );
            $name = $json["name"];
            $this->jsonCache[$name] = $json;
            $this->files[$name] = $fileOrPackage;
            return $json;
        }
        return NULL;
    }

    /**
     * @inheritDoc
     */
    public function compile(CompilerContext $context)
    {
        $dependencyCollection = new ComposerPackageDependencyCollection();
        $root = $this->getComposer( $this->scanDir );

        $register = function($json, $path) use ($dependencyCollection) {
            $req = array_keys($json["require"] ?? []);
            $dependencyCollection->add($json["name"], $path, $req);
        };

        foreach(($root["repositories"] ?? []) as $rep) {
            if(($rep["type"] ?? NULL) == 'path') {
                $path = realpath($rep["url"]);
                if($path && is_file("$path/composer.json")) {
                    $js = $this->getComposer($path);
                    $register($js, $path);
                }
            }
        }

        foreach($context->getSourceCodeManager()->yieldSourceFiles("/^composer\.json$/i") as $file) {
            $js = $this->getComposer((string)$file);
            $register($js, (string) $file);
        }

        $register($root, $this->scanDir);

        $ordered = $dependencyCollection->getOrderedElements();

        $context->getValueCache()->postValue($ordered, static::CACHE_PACKAGES_NAME);
        if($this->storeLocal) {
            $file = $context->getSkylineAppDirectory( CompilerConfiguration::SKYLINE_DIR_COMPILED ) . "/" . static::PACKAGES_FILENAME;
            $data = var_export($ordered, true);
            file_put_contents($file, "<?php
/**
 *  File generated by Skyline CMS Compiler
 *  (c) Skyline CMS by TASoft Applications
 *  All rights reserved
 *  @license BSD-3-Clause
 */

 return $data;");
        }
    }

    /**
     * ComposerPackagesOrderCompiler constructor.
     * @param string $compilerID
     * @param string|NULL $scanDir
     * @param bool $requireDev
     */
    public function __construct(string $compilerID, string $scanDir = NULL, bool $storeLocal = true)
    {
        parent::__construct($compilerID);
        $this->scanDir = is_dir($scanDir) ? $scanDir : getcwd();
        $this->storeLocal = $storeLocal;
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: lvinkim
 * Date: 24/09/2018
 * Time: 3:24 PM
 */

namespace Lvinkim\SwimKernel;

use Lvinkim\SwimKernel\Component\KernelInterface;
use Lvinkim\SwimKernel\Processor\LoadProcessor;
use Lvinkim\SwimKernel\Processor\RequestProcessor;
use Slim\Container;
use Swoole\Http\Request;
use Swoole\Http\Response;
use Swoole\Table;

class Kernel implements KernelInterface
{
    const VERSION = "v0.1.0";

    private $settings;

    /** @var Container */
    private $container;

    /**
     * KernelInterface constructor.
     * @param array $settings
     */
    public function __construct(array $settings)
    {
        $this->settings = $settings;
    }

    /**
     * 在 onWorkerStart 回调事件中的处理函数
     * @param int $workerId
     * @return mixed|void
     */
    public function dispatchWorkerStart(int $workerId)
    {
        $this->settings["workerId"] = $workerId;

        $loadProcessor = new LoadProcessor();
        $this->container = $loadProcessor->load($this->settings);
    }

    /**
     * 在 onRequest 回调事件中的处理函数
     * @param Request $request
     * @param Response $response
     * @param Table $table
     * @return mixed|void
     */
    public function dispatchRequest(Request $request, Response $response, Table $table)
    {
        $requestProcessor = new RequestProcessor($this->container);
        $actionResponse = $requestProcessor->process($request, $response, $table);

        if (!$actionResponse->isSent()) {
            $response->header("Content-Type", $actionResponse->getContentType());

            $contentBlocks = str_split($actionResponse->getBody(), 2046 * 1024);
            foreach ($contentBlocks as $block) {
                $response->write($block);
            }

            $response->end();
        }
    }

    /**
     * @return Container
     */
    public function getContainer(): Container
    {
        return $this->container;
    }

    /**
     * @return array
     */
    public function getSettings()
    {
        return $this->settings;
    }
}


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

namespace cascade\components\web\themes;

use Yii;

/**
 * Collector [[@doctodo class_description:cascade\components\web\themes\Collector]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class Collector extends \canis\base\collector\Module
{
    /**
     * @var [[@doctodo var_type:initial]] [[@doctodo var_description:initial]]
     */
    public $initial = [];
    /**
     * @var [[@doctodo var_type:_lastLoadedTheme]] [[@doctodo var_description:_lastLoadedTheme]]
     */
    protected $_lastLoadedTheme;
    /**
     * @var [[@doctodo var_type:_theme]] [[@doctodo var_description:_theme]]
     */
    protected $_theme;

    /**
     * @inheritdoc
     */
    public function getCollectorItemClass()
    {
        return 'cascade\components\web\themes\Item';
    }

    /**
     * @inheritdoc
     */
    public function getModulePrefix()
    {
        return 'Theme';
    }

    /**
     * Get theme.
     *
     * @throws Exception [[@doctodo exception_description:Exception]]
     * @return [[@doctodo return_type:getTheme]] [[@doctodo return_description:getTheme]]
     *
     */
    public function getTheme()
    {
        if (!isset($this->_theme)) {
            return $this->_lastLoadedTheme->object;
        }
        if (!isset($this->_theme)) {
            throw new Exception("No theme has been loaded!");
        }

        return $this->_theme;
    }

    /**
     * [[@doctodo method_description:registerAssetBundles]].
     *
     * @param [[@doctodo param_type:view]] $view [[@doctodo param_description:view]]
     */
    public function registerAssetBundles($view)
    {
        foreach ($this->theme->assetBundles as $bundle) {
            $bundle::register($view);
        }
    }

    /**
     * Get identity asset bundle.
     *
     * @return [[@doctodo return_type:getIdentityAssetBundle]] [[@doctodo return_description:getIdentityAssetBundle]]
     */
    public function getIdentityAssetBundle()
    {
        return $this->theme->identityAssetBundle;
    }

    /**
     * @inheritdoc
     */
    public function register($owner, $itemComponent, $systemId = null)
    {
        $item = parent::register($owner, $itemComponent, $systemId);
        $this->_lastLoadedTheme = $item;

        return $item;
    }

    /**
     * Get identity.
     *
     * @param [[@doctodo param_type:view]] $view [[@doctodo param_description:view]]
     *
     * @return [[@doctodo return_type:getIdentity]] [[@doctodo return_description:getIdentity]]
     */
    public function getIdentity($view)
    {
        if (!isset($view->assetBundles[$this->identityAssetBundle])) {
            return false;
        }

        return Yii::$app->assetManager->getBundle($this->identityAssetBundle);
    }
}


<?php

namespace OpenOrchestra\ModelBundle\Validator\Constraints;

use OpenOrchestra\ModelInterface\Model\AutoPublishableInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Class CheckPublishingDateValidator
 */
class CheckPublishingDateValidator extends ConstraintValidator
{
    protected $nodeRepository;

    /**
     * Checks if the passed value is valid.
     *
     * @param AutoPublishableInterface $value The value that should be validated
     * @param Constraint               $constraint The constraint for the validation
     */
    public function validate($value, Constraint $constraint)
    {
        if ($value instanceof AutoPublishableInterface &&
            $value->getPublishDate() instanceof \DateTime &&
            $value->getUnpublishDate() instanceof \DateTime &&
            $value->getPublishDate()->getTimestamp() > $value->getUnpublishDate()->getTimestamp()
        ) {
            $this->context->buildViolation($constraint->message)
                ->atPath('unpublishDate')
                ->addViolation();
        }
    }
}


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

namespace Praxigento\BonusHybrid\Service\Calc\Bonus;

use Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent\Request as AGetPeriodRequest;
use Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent\Response as AGetPeriodResponse;
use Praxigento\BonusBase\Repo\Data\Log\Customers as ELogCust;
use Praxigento\BonusBase\Repo\Data\Log\Opers as ELogOper;
use Praxigento\BonusHybrid\Config as Cfg;

/**
 * Calculate Override Bonus.
 */
class Override
    implements \Praxigento\Core\Api\App\Service\Process
{
    /** Calculation scheme (DEFAULT or EU) */
    const CTX_IN_SCHEME = 'in.scheme';

    /** @var \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Helper\CreateOper */
    private $hlpOper;
    /** @var  \Praxigento\Core\Api\Helper\Period */
    private $hlpPeriod;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Helper\PrepareTrans */
    private $hlpTrans;
    /** @var \Praxigento\Core\Api\App\Logger\Main */
    private $logger;
    /** @var \Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent */
    private $servPeriodGet;
    /** @var \Praxigento\BonusBase\Repo\Dao\Calculation */
    private $daoCalc;
    /** @var \Praxigento\BonusBase\Repo\Dao\Log\Customers */
    private $daoLogCust;
    /** @var \Praxigento\BonusBase\Repo\Dao\Log\Opers */
    private $daoLogOper;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Bonus\Override\Calc */
    private $subCalc;

    public function __construct(
        \Praxigento\Core\Api\App\Logger\Main $logger,
        \Praxigento\Core\Api\Helper\Period $hlpPeriod,
        \Praxigento\BonusBase\Repo\Dao\Calculation $daoCalc,
        \Praxigento\BonusBase\Repo\Dao\Log\Customers $daoLogCust,
        \Praxigento\BonusBase\Repo\Dao\Log\Opers $daoLogOper,
        \Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent $servPeriodGet,
        \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Helper\PrepareTrans $hlpTrans,
        \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Helper\CreateOper $hlpOper,
        \Praxigento\BonusHybrid\Service\Calc\Bonus\Override\Calc $subCalc
    ) {
        $this->logger = $logger;
        $this->hlpPeriod = $hlpPeriod;
        $this->daoCalc = $daoCalc;
        $this->daoLogCust = $daoLogCust;
        $this->daoLogOper = $daoLogOper;
        $this->servPeriodGet = $servPeriodGet;
        $this->hlpTrans = $hlpTrans;
        $this->hlpOper = $hlpOper;
        $this->subCalc = $subCalc;
    }

    public function exec(\Praxigento\Core\Data $ctx)
    {
        /* get working data from context */
        $scheme = $ctx->get(self::CTX_IN_SCHEME) ?? Cfg::SCHEMA_DEFAULT;
        /**
         * perform processing
         */
        $ctx->set(self::CTX_OUT_SUCCESS, false);
        $this->logger->info("Override bonus ('$scheme' scheme) is started.");
        /**
         * get dependent calculation data
         *
         * @var \Praxigento\BonusBase\Repo\Data\Calculation $compressCalc
         * @var \Praxigento\BonusBase\Repo\Data\Calculation $ovrdPeriod
         * @var \Praxigento\BonusBase\Repo\Data\Calculation $ovrdCalc
         */
        list($compressCalc, $ovrdPeriod, $ovrdCalc) = $this->getCalcData($scheme);
        $compressCalcId = $compressCalc->getId();
        $ovrdCalcId = $ovrdCalc->getId();
        /* calculate bonus */
        $bonus = $this->subCalc->exec($compressCalcId, $scheme);
        /* convert calculated bonus to transactions */
        $trans = $this->getTransactions($bonus, $ovrdPeriod);
        /* register bonus operation */
        $operRes = $this->hlpOper->exec(Cfg::CODE_TYPE_OPER_BONUS_OVERRIDE, $trans, $ovrdPeriod);
        $operId = $operRes->getOperationId();
        $transIds = $operRes->getTransactionsIds();
        /* register transactions in log */
        $this->saveLogCustomers($transIds);
        /* register operation in log */
        $this->saveLogOper($operId, $ovrdCalcId);
        /* mark this calculation complete */
        $this->daoCalc->markComplete($ovrdCalcId);
        /* mark process as successful */
        $ctx->set(self::CTX_OUT_SUCCESS, true);
        $this->logger->info("Override bonus ('$scheme' scheme) is completed.");
    }

    /**
     * Get period and calculation data for all related calculation types.
     *
     * @return array [$compressCalc, $ovrdPeriod, $ovrdCalc]
     * @throws \Exception
     */
    private function getCalcData($scheme)
    {
        if ($scheme == Cfg::SCHEMA_EU) {
            $baseTypeCode = Cfg::CODE_TYPE_CALC_COMPRESS_PHASE2_EU;
            $depTypeCode = Cfg::CODE_TYPE_CALC_BONUS_OVERRIDE_EU;
        } else {
            $baseTypeCode = Cfg::CODE_TYPE_CALC_COMPRESS_PHASE2_DEF;
            $depTypeCode = Cfg::CODE_TYPE_CALC_BONUS_OVERRIDE_DEF;
        }
        /**
         * Get period & calc data for Override bonus based on Phase2 Compression.
         */
        $req = new AGetPeriodRequest();
        $req->setBaseCalcTypeCode($baseTypeCode);
        $req->setDepCalcTypeCode($depTypeCode);
        /** @var AGetPeriodResponse $resp */
        $resp = $this->servPeriodGet->exec($req);
        /** @var \Praxigento\BonusBase\Repo\Data\Period $ovrdPeriod */
        $ovrdPeriod = $resp->getDepPeriodData();
        /** @var \Praxigento\BonusBase\Repo\Data\Calculation $ovrdCalc */
        $ovrdCalc = $resp->getDepCalcData();
        /** @var \Praxigento\BonusBase\Repo\Data\Calculation $compressCalc */
        $compressCalc = $resp->getBaseCalcData();
        /**
         * Compose result.
         */
        $result = [$compressCalc, $ovrdPeriod, $ovrdCalc];
        return $result;
    }

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

    /**
     * Save customers log for Team bonus transactions (DEFAULT scheme).
     *
     * @param array $transIds [$transId => $custId]
     */
    private function saveLogCustomers($transIds)
    {
        foreach ($transIds as $transId => $custId) {
            $this->daoLogCust->create([
                ELogCust::A_TRANS_ID => $transId,
                ELogCust::A_CUSTOMER_ID => $custId

            ]);
        }
    }

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

}


<?php

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

use \Attila\lib\Entity  as LibEntity;
use \Venus\lib\Form     as Form;
use VenusPhpdoc\Reader;

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

    /**
     * form library with its entity
     *
     * @access private
     * @var    Form
     */
    private $_oForm = null;

    /**
     * Block the save in the entity if you don't call handleRequest
     *
     * @access private
     * @var    bool
     */
    private $_bHandleRequestActivate = false;

    /**
     * Request of the formular
     *
     * @access private
     * @var    array
     */
    private $_aRequest = null;

    /**
     * @var object
     */
    private $entityObject = null;

    /**
     * get the Value
     *
     * @access public
     * @return \stdClass
     */
    public function createView() : \stdClass
    {
        $oView = new \stdClass;
        $oView->form = $this->_sView;
        $oView->form_start = $this->_oForm->getFormInObject()->start;
        $oView->form_end = $this->_oForm->getFormInObject()->end;
        $oView->form_row = array();

        foreach ($this->_oForm->getFormInObject()->form as $sKey => $mValue) {

            if ($mValue instanceof Container) {

                $oNewForm = $mValue->createView();
                $oView->form_row[$sKey] = $oNewForm->form_row;
            } else {

               $oView->form_row[$sKey] = $mValue;
            }
        }

        return $oView;
    }

    /**
     * set the Value
     *
     * @access public
     * @param  string $sView Display of form;
     * @return \Venus\lib\Form\Container
     */
    public function setView(string $sView) : Container
    {
        $this->_sView = $sView;
        return $this;
    }

    /**
     * handle the request to do many actions on it
     *
     * @access public
     * @param  array $aRequest request like $_POST
     * @return bool
     */
    public function handleRequest(array $aRequest) : bool
    {
        if (!count($_POST)) { return true; }

        // Validation
        foreach ($this->_oForm->getElement() as $sKey => $sValue) {

            if (!$sValue instanceof self && !$this->_validate($sValue)) {

                return false;
            }
        }

        // Save
        if ($this->_oForm->getIdEntity() > 0 && $this->_oForm->getSynchronizeEntity() !== null && count($aRequest) > 0) {

			$entityName = $this->_oForm->getSynchronizeEntity();
			$oEntity = new $entityName;
            $sPrimaryKey = LibEntity::getPrimaryKeyNameWithoutMapping($oEntity);
            $sMethodName = 'set_'.$sPrimaryKey;

            call_user_func_array(array(&$oEntity, $sMethodName), array($this->_oForm->getIdEntity()));

            foreach ($this->_oForm->getElement() as $sKey => $sValue) {

                $sMethodName = 'set_'.$sValue->getName().'';
                if (method_exists($oEntity, $sMethodName)) {
					call_user_func_array(array(&$oEntity, $sMethodName), array($aRequest[$sValue->getName()]));
				}
            }

            $oEntity->save();
        } else if ($this->_oForm->getSynchronizeEntity() !== null && isset($aRequest) && count($aRequest) > 0) {

            $sClassName = $this->_oForm->getSynchronizeEntity();
            $oEntity = new $sClassName;

            foreach ($this->_oForm->getElement() as $sKey => $sValue) {

                if ($sValue->getName()) {
                    $sMethodName = 'set_' . $sValue->getName() . '';

                    if (method_exists($oEntity, $sMethodName)) {

                        $doc = Reader::getPhpDocOfMethod($sClassName, $sMethodName);

                        if ($doc['param'][0][0] === 'int') {
                            $aRequest[$sValue->getName()] = (int)$aRequest[$sValue->getName()];
                        }
                        if ($doc['param'][0][0] === 'string') {
                            $aRequest[$sValue->getName()] = (string)$aRequest[$sValue->getName()];
                        }
                        if ($doc['param'][0][0] === 'float') {
                            $aRequest[$sValue->getName()] = (float)$aRequest[$sValue->getName()];
                        }
                        if ($doc['param'][0][0] === 'bool') {
                            $aRequest[$sValue->getName()] = (bool)$aRequest[$sValue->getName()];
                        }
                        if ($doc['param'][0][0] === 'boolean') {
                            $aRequest[$sValue->getName()] = (bool)$aRequest[$sValue->getName()];
                        }

						call_user_func_array(array(&$oEntity, $sMethodName), array($aRequest[$sValue->getName()]));
                    }
                }
            }

            $idRecord =  $oEntity->save();
            $this->setEntityObject($oEntity);
            $this->_oForm->setIdEntityCreated($idRecord);
        }

        $this->_bHandleRequestActivate = true;
        $this->_aRequest = $aRequest;
        return true;
    }

    /**
     * set Form lib with its entity
     *
     * @access public
     * @param  Form $oForm request like $_POST
     * @return \Venus\lib\Form\Container
     */
    public function setForm(Form $oForm) : Container
    {
        $this->_oForm = $oForm;
        return $this;
    }

    /**
     * if this form is validate and save
     *
     * @access public
     * @return boolean
     */
    public function isValid() : bool
    {
        if ($this->_bHandleRequestActivate === true) { return true; } else { return false; }
    }

    /**
     * if this form is validate and save
     *
     * @access public
     * @return boolean
     */
    public function isSubmitted() : bool
    {
        if (isset($_POST['validform'.$this->_oForm->getFormNumber()]) && $_POST['validform'.$this->_oForm->getFormNumber()] == 1) {

            return true;
        } else {

            return false;
        }
    }

    /**
     * if this form is validate and save
     *
     * @access public
     * @param  string $sElementName element name what we want test the click
     * @return boolean
     */
    public function isClicked(string $sElementName) : bool
    {
        if (isset($_POST[$sElementName]) && $_POST[$sElementName]) { return true; } else { return false; }
    }

    /**
     * if the element is valide or not (with the constraint)
     *
     * @access private
     * @param  object $oElement element of formular
     * @return boolean
     */
    private function _validate($oElement) : bool
    {
        if (is_array($oElement->getConstraint())) {

            foreach ($oElement->getConstraint() as $oConstraint) {

                if (!$oConstraint->validate($_POST[$oElement->getName()])) {

                    return false;
                }
            }
        }

        return true;
    }

    /**
     * @return null
     */
    public function getEntityObject()
    {
        return $this->entityObject;
    }

    /**
     * @param null $entityObject
     */
    public function setEntityObject($entityObject)
    {
        $this->entityObject = $entityObject;
    }
}


<?php

/**
 * MvcCore
 *
 * This source file is subject to the BSD 3 License
 * For the full copyright and license information, please view
 * the LICENSE.md file that are distributed with this source code.
 *
 * @copyright	Copyright (c) 2016 Tom Flídr (https://github.com/mvccore/mvccore)
 * @license		https://mvccore.github.io/docs/mvccore/4.0.0/LICENCE.md
 */

namespace MvcCore\Ext\Routers\ModuleLocalization;

trait Redirect
{
	/**
	 * When request is redirected by router configured behaviour, this method is
	 * called to correct localization URL value in domain params array.
	 * @param array $domainParams
	 * @return void
	 */
	protected function redirectCorrectDomainSystemParams (& $domainParams) {
		$localizationParamName = static::URL_PARAM_LOCALIZATION;
		if (isset($domainParams[$localizationParamName])) {
			$domainParams[$localizationParamName] = $this->redirectLocalizationGetUrlValueAndUnsetGet(
				$domainParams[$localizationParamName]
			);
		}
	}
}


<?php
/**
 * This source file is part of Xloit project.
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the MIT License that is bundled with this package in the file LICENSE.
 * It is also available through the world-wide-web at this URL:
 * <http://www.opensource.org/licenses/mit-license.php>
 * If you did not receive a copy of the license and are unable to obtain it through the world-wide-web,
 * please send an email to <license@xloit.com> so we can send you a copy immediately.
 *
 * @license   MIT
 * @link      http://xloit.com
 * @copyright Copyright (c) 2016, Xloit. All rights reserved.
 */

namespace Xloit\Bridge\Zend\Form\View\Helper;

use Zend\Form\Element\Button;
use Zend\Form\Element\Collection as CollectionElement;
use Zend\Form\ElementInterface;
use Zend\Form\View\Helper\FormCollection as ZendFormCollection;

/**
 * A {@link FormCollection} class.
 *
 * @package Xloit\Bridge\Zend\Form\View\Helper
 */
class FormCollection extends ZendFormCollection
{
    /**
     *
     *
     * @var string
     */
    protected $wrapper = '
%s
%s
%s
';

    /**
     *
     *
     * @var string
     */
    protected $elementWrap = '

%s%s

';

    /**
     * Where shall the template-data be inserted into.
     *
     * @var string
     */
    protected $templateWrapper = '

';

    /**
     *
     *
     * @var string
     */
    protected $horizontalWrapClass = 'col-sm-9 col-md-6';

    /**
     * Form element errors helper instance.
     *
     * @var FormElementErrors
     */
    protected $elementErrorsHelper;

    /**
     *
     *
     * @var array
     */
    protected $hiddenClass = 'hidden';

    /**
     *
     *
     * @var array
     */
    protected $errorClass = 'has-error';

    /**
     * The name of the default view helper that is used to render sub elements.
     *
     * @var string
     */
    protected $defaultElementHelper = 'formElement';

    /**
     * Form label helper instance.
     *
     * @var FormLabel
     */
    protected $labelHelper;

    /**
     * Render a collection by iterating through all fieldset and elements.
     *
     * @param ElementInterface $element
     *
     * @return string
     * @throws \RuntimeException
     * @throws \Zend\Form\Exception\InvalidArgumentException
     */
    public function render(ElementInterface $element)
    {
        $renderer = $this->getView();

        if (!method_exists($renderer, 'plugin')) {
            return '';
        }

        $wrapperClass     = '';
        $elementMarkup    = '';
        $templateMarkup   = '';
        $attributesString = '';
        $label            = '';

        if ($element instanceof CollectionElement && $element->shouldCreateTemplate()) {
            $templateMarkup = $this->renderTemplate($element);
        }

        foreach ($element->getIterator() as $elementOrFieldset) {
            /** @var  ElementInterface $elementOrFieldset */
            $elementMarkup .= $this->renderElement($elementOrFieldset);
        }

        $helperFormButtonIcon = $this->getFormButtonIconHelper();
        $helperLabel          = $this->getLabelHelper();

        $elementMarkup .= sprintf(
            $this->elementWrap,
            '',
            $helperFormButtonIcon(
                new Button(
                    null,
                    [
                        'label' => 'Add New',
                        'icon'  => 'fa fa-plus-circle'
                    ]
                )
            ),
            ''
        );

        if ($this->shouldWrap) {
            $attributes = $element->getAttributes();

            /** @noinspection UnSafeIsSetOverArrayInspection */
            if (isset($attributes['class'])) {
                $wrapperClass = $attributes['class'];

                unset($attributes['class']);
            }

            unset($attributes['name']);

            $attributesString = count($attributes) ? ' ' . $this->createAttributesString($attributes) : '';

            /** @noinspection IsEmptyFunctionUsageInspection */
            if (!empty($element->getLabel())) {
                $label = $helperLabel($element);
            }
        }

        return sprintf(
            $this->wrapper,
            $wrapperClass,
            $attributesString,
            $label,
            $this->horizontalWrapClass,
            $elementMarkup,
            $templateMarkup
        );
    }

    /**
     *
     *
     * @param ElementInterface $element
     *
     * @return string
     * @throws \RuntimeException
     */
    protected function renderElement(ElementInterface $element)
    {
        /** @var $elementHelper Callable */
        $elementHelper = $this->getElementHelper();
        $wrapClass     = '';

        if ($element->getAttribute('type') === $this->hiddenClass) {
            $wrapClass .= $this->hiddenClass;
        }

        $helperElementErrors = $this->getElementErrorsHelper();
        $errorHtml           = $helperElementErrors($element);

        /** @noinspection IsEmptyFunctionUsageInspection */
        if (!empty($errorHtml)) {
            $wrapClass .= ' ' . $this->errorClass;
        }

        return sprintf(
            $this->elementWrap,
            $wrapClass,
            $elementHelper($element),
            $errorHtml
        );
    }

    /**
     * Retrieve the FormButtonIcon helper.
     *
     * @return FormButtonIcon
     */
    protected function getFormButtonIconHelper()
    {
        return new FormButtonIcon();
    }

    /**
     * Retrieve the FormElementErrors helper.
     *
     * @return FormElementErrors
     */
    protected function getElementErrorsHelper()
    {
        if ($this->elementErrorsHelper) {
            return $this->elementErrorsHelper;
        }

        if (method_exists($this->view, 'plugin')) {
            $this->elementErrorsHelper = $this->view->plugin('form_element_errors');
        }

        if (!$this->elementErrorsHelper instanceof FormElementErrors) {
            $this->elementErrorsHelper = new FormElementErrors();
        }

        return $this->elementErrorsHelper;
    }

    /**
     * Retrieve the FormLabel helper.
     *
     * @return FormLabel
     */
    protected function getLabelHelper()
    {
        if ($this->labelHelper) {
            return $this->labelHelper;
        }

        if (method_exists($this->view, 'plugin')) {
            $this->labelHelper = $this->view->plugin('form_label');
        }

        if (!$this->labelHelper instanceof FormLabel) {
            $this->labelHelper = new FormLabel();
        }

        if ($this->hasTranslator()) {
            $this->labelHelper->setTranslator(
                $this->getTranslator(),
                $this->getTranslatorTextDomain()
            );
        }

        return $this->labelHelper;
    }
}


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

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

namespace EasyWeChat\Staff;

use EasyWeChat\Core\AbstractAPI;

/**
 * Class Session.
 */
class Session extends AbstractAPI
{
    const API_CREATE = 'https://api.weixin.qq.com/customservice/kfsession/create';
    const API_CLOSE = 'https://api.weixin.qq.com/customservice/kfsession/close';
    const API_GET = 'https://api.weixin.qq.com/customservice/kfsession/getsession';
    const API_LISTS = 'https://api.weixin.qq.com/customservice/kfsession/getsessionlist';
    const API_WAITERS = 'https://api.weixin.qq.com/customservice/kfsession/getwaitcase';

    /**
     * List all sessions of $account.
     *
     * @param string $account
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function lists($account)
    {
        return $this->parseJSON('get', [self::API_LISTS, ['kf_account' => $account]]);
    }

    /**
     * List all waiters of $account.
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function waiters()
    {
        return $this->parseJSON('get', [self::API_WAITERS]);
    }

    /**
     * Create a session.
     *
     * @param string $account
     * @param string $openId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function create($account, $openId)
    {
        $params = [
                   'kf_account' => $account,
                   'openid' => $openId,
                  ];

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

    /**
     * Close a session.
     *
     * @param string $account
     * @param string $openId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function close($account, $openId)
    {
        $params = [
                   'kf_account' => $account,
                   'openid' => $openId,
                  ];

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

    /**
     * Get a session.
     *
     * @param string $openId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function get($openId)
    {
        return $this->parseJSON('get', [self::API_GET, ['openid' => $openId]]);
    }
}


<?php

/*
 * Chill is a software for social workers
 *
 * Copyright (C) 2014-2015, Champs Libres Cooperative SCRLFS,
 * <http://www.champs-libres.coop>, <info@champs-libres.coop>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

namespace Chill\PersonBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\ExecutionContextInterface;

/**
 * AccompanyingPeriod
 */
class AccompanyingPeriod
{
    /** @var integer */
    private $id;

    /** @var \DateTime */
    private $openingDate;

    /** @var \DateTime */
    private $closingDate;

    /** @var string */
    private $remark = '';

    /** @var \Chill\PersonBundle\Entity\Person */
    private $person;

    /** @var AccompanyingPeriod\ClosingMotive */
    private $closingMotive = null;

    /**
     *
     * @param \DateTime $dateOpening
     * @uses AccompanyingPeriod::setClosingDate()
     */
    public function __construct(\DateTime $dateOpening) {
        $this->setOpeningDate($dateOpening);
    }

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

    /**
     * Set openingDate
     *
     * @param \DateTime $dateOpening
     * @return AccompanyingPeriod
     */
    public function setOpeningDate($openingDate)
    {
        $this->openingDate = $openingDate;

        return $this;
    }

    /**
     * Get openingDate
     *
     * @return \DateTime
     */
    public function getOpeningDate()
    {
        return $this->openingDate;
    }

    /**
     * Set closingDate
     *
     * For closing a Person file, you should use Person::setClosed instead.
     *
     * @param \DateTime $dateClosing
     * @return AccompanyingPeriod
     *
     */
    public function setClosingDate($closingDate)
    {
        $this->closingDate = $closingDate;

        return $this;
    }

    /**
     * Get closingDate
     *
     * @return \DateTime
     */
    public function getClosingDate()
    {
        return $this->closingDate;
    }

    /**
     *
     * @return boolean
     */
    public function isOpen() {
        if ($this->getClosingDate() === null) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Set remark
     *
     * @param string $remark
     * @return AccompanyingPeriod
     */
    public function setRemark($remark)
    {
        if ($remark === null) {
            $remark = '';
        }

        $this->remark = $remark;

        return $this;
    }

    /**
     * Get remark
     *
     * @return string
     */
    public function getRemark()
    {
        return $this->remark;
    }

    /**
     * Set person.
     *
     * For consistency, you should use Person::addAccompanyingPeriod instead.
     *
     * @param \Chill\PersonBundle\Entity\Person $person
     * @return AccompanyingPeriod
     * @see Person::addAccompanyingPeriod
     */
    public function setPerson(\Chill\PersonBundle\Entity\Person $person = null)
    {
        $this->person = $person;

        return $this;
    }

    /**
     * Get person
     *
     * @return \Chill\PersonBundle\Entity\Person
     */
    public function getPerson()
    {
        return $this->person;
    }

    public function getClosingMotive()
    {
        return $this->closingMotive;
    }

    public function setClosingMotive(AccompanyingPeriod\ClosingMotive $closingMotive)
    {
        $this->closingMotive = $closingMotive;
        return $this;
    }

    /// VALIDATION function
    public function isDateConsistent(ExecutionContextInterface $context) {
        if ($this->isOpen()) {
            return;
        }

        if (! $this->isClosingAfterOpening()) {
            $context->addViolationAt('dateClosing',
                'The date of closing is before the date of opening',
                array(), null);
        }
    }

    /**
     * Returns true if the closing date is after the opening date.
     *
     * @return boolean
     */
    public function isClosingAfterOpening() {
        $diff = $this->getOpeningDate()->diff($this->getClosingDate());

        if ($diff->invert === 0) {
            return true;
        } else {
            return false;
        }
    }
}


<?php namespace ZN\Prompt;
/**
 * ZN PHP Web Framework
 *
 * "Simplicity is the ultimate sophistication." ~ Da Vinci
 *
 * @package ZN
 * @license MIT [http://opensource.org/licenses/MIT]
 * @author  Ozan UYKUN [ozan@znframework.com]
 */

use ZN\Config;
use ZN\Singleton;
use ZN\Buffering;

class Processor implements ProcessorInterface
{
    /**
     * @var string
     */
    protected $path;

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

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

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

    /**
     * Magic Constructor
     */
    public function __construct()
    {
        $this->getConfig = Config::default('ZN\Prompt\PromptDefaultConfiguration')::get('Services', 'processor');
        $this->path      = $this->getConfig['path'];
        $this->driver    = $this->getConfig['driver'];
    }

    /**
     * Path
     *
     * @param string $path = NULL
     *
     * @return Processor
     */
    public function path(String $path = NULL)
    {
        $this->path = $path;

        return $this;
    }

    /**
     * Sapi Name
     *
     * @return string
     */
    public function type() : String
    {
        switch( $name = substr($sapi = php_sapi_name(), 0, 3) )
        {
            case 'cli' :
            case 'cgi' : return $name;

            default    : return $sapi;
        }
    }

    /**
     * Execute
     *
     * @param string $command
     *
     * @return string|false
     */
    public function exec($command)
    {
        switch( $this->driver )
        {
            case 'exec':
                $return = exec($command, $this->output, $this->return);
            break;

            case 'shell_exec':
            case 'shell'     :
                $return       = shell_exec($command);
                $this->output = $this->_split($return);
                $this->return = 0;
            break;

            case 'system':
                $return       = Buffering\Callback::do(function() use($command) {system($command, $this->return);});
                $this->output = $this->_split($return);
            break;

            case 'ssh':
                $ssh = Singleton::class('ZN\Remote\SSH');
                $ssh->run($command);
                $this->output = $this->_split($return = $ssh->output());
                $this->return = 0;
            break;
        }

        return $return ?? false;
    }

    /**
     * Select Driver
     *
     * @param string $driver
     *
     * @return Processor
     */
    public function driver(String $driver) : Processor
    {
        $this->driver = $driver;

        return $this;
    }

    /**
     * Output
     *
     * @return array
     */
    public function output() : Array
    {
        return (array) $this->output;
    }

    /**
     * Return
     *
     * @return int
     */
    public function return() : Int
    {
        return (int) $this->return;
    }

    /**
     * Protected Split
     */
    protected function _split($string)
    {
        return explode("\n", rtrim($string, "\n"));
    }

    /**
     * Protected Run
     */
    protected function _run($command)
    {
        $return = $this->exec($command);

        $this->_defaultVariables();

        return $return;
    }

    /**
     * Protected Default Variables
     */
    protected function _defaultVariables()
    {
        $this->path    = NULL;
        $this->driver  = NULL;
    }
}


<?php
/**
 * File ArrayAccessTrait.php
 *
 * @author Edward Pfremmer <epfremme@nerdery.com>
 */
namespace Epfremme\Collection\Traits;

/**
 * Trait ArrayAccessTrait
 *
 * @property array|mixed[] $elements
 * @package Epfremme\Collection\Traits
 */
trait ArrayAccessTrait
{
    /**
     * Test if offset exists in collection
     *
     * @param $offset
     * @return bool
     */
    public function offsetExists($offset)
    {
        return array_key_exists($offset, $this->elements);
    }

    /**
     * Return collection element at $offset
     *
     * @return mixed
     */
    public function offsetGet($offset)
    {
        if (!$this->offsetExists($offset)) {
            throw new \InvalidArgumentException(
                sprintf('Offset %s does not exist in collection', $offset)
            );
        }

        return $this->elements[$offset];
    }

    /**
     * Collection offset to set
     *
     * @param mixed $offset
     * @param mixed $value
     * @return void
     */
    public function offsetSet($offset, $value)
    {
        $this->elements[$offset] = $value;
    }

    /**
     * Collection offset to unset
     *
     * @param mixed $offset
     * @return void
     */
    public function offsetUnset($offset)
    {
        unset($this->elements[$offset]);
    }
}


<?php /** @noinspection PhpParamsInspection */

/**
 * BSD 3-Clause License
 *
 * Copyright (c) 2019, TASoft Applications
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 *
 *  Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 *  Neither the name of the copyright holder nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

namespace Skyline\Compiler\Context\Code;

use Generator;
use RecursiveDirectoryIterator;
use Skyline\Compiler\CompilerConfiguration as CC;
use Skyline\Compiler\CompilerContext;
use Skyline\Compiler\Project\Attribute\SearchPathAttribute;
use SplFileInfo;

class SourceCodeManager
{
    /** @var CompilerContext */
    protected $context;

    /** @var array */
    protected $sourceFiles;
    protected $excludedFiles;

    /**
     * SourceCodeManager constructor.
     * @param CompilerContext $context
     */
    public function __construct(CompilerContext $context)
    {
        $this->context = $context;
    }

    /**
     * @return CompilerContext
     */
    public function getContext(): CompilerContext
    {
        return $this->context;
    }

    /**
     * Yields all source files found in declared directories that match the passed regex.
     * NOTE: The first call takes longer to iterate over all source directories collecting the source files.
     *
     * @param string $fileNameRegex If null, yields all source files
     * @param array $searchPaths Define in which search paths to look for files
     * @return Generator
     */
    public function yieldSourceFiles(string $fileNameRegex = NULL, array $searchPaths = NULL) {
        $loadSearchPathIfNeeded = function($path, $name) {
            if(!isset($this->sourceFiles[$name])) {
                $this->sourceFiles[$name] = [];

                $iterateOverDirectory = function(RecursiveDirectoryIterator $iterator) use (&$iterateOverDirectory) {
                    /** @var SplFileInfo $item */
                    foreach($iterator as $item) {
                        $file = new SourceFile($item);
                        if($this->shouldIncludeFilename($file)) {
                            if($item->isFile())
                                yield (string)$file => $file;
                            elseif($iterator->hasChildren(true)) {
                                yield from $iterateOverDirectory($iterator->getChildren());
                            }
                        } else {
                            $this->excludedFiles[ (string)$file ] = $file;
                        }
                    }
                };

                $iterator = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS | RecursiveDirectoryIterator::FOLLOW_SYMLINKS);

                foreach($iterateOverDirectory($iterator) as $fn => $file) {
                    $this->sourceFiles[$name][$fn] = $file;
                }
            }
        };

        $addSrcDir = function($dirsOrDir, $kind) use (&$sources, $loadSearchPathIfNeeded) {
            $notFound = function($value) {
                trigger_error("Search path $value not found", E_USER_WARNING);
            };

            if(is_array($dirsOrDir)) {
                foreach($dirsOrDir as $ss) {
                    if(is_dir($ss))
                        $loadSearchPathIfNeeded($ss, $kind);
                    else
                        $notFound($ss);
                }
            }
            elseif(is_dir($dirsOrDir))
               $loadSearchPathIfNeeded($dirsOrDir, $kind);
            else
                $notFound($dirsOrDir);
        };

        if(NULL === $searchPaths) {
            $searchPaths = [];

            foreach($this->getDefaultSearchPaths() as $name => $dirsOrDir) {
                if($dirsOrDir)
                    $addSrcDir($dirsOrDir, $name);
                $searchPaths[] = $name;
            }
        } else {
            $defaults = $this->getDefaultSearchPaths();

            foreach($searchPaths as $key => $value) {
                if(is_numeric($key))
                    $key = $value;

                if(isset($defaults[$value])) {
                    $value = $defaults[$value];
                }

                $addSrcDir($value, $key);
            }
        }

        foreach($this->sourceFiles as $bank => $files) {
            if(!in_array($bank, $searchPaths))
                continue;

            foreach($files as $fileName => $file) {
                if(NULL == $fileNameRegex || preg_match($fileNameRegex, basename($fileName)))
                    yield $fileName => $file;
            }
        }
    }

    protected function getDefaultSearchPaths(): array {
        return [
            CC::COMPILER_SOURCE_DIRECTORIES => CC::get($this->getContext()->getConfiguration(), CC::COMPILER_SOURCE_DIRECTORIES),
            SearchPathAttribute::SEARCH_PATH_VENDOR => $this->getContext()->getProjectSearchPaths( SearchPathAttribute::SEARCH_PATH_VENDOR ),
            SearchPathAttribute::SEARCH_PATH_CLASSES => $this->getContext()->getProjectSearchPaths( SearchPathAttribute::SEARCH_PATH_CLASSES )
        ];
    }

    /**
     * Decide if a source file should be used for this compilation or not.
     * NOTE: This method is called for every directory and every file.
     * WARNING: Excluding a directory also excludes all its sub files and directories.
     *
     * @param string $filename
     * @return bool
     */
    protected function shouldIncludeFilename(string $filename): bool {
        return true;
    }
}


<?php

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

/**
 * Manage Cache by Mock -> just for simulate the cache object
 *
 * @category  	lib
 * @package		lib\Cache
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */
class Mock implements CacheInterface
{
    /**
     * get a value
     *
     * @access public
     * @param  string $sName name of the session
     * @param  int $iFlags flags
     * @param  int $iTimeout expiration of cache
     * @return boolean
     */
    public function get(string $sName, int&$iFlags = null, int $iTimeout = 0)
    {
        return false;
    }

    /**
     * set a value
     *
     * @access public
     * @param  string $sName name of the session
     * @param  mixed $mValue value of this sesion var
     * @param  int $iFlag unused
     * @param  int $iExpire expiration of cache
     * @return boolean
     */
    public function set(string $sName, $mValue, int $iFlag = 0, int $iExpire = false)
    {
        return true;
    }

    /**
     * flush the cache
     *
     * @access public
     * @return boolean
     */
    public function flush()
    {
        return false;
    }

    /**
     * delete a value
     *
     * @access public
     * @param  string $sName name of the session
     * @return boolean
     */
    public function delete(string $sName)
    {
        return false;
    }

    /**
     * add
     *
     * @access public
     * @param  string $sName name of the session
     * @param  mixed $mValue value of this sesion var
     * @param  int $iExpire expiration of cache
     * @return boolean
     */
    public function add($sName, $mValue, $iExpire = false)
    {
        return true;
    }
}


<?php namespace ForeverPHP\Routing;

use ForeverPHP\Core\Facades\Settings;
use ForeverPHP\Http\{RedirectResponse, Response};
use ForeverPHP\View\Context;

/**
 * Permite la redireccion con multiples opciones.
 *
 * @author      Daniel Nuñez S. <dnunez@emarva.com>
 * @since 1.0.0
 */
class Redirect {
    /**
     * Redirecciona a una ruta especifica con un estado y encabezado
     * especificos.
     *
     * @param  string  $path
     * @param  integer $status
     * @param  array   $headers
     * @return \ForeverPHP\Http\RedirectResponse
     */
    public function to(string $path, int $status = 301, array $headers = array()) {
        return $this->makeRedirect($path, $status, $headers);
    }

    /**
     * Redirecciona a una ruta segun su nombre asignado.
     *
     * @param  string $name
     * @return \ForeverPHP\Http\RedirectResponse
     */
    public function route(string $name) {
        // Debe construir una ruta segun el nombre de la ruta
    }

    /**
     * Redirecciona a un error, ejemplo un 404.
     *
     * @param  integer $errno
     * @return void
     */
    public function error(int $errno) {
        $response = new Response();

        header("HTTP/1.0 $errno " . $response->getResponseStatus($errno), true, $errno);

        /*
         * Retorna un Response para mostrar el mensaje de que algo salio mal
         * este solo se muestra cuando esta en produccion.         *
         */
        if (!Settings::inDebug()) {
            Settings::set('ForeverPHPTemplate', true);
            $response->render('error', new Context(array('message' => 'Oops, al parecer algo salió mal.')))->make();
        }
    }

    public function makeRedirect(string $path, int $status, array $headers) {
        $redirect = new RedirectResponse($path, $status, $headers);

        return $redirect;
    }
}


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

namespace RedKiteCms\Bridge\Translation;

use Symfony\Component\Translation\TranslatorInterface;

/**
 * This object statically handles the Symfony translator object
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Bridge\Translation
 */
class Translator
{
    /**
     * @type null|TranslatorInterface
     */
    private static $translator = null;

    /**
     * Sets the translator
     *
     * @param TranslatorInterface $translator
     */
    public static function setTranslator(TranslatorInterface $translator)
    {
        self::$translator = $translator;
    }

    /**
     * Translates the given message
     *
     * @param        $message
     * @param array  $parameters
     * @param string $domain
     * @param null   $locale
     * @return string
     */
    public static function translate($message, $parameters = array(), $domain = "RedKiteCms", $locale = null)
    {
        if (null === self::$translator) {
            return $message;
        }

        return self::$translator->trans($message, $parameters, $domain, $locale);
    }
}


<?php
namespace eMacros\Runtime\Builder;

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

class ObjectBuilder implements Applicable {
	/**
	 * Creates a new instance from a symbol
	 * Usage: (new ArrayObject (array 1 2 3))
	 * Returns: object
	 * (non-PHPdoc)
	 * @see \eMacros\Applicable::apply()
	 */
	public function apply(Scope $scope, GenericList $arguments) {
		if (count($arguments) == 0) throw new \BadFunctionCallException("ObjectBuilder: No arguments found.");
		$class = $arguments[0];
		if (!($class instanceof Symbol))
			throw new \InvalidArgumentException(sprintf("ObjectBuilder: Expected symbol as first argument but %s was found instead.", substr(strtolower(strstr(get_class($arguments[0]), '\\')), 1)));
		$class = $class->symbol;
		//get additional arguments
		$list = array_slice($arguments->getArrayCopy(), 1);
		$args = [];
		//build constructor parameters
		foreach ($list as $el)
			$args[] = $el->evaluate($scope);
		$rc = new \ReflectionClass($class);
		return empty($args) ? $rc->newInstance() : $rc->newInstanceArgs($args);
	}
}
?>


<?php

namespace CvoTechnologies\StreamEmulation\Emulator;

use GuzzleHttp\Psr7\Request;

class HttpEmulator extends Emulator
{
    protected $response;

    /**
     * {@inheritDoc}
     */
    public function getIncomingStream()
    {
        $options = stream_context_get_options($this->context);

        $method = 'GET';
        if (isset($options['http']['method'])) {
            $method = $options['http']['method'];
        }
        $headers = [];
        if (isset($options['http']['header'])) {
            $headerLines = explode("\r\n", $options['http']['header']);
            foreach ($headerLines as $headerLine) {
                if (!$headerLine) {
                    continue;
                }

                list($header, $value) = explode(': ', $headerLine, 2);

                $headers[$header][] = $value;
            }
        }
        $body = null;
        if (isset($options['http']['content'])) {
            $body = $options['http']['content'];
        }
        $protocolVersion = 1.1;
        if (isset($options['http']['protocol_version'])) {
            $protocolVersion = $options['http']['protocol_version'];
        }

        $request = new Request($method, $this->path, $headers, $body, $protocolVersion);

        return \GuzzleHttp\Psr7\stream_for(\GuzzleHttp\Psr7\str($request));
    }

    /**
     * {@inheritDoc}
     */
    public function getOutgoingStream()
    {
        return $this->getResponse()->getBody();
    }

    /**
     * Get the HTTP response object.
     *
     * @return \Psr\Http\Message\ResponseInterface The response as object.
     */
    public function getResponse()
    {
        if ($this->response) {
            return $this->response;
        }

        return $this->response = \GuzzleHttp\Psr7\parse_response($this->getResponseStream());
    }

    /**
     * Whether a offset exists.
     * @link http://php.net/manual/en/arrayaccess.offsetexists.php
     * @param mixed $offset

     * An offset to check for.
     *

     * @return bool true on success or false on failure.
     *

     *

     * The return value will be casted to boolean if non-boolean was returned.
     * @since 5.0.0
     */
    public function offsetExists($offset)
    {
        return in_array($offset, ['headers']);
    }

    /**
     * Offset to retrieve.
     * @link http://php.net/manual/en/arrayaccess.offsetget.php
     * @param mixed $offset

     * The offset to retrieve.
     *

     * @return mixed Can return all value types.
     * @since 5.0.0
     */
    public function offsetGet($offset)
    {
        if ($offset === 'headers') {
            $headers = [
                'HTTP/' . $this->getResponse()->getProtocolVersion() . ' ' . $this->getResponse()->getStatusCode() . ' ' . $this->getResponse()->getReasonPhrase()
            ];
            foreach ($this->getResponse()->getHeaders() as $header => $values) {
                foreach ($values as $value) {
                    $headers[] = $header . ': ' . $value;
                }
            }

            return $headers;
        }
    }

    /**
     * Offset to set.
     * @link http://php.net/manual/en/arrayaccess.offsetset.php
     * @param mixed $offset

     * The offset to assign the value to.
     *

     * @param mixed $value

     * The value to set.
     *

     * @return void
     * @since 5.0.0
     */
    public function offsetSet($offset, $value)
    {
    }

    /**
     * Offset to unset.
     * @link http://php.net/manual/en/arrayaccess.offsetunset.php
     * @param mixed $offset

     * The offset to unset.
     *

     * @return void
     * @since 5.0.0
     */
    public function offsetUnset($offset)
    {
    }
}


<?php

/**
 * ItePHP: Framework PHP (http://itephp.com)
 * Copyright (c) NewClass (http://newclass.pl)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the file LICENSE
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) NewClass (http://newclass.pl)
 * @link          http://itephp.com ItePHP Project
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace ItePHP\Core;

/**
 * Presenter for http error.
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
class HTTPErrorPresenter implements Presenter{

    /**
     * @var Environment
     */
    private $environment;

    /**
     * HTTPErrorPresenter constructor.
     * @param Environment $environment
     */
    public function __construct(Environment $environment){
        $this->environment=$environment;
    }

    /**
     * {@inheritdoc}
     */
	public function render(Request $request , Response $response){
	    if(!$this->environment->isSilent()){
            header('HTTP/1.1 '.$response->getStatusCode().' '.$response->getStatusMessage());
            foreach($response->getHeaders() as $name=>$value){
                header($name.': '.$value);
            }
        }

		echo $this->createTemplate($response);
	}

    /**
     *
     * @param Response $response
     * @return string
     */
	private function createTemplate($response){
		$content=$response->getContent();
		if($content instanceof \Exception){
			$templateContent=$this->createExceptionContent($content);
		}
		else{
			$templateContent=$this->createObjectContent($content);

		}
		$template='<!DOCTYPE html>

			'.
				$templateContent
			.'

			';

		return $template;

	}

    /**
     *
     * @param \Exception $exception
     * @return string
     */
	private function createExceptionContent(\Exception $exception){
		$template='

'.get_class($exception).'

'.$exception->getMessage().'

'.$exception->getFile().'

'.$exception->getLine().'

		';

		return $template;
	}

    /**
     *
     * @param mixed $content
     * @return string
     */
	private function createObjectContent($content){
		$template='

'.gettype($content).'

'.(string)$content.'

		';

		return $template;
	}

}


<?php

declare(strict_types=1);

namespace Ruwork\Reminder\Item;

final class LazyItem implements ClearableItemInterface
{
    private $id;
    private $initializer;
    private $clear;
    private $initialized = false;
    private $value;

    public function __construct(string $id, callable $initializer, ?callable $clear = null)
    {
        $this->id = $id;
        $this->initializer = $initializer;
        $this->clear = $clear;
    }

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

    /**
     * {@inheritdoc}
     */
    public function getData()
    {
        if (!$this->initialized) {
            $this->value = ($this->initializer)($this->id);
            $this->initialized = true;
        }

        return $this->value;
    }

    /**
     * {@inheritdoc}
     */
    public function clear(): void
    {
        if (null !== $this->clear && $this->initialized) {
            ($this->clear)($this->id, $this->value);
        }
    }
}


<?php

namespace Bridge\HttpApi\Action;

use Bridge\Action\ProceduralAction;
use Bridge\HttpApi\Adapter\HttpApiAdapter;
use Bridge\HttpApi\Worker\SerializationWorker;
use Bridge\HttpApi\Worker\VirtualizationWorker;
use Bridge\Registry;
use Bridge\RegistryAwareInterface;
use Transfer\Adapter\CacheAdapter;
use Transfer\Adapter\Transaction\Request;
use Transfer\Adapter\CallbackAdapter;

class HttpApiAction extends ProceduralAction implements RegistryAwareInterface
{
    /**
     * @var array Source configuration
     */
    private $source;

    /**
     * @var array Deserialization configuration
     */
    private $deserialization;

    /**
     * @var array Virtual properties
     */
    private $virtualProperties;

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

    /**
     * @param string $name    HTTP API Action name
     * @param array  $options Action options
     */
    public function __construct($name, array $options = array())
    {
        parent::__construct($name);

        $this->source = isset($options['source']) ? $options['source'] : null;
        $this->deserialization = isset($options['deserialization']) ? $options['deserialization'] : null;
        $this->virtualProperties = isset($options['virtual_properties']) ? $options['virtual_properties'] : null;

        $this->deserialization['multiple'] = (boolean) strpos($this->deserialization['type'], '[]');
        if ($this->deserialization['multiple']) {
            $matches = array();
            preg_match('/(.+)\[\]/', $this->deserialization['type'], $matches);

            if (isset($matches[1])) {
                $this->deserialization['single_type'] = $matches[1];
            } else {
                throw new \Exception(sprintf(
                    'Could not extract single type from "%s"',
                    $this->deserialization['type'])
                );
            }
        } else {
            $this->deserialization['single_type'] = $this->deserialization['type'];
        }
    }

    /**
     * @param Registry $registry
     */
    public function setRegistry(Registry $registry)
    {
        $this->registry = $registry;
    }

    /**
     * {@inheritdoc}
     */
    public function execute(array $arguments = array())
    {
        if ($this->source) {
            $this->addSource($arguments);
        }

        if ($this->deserialization) {
            $this->addSerializationWorker();
        }

        if (isset($this->deserialization['multiple']) && $this->deserialization['multiple']) {
            $this->builder->split();
        }

        if ($this->virtualProperties) {
            $this->addVirtualizationWorker($arguments);
        }

        $response = parent::execute($arguments);

        if (isset($this->deserialization['multiple']) && $this->deserialization['multiple']) {
            return $response->getIterator();
        } else {
            return $response->getIterator()->current();
        }
    }

    /**
     * Adds source adapter.
     *
     * @param array $arguments
     */
    private function addSource(array $arguments = array())
    {
        $this->builder->addSource(
            array_key_exists('cache', $this->source) ? $this->createCacheAdapter() : new HttpApiAdapter(),
            new Request(array(
                'source' => $this->source,
                'arguments' => $arguments,
                'service' => $this->getGroup()->getService()->getName(),
                'group' => $this->getGroup()->getName(),
                'action' => $this->getName(),
            )));
    }

    /**
     * Adds serialization worker.
     */
    private function addSerializationWorker()
    {
        $this->builder->addWorker(new SerializationWorker($this->deserialization, $this->source));
    }

    /**
     * Adds virtualization worker.
     *
     * @param array $arguments
     */
    private function addVirtualizationWorker($arguments = array())
    {
        $this->builder->addWorker(new VirtualizationWorker(
            $this->registry,
            $this->virtualProperties,
            $this->deserialization,
            $arguments
        ));
    }

    /**
     * Returns cache adapter.
     *
     * @return CallbackAdapter Cache adapter
     */
    private function createCacheAdapter()
    {
        $extraData = &$this->extraData;

        return new CallbackAdapter(function (Request $request) use (&$extraData) {

            $poolName = 'default';

            if (isset($this->source['cache']['pool'])) {
                $poolName = $this->source['cache']['pool'];
            }

            $adapter = new CacheAdapter(
                $this->registry->getCachePool($poolName),
                new HttpApiAdapter(),
                function (Request $request) {
                    $data = $request->getData();

                    return $this->registry->generateCacheItemKey(
                        sprintf('%s.%s.%s', $data['service'], $data['group'], $data['action']),
                        $data['arguments']
                    );
                }
            );

            $response = $adapter->receive($request);

            $extraData = $response->getHeaders();

            return $response;
        });
    }
}


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

/**
 * Authorizer.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    lixiao <leonlx126@gmail.com>
 * @author    mingyoung <mingyoungcheung@gmail.com>
 * @copyright 2016
 *
 * @see      https://github.com/overtrue
 * @see      http://overtrue.me
 */

namespace EasyWeChat\OpenPlatform;

use Doctrine\Common\Cache\Cache;
use EasyWeChat\Core\Exception;
use EasyWeChat\OpenPlatform\Api\BaseApi;

class Authorizer
{
    const CACHE_KEY_ACCESS_TOKEN = 'easywechat.open_platform.authorizer_access_token';
    const CACHE_KEY_REFRESH_TOKEN = 'easywechat.open_platform.authorizer_refresh_token';

    /**
     * Cache.
     *
     * @var \Doctrine\Common\Cache\Cache
     */
    protected $cache;

    /**
     * Base API.
     *
     * @var \EasyWeChat\OpenPlatform\Api\BaseApi
     */
    protected $api;

    /**
     * Authorizer AppId.
     *
     * @var string
     */
    protected $appId;

    /**
     * OpenPlatform AppId.
     *
     * @var string
     */
    protected $openPlatformAppId;

    /**
     * Authorizer Constructor.
     *
     * @param \EasyWeChat\OpenPlatform\Api\BaseApi $api
     * @param string                               $openPlatformAppId OpenPlatform AppId
     * @param \Doctrine\Common\Cache\Cache         $cache
     */
    public function __construct(BaseApi $api, $openPlatformAppId, Cache $cache)
    {
        $this->api = $api;
        $this->openPlatformAppId = $openPlatformAppId;
        $this->cache = $cache;
    }

    /**
     * Gets the base api.
     *
     * @return \EasyWeChat\OpenPlatform\Api\BaseApi
     */
    public function getApi()
    {
        return $this->api;
    }

    /**
     * Sets the authorizer app id.
     *
     * @param string $appId
     *
     * @return $this
     */
    public function setAppId($appId)
    {
        $this->appId = $appId;

        return $this;
    }

    /**
     * Gets the authorizer app id, or throws if not found.
     *
     * @return string
     *
     * @throws \EasyWeChat\Core\Exception
     */
    public function getAppId()
    {
        if (!$this->appId) {
            throw new Exception(
                'Authorizer App Id is not present, you may not make the authorizer yet.'
            );
        }

        return $this->appId;
    }

    /**
     * Saves the authorizer access token in cache.
     *
     * @param string $token
     * @param int    $expires
     *
     * @return $this
     */
    public function setAccessToken($token, $expires = 7200)
    {
        $this->cache->save($this->getAccessTokenCacheKey(), $token, $expires);

        return $this;
    }

    /**
     * Gets the authorizer access token.
     *
     * @return string
     */
    public function getAccessToken()
    {
        return $this->cache->fetch($this->getAccessTokenCacheKey());
    }

    /**
     * Saves the authorizer refresh token in cache.
     *
     * @param string $refreshToken
     *
     * @return $this
     */
    public function setRefreshToken($refreshToken)
    {
        $this->cache->save($this->getRefreshTokenCacheKey(), $refreshToken);

        return $this;
    }

    /**
     * Gets the authorizer refresh token.
     *
     * @return string
     *
     * @throws \EasyWeChat\Core\Exception when refresh token is not present
     */
    public function getRefreshToken()
    {
        if ($token = $this->cache->fetch($this->getRefreshTokenCacheKey())) {
            return $token;
        }

        throw new Exception(
            'Authorizer Refresh Token is not present, you may not make the authorizer yet.'
        );
    }

    /**
     * Gets the authorizer access token cache key.
     *
     * @return string
     */
    public function getAccessTokenCacheKey()
    {
        return self::CACHE_KEY_ACCESS_TOKEN.$this->appId.$this->getAppId();
    }

    /**
     * Gets the authorizer refresh token cache key.
     *
     * @return string
     */
    public function getRefreshTokenCacheKey()
    {
        return self::CACHE_KEY_REFRESH_TOKEN.$this->appId.$this->getAppId();
    }
}


<?php

namespace SetBased\Helper\CodeStore;

/**
 * A helper class for automatically generating MySQL compound syntax code with proper indentation.
 */
class MySqlCompoundSyntaxCodeStore extends CodeStore
{
  //--------------------------------------------------------------------------------------------------------------------
  /**
   * {@inheritdoc}
   */
  protected function indentationMode(string $line): int
  {
    $mode = 0;

    $line = trim($line);

    if (substr($line, 0, 5)=='begin' || substr($line, 0, 2)=='if' || substr($line, -4, 4)=='loop')
    {
      $mode |= self::C_INDENT_INCREMENT_AFTER;
    }

    if (substr($line, 0, 3)=='end')
    {
      $mode |= self::C_INDENT_DECREMENT_BEFORE;
    }

    return $mode;
  }

  //--------------------------------------------------------------------------------------------------------------------
}

//----------------------------------------------------------------------------------------------------------------------


<?php
namespace Lab123\Odin\Traits;

use Lab123\Odin\Requests\FilterRequest;
use Lab123\Odin\Libs\Api;
use App;
use DB;

trait ApiActions
{

    /**
     * Class Fields Manage.
     *
     * @var $fieldManager
     */
    protected $fieldManager = '';

    /**
     * Define resource is List to return full data
     *
     * @var boolean $list
     */
    protected $list = false;

    /**
     * Display a listing of the resource.
     * paginate
     *
     * @return \Illuminate\Http\Response
     */
    public function index(FilterRequest $request)
    {
        $limit = $request->request->get('limit', 15);
        $limit = ($limit > 49) ? 50 : $limit;

        $filter = $this->repository->filter($request);

        if ($this->list || $request->request->get('search_type') == 'list') {
            $resources = $filter->get(1000);
        } else {
            $resources = $filter->paginate($limit);
        }

        if ($resources->count() < 1) {
            // return $this->notFound();
        }

        return $this->success($resources);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function lists(FilterRequest $request)
    {
        $resources = $this->repository->filter($request)->get();

        if ($resources->count() < 1) {
            // return $this->notFound();
        }

        return $this->success($resources);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function autocomplete(FilterRequest $request)
    {
        $this->fieldManager = $this->getFieldManager();
        $this->validate($request->request, $this->fieldManager->autocomplete());

        $text = $request->request->get('text');

        $resources = $this->repository->filter($request)->autocomplete($text)->get();

        if ($resources->count() < 1) {
            // return $this->notFound();
        }

        return $this->success($resources);
    }

    /**
     * Display one resource by id.
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id, FilterRequest $request)
    {
        $id = $this->getRealId($id);

        $request->criteria[] = 'id,=,' . $id;

        $resource = $this->repository->filter($request)->first();

        //$resource = $this->repository->find($id);

        if (! $resource) {
            // return $this->notFound();
        }

        return $this->success($resource);
    }

    /**
     * Create and display the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(FilterRequest $request)
    {
        $this->fieldManager = $this->getFieldManager();
        $this->validate($request->request, $this->fieldManager->store());

        $input = $request->all();

        $resource = $this->repository->create($input);

        if (! $resource) {
            // return $this->notFound();
        }

        return $this->created($resource);
    }

    /**
     * Update and display the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function update(FilterRequest $request, $id)
    {
        $this->fieldManager = $this->getFieldManager();
        $this->validate($request->request, $this->fieldManager->update());

        $id = $this->getRealId($id);

        $resource = $this->repository->update($request->all(), $id);

        if (! $resource) {
            // return $this->notFound();
        }

        return $this->success($resource);
    }

    /**
     * Delete a resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $id = $this->getRealId($id);

        $resource = $this->repository->find($id);

        if (! $resource) {
            return $this->notFound();
        }

        $result = $resource->delete();

        return $this->success($result);
    }

    /**
     * Return instance Field Manager of controller
     *
     * @return object Lab123\Odin\FieldManager
     */
    protected function getFieldManager()
    {
        /* Verifica se existe Field Manager com prefixo igual a controller */
        if (! $this->fieldManager) {
        	$this->fieldManager = $this->repository->getFieldManager();
        }

        /* Ainda precisa instanciar o objeto */
        if (is_string($this->fieldManager)) {
            return new $this->fieldManager();
        }

        /* Objeto já instanciado, só retornar */
        return $this->fieldManager;
    }
}


<?php

namespace OpenOrchestra\ModelBundle\Repository;

use OpenOrchestra\ModelInterface\Model\SiteInterface;
use OpenOrchestra\ModelInterface\Repository\SiteRepositoryInterface;
use OpenOrchestra\Pagination\Configuration\PaginateFinderConfiguration;
use OpenOrchestra\Repository\AbstractAggregateRepository;
use Solution\MongoAggregation\Pipeline\Stage;

/**
 * Class SiteRepository
 */
class SiteRepository extends AbstractAggregateRepository implements SiteRepositoryInterface
{
    /**
     * @param string $siteId
     *
     * @return SiteInterface
     */
    public function findOneBySiteId($siteId)
    {
        return $this->findOneBy(array('siteId' => $siteId));
    }

    /**
     * @param array $sitesIds
     *
     * @return array
     */
    public function findBySiteIds(array $sitesIds)
    {
        return parent::findBy(
            array(
                'siteId' => array('$in' => $sitesIds),
                'deleted' => false
            )
        );
    }

    /**
     * @param boolean $deleted
     *
     * @return array
     */
    public function findByDeleted($deleted)
    {
        return $this->findBy(array('deleted' => $deleted));
    }

    /**
     * @param string $domain
     *
     * @return \Doctrine\ODM\MongoDB\Cursor
     */
    public function findByAliasDomain($domain)
    {
        $database = $this->dm->getDocumentDatabase($this->documentName);
        $collectionName = $this->dm->getClassMetadata($this->documentName)->collection;

        $map = new \MongoCode(
            'function(){
                for (var i in this.aliases) {
                    if (this.aliases[i].domain == domain) {
                        emit(this.siteId, this.siteId);
                    }
                }
            }'
        );
        $reduce = new \MongoCode("function(key, values) { return values[0]; }");

        $commandResult = $database->command(array(
            "mapreduce" => $collectionName,
            "map" => $map,
            "reduce" => $reduce,
            "out" => array("inline" => 1),
            "scope" => array(
                "domain" => "$domain"
            )
        ));

        $ids = array();
        if (is_array($commandResult) && array_key_exists('ok', $commandResult) && $commandResult['ok'] == 1) {
            foreach ($commandResult['results'] as $siteId) {
                $ids[] = $siteId['_id'];
            }
        }

        $qb = $this->createQueryBuilder();
        $qb->field('siteId')->in($ids);

        return $qb->getQuery()->execute();
    }

    /**
     * @param PaginateFinderConfiguration $configuration
     * @param array|null                  $siteIds
     *
     * @return array
     */
    public function findForPaginateFilterBySiteIds(PaginateFinderConfiguration $configuration, array $siteIds = null)
    {
        $qa = $this->createAggregateQueryWithDeletedFilter(false);
        if (null !== $siteIds) {
            $qa->match(array('siteId' => array('$in' => $siteIds)));
        }

        $this->filterSearch($configuration, $qa);

        $order = $configuration->getOrder();
        if (!empty($order)) {
            $qa->sort($order);
        }

        $qa->skip($configuration->getSkip());
        $qa->limit($configuration->getLimit());

        return $this->hydrateAggregateQuery($qa);
    }

    /**
     * @param array|null $siteIds
     *
     * @return int
     */
    public function countFilterBySiteIds(array $siteIds = null)
    {
        $qa = $this->createAggregateQueryWithDeletedFilter(false);
        if (null !== $siteIds) {
            $qa->match(array('siteId' => array('$in' => $siteIds)));
        }

        return $this->countDocumentAggregateQuery($qa);
    }

    /**
     * @param PaginateFinderConfiguration $configuration
     * @param array|null                  $siteIds
     *
     * @return int
     */
    public function countWithFilterAndSiteIds(PaginateFinderConfiguration $configuration, array $siteIds = null)
    {
        $qa = $this->createAggregateQueryWithDeletedFilter(false);
        if (null !== $siteIds) {
            $qa->match(array('siteId' => array('$in' => $siteIds)));
        }
        $this->filterSearch($configuration, $qa);

        return $this->countDocumentAggregateQuery($qa);
    }

    /**
     * @param PaginateFinderConfiguration $configuration
     * @param Stage                       $qa
     *
     * @return array
     */
    protected function filterSearch(PaginateFinderConfiguration $configuration, Stage $qa)
    {
        $search = $configuration->getSearchIndex('name');
        if (null !== $search && $search !== '') {
            $qa->match(array('name' => new \MongoRegex('/.*'.$search.'.*/i')));
        }

        return $qa;
    }

    /**
     * @param $deleted
     *
     * @return \Solution\MongoAggregation\Pipeline\Stage
     */
    protected function createAggregateQueryWithDeletedFilter($deleted)
    {
        $qa = $this->createAggregationQuery();
        $qa->match(array('deleted' => $deleted));

        return $qa;
    }
}