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

namespace Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress;

use Praxigento\BonusHybrid\Config as Cfg;
use Praxigento\BonusHybrid\Repo\Data\Cfg\Param as ECfgParam;
use Praxigento\BonusHybrid\Repo\Data\Compression\Phase2\Legs as ELegs;
use Praxigento\BonusHybrid\Repo\Data\Downline as EBonDwnl;
use Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase2\Data\Legs as DLegs;
use Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase2\Fun\Act\Qualify as ActQualify;
use Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase2\Fun\Rou\CalcLegs as RouCalcLegs;
use Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase2\Fun\Rou\ComposeLegs as RouComposeLegs;

/**
 * Process to calculate Phase2 compression.
 */
class Phase2
    implements \Praxigento\Core\Api\App\Service\Process
{
    /** int */
    const IN_CALC_ID_PHASE2 = 'calcIdPhase2';
    /** Phase1 compressed downline  */
    const IN_DWNL_PHASE1 = 'dwnlPhase1';
    /** Plain downline */
    const IN_DWNL_PLAIN = 'dwnlPlain';
    /** array none-compressed PV by customer ID */
    const IN_MAP_PV = 'mapPV';
    /** string Scheme code (see \Praxigento\BonusHybrid\Config::SCHEMA_XXX) */
    const IN_SCHEME = 'scheme';
    /** \Praxigento\BonusHybrid\Repo\Data\Downline[] */
    const OUT_DWNL_PHASE2 = 'dwnlPhase2';
    /** \Praxigento\BonusHybrid\Repo\Data\Compression\Phase2\Legs[] */
    const OUT_LEGS = 'legs';
    /** @var \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase2\Fun\Act\Qualify */
    private $actQualify;
    /** @var \Praxigento\Downline\Api\Helper\Tree */
    private $hlpTree;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase2\IsQualified */
    private $hlpIsQualified;
    /** @var \Praxigento\BonusHybrid\Api\Helper\Scheme */
    private $hlpScheme;
    /** @var \Praxigento\BonusHybrid\Repo\Dao\Downline */
    private $daoBonDwnl;
    /** @var \Praxigento\BonusHybrid\Repo\Dao\Cfg\Param */
    private $daoCfgParam;
    /** @var \Praxigento\BonusBase\Repo\Dao\Rank */
    private $daoRank;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase2\Fun\Rou\CalcLegs */
    private $rouCalcLegs;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase2\Fun\Rou\ComposeLegs */
    private $rouComposeLegs;

    public function __construct(
        \Praxigento\Downline\Api\Helper\Tree $hlpTree,
        \Praxigento\BonusHybrid\Api\Helper\Scheme $hlpScheme,
        \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase2\IsQualified $hlpIsQualified,
        \Praxigento\BonusBase\Repo\Dao\Rank $daoRank,
        \Praxigento\BonusHybrid\Repo\Dao\Cfg\Param $daoCfgParam,
        \Praxigento\BonusHybrid\Repo\Dao\Downline $daoBonDwnl,
        ActQualify $actQualify,
        RouCalcLegs $rouCalcLegs,
        RouComposeLegs $rouComposeLegs
    )
    {
        $this->hlpTree = $hlpTree;
        $this->hlpScheme = $hlpScheme;
        $this->hlpIsQualified = $hlpIsQualified;
        $this->daoRank = $daoRank;
        $this->daoCfgParam = $daoCfgParam;
        $this->daoBonDwnl = $daoBonDwnl;
        $this->actQualify = $actQualify;
        $this->rouCalcLegs = $rouCalcLegs;
        $this->rouComposeLegs = $rouComposeLegs;
    }

    public function exec(\Praxigento\Core\Data $ctx)
    {
        /* get working data from input */
        $phase2CalcId = $ctx->get(self::IN_CALC_ID_PHASE2);
        $dwnlCompress = $ctx->get(self::IN_DWNL_PHASE1);
        $dwnlPlain = $ctx->get(self::IN_DWNL_PLAIN);
        $mapPv = $ctx->get(self::IN_MAP_PV);
        $scheme = $ctx->get(self::IN_SCHEME);

        /* define local working data */
        $cfgParams = $this->getCfgParams();

        /* prepare output vars */
        $outDownline = [];
        $outLegs = [];

        /**
         * perform processing
         */
        $mapByIdCompress = $this->hlpTree->mapById($dwnlCompress, EBonDwnl::A_CUST_REF);
        $mapByTeamCompress = $this->hlpTree->mapByTeams($dwnlCompress, EBonDwnl::A_CUST_REF, EBonDwnl::A_PARENT_REF);
        $mapByDepthCompress = $this->hlpTree->mapByTreeDepthDesc($dwnlCompress, EBonDwnl::A_CUST_REF, EBonDwnl::A_DEPTH);
        $mapByIdPlain = $this->hlpTree->mapById($dwnlPlain, EBonDwnl::A_CUST_REF);
        $mapByTeamPlain = $this->hlpTree->mapByTeams($dwnlPlain, EBonDwnl::A_CUST_REF, EBonDwnl::A_PARENT_REF);
        $rankIdMgr = $this->daoRank->getIdByCode(Cfg::RANK_MANAGER);
        /* MOBI-629: add init rank for un-ranked entries ('distributor' is the minimal rank in compressed trees) */
        $rankIdDistr = $this->daoRank->getIdByCode(Cfg::RANK_DISTRIBUTOR);;
        /* run though the compressed tree from bottom to top and collect OV */
        foreach ($mapByDepthCompress as $level) {
            foreach ($level as $custId) {
                /* prepare results entries */
                $entryDwnl = new EBonDwnl();
                /* get compressed data and compose downline item */
                /** @var EBonDwnl $custData */
                $custData = $mapByIdCompress[$custId];
                $parentId = $custData->getParentRef();
                $pvOwn = $mapPv[$custId] ?? 0;
                $pvCompress = $custData->getPv();
                $tvCompress = $custData->getTv();
                $ovCompress = $custData->getOv();
                /* populate downline result entry with data */
                $entryDwnl->setCalculationRef($phase2CalcId);
                $entryDwnl->setCustomerRef($custId);
                $entryDwnl->setParentRef($parentId);
                $entryDwnl->setRankRef($rankIdDistr);
                $entryDwnl->setPv($pvCompress);
                $entryDwnl->setTv($tvCompress);
                $entryDwnl->setOv($ovCompress);

                /**
                 * Calculate phase2 legs for qualified customers only (manager or higher).
                 */
                $ctxHlpQ = new \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase2\IsQualified\Context();
                $ctxHlpQ->setCustId($custId);
                $ctxHlpQ->setPv($pvOwn);
                $ctxHlpQ->setTv($tvCompress);
                $ctxHlpQ->setScheme($scheme);
                $ctxHlpQ->setCfgParams($cfgParams);
                $isCustQualifiedAsMgr = $this->hlpIsQualified->exec($ctxHlpQ);

                if ($isCustQualifiedAsMgr) {
                    /* this is qualified manager, calculate MAX leg, second leg and summary leg */
                    if (isset($mapByTeamCompress[$custId])) {
                        /* this customer has downline subtrees in compressed and plain trees */
                        /* populate legs result entry with data */
                        $entryLegs = new ELegs();
                        $entryLegs->setCalcRef($phase2CalcId);
                        $entryLegs->setCustRef($custId);

                        /* define legs based on plain OV */
                        if (isset($mapByTeamPlain[$custId])) {
                            $teamPlain = $mapByTeamPlain[$custId];
                            $legsPlain = $this->rouCalcLegs->exec($teamPlain, $mapByIdPlain);
                        } else {
                            $legsPlain = new DLegs();
                        }
                        /* define legs based on compressed OV */
                        $teamCompress = $mapByTeamCompress[$custId];
                        $legsCompress = $this->rouCalcLegs->exec($teamCompress, $mapByIdCompress);

                        /* get first 2 legs from plain and 'others' from compressed */
                        $legs = $this->rouComposeLegs->exec($legsPlain, $legsCompress);

                        /* update legs */
                        $entryLegs->setLegMax($legs->getMaxOv());
                        $entryLegs->setLegSecond($legs->getSecondOv());
                        $entryLegs->setLegOthers($legs->getOthersOv());
                        $entryLegs->setCustMaxRef($legs->getMaxCustId());
                        $entryLegs->setCustSecondRef($legs->getSecondCustId());
                        /* then calculate & update rank ID */
                        $reqQual = new \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase2\Fun\Act\Qualify\Data\Request();
                        $reqQual->setCfgParams($cfgParams);
                        $reqQual->setScheme($scheme);
                        $reqQual->setDownlineEntry($entryDwnl);
                        $reqQual->setLegsEntry($entryLegs);
                        $respQual = $this->actQualify->exec($reqQual);
                        $rankId = $respQual->getRankId();
                        $entryLegs = $respQual->getLegsEntry();

                        /* save rankId & add legs entry to results */
                        $entryDwnl->setRankRef($rankId);
                        $outLegs[$custId] = $entryLegs;

                    } else {
                        /* qualified customer w/o downline is a Manager */
                        $forcedRank = $this->hlpScheme->getForcedQualificationRank($custId, $scheme);
                        $rankIdChecked = ($forcedRank) ? $forcedRank : $rankIdMgr;
                        $entryDwnl->setRankRef($rankIdChecked);
                    }
                }
                /**
                 * Check qualification for current parent
                 */
                /** @var EBonDwnl $parentData */
                $parentData = $mapByIdCompress[$parentId];
                $parentPvOwn = isset($mapPv[$parentId]) ? $mapPv[$parentId] : 0;
                $parentTv = $parentData->getTv();
                /* validate parent qualification */
                $ctxHlpQ = new \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase2\IsQualified\Context();
                $ctxHlpQ->setCustId($parentId);
                $ctxHlpQ->setPv($parentPvOwn);
                $ctxHlpQ->setTv($parentTv);
                $ctxHlpQ->setScheme($scheme);
                $ctxHlpQ->setCfgParams($cfgParams);
                $isParentQualifiedAsMgr = $this->hlpIsQualified->exec($ctxHlpQ);

                /* re-link parent for all customers (qualified & distributors) */
                if (!$isParentQualifiedAsMgr) {
                    /* parent is not qualified, move customer up to the closest parent qualified as manager or higher */
                    $path = $custData->getPath();
                    $parents = $this->hlpTree->getParentsFromPathReversed($path);
                    $foundParentId = null;
                    $prevParentId = null;
                    $fatherIsUnqual = false; // we should not compress nodes for EU scheme where grand is qualified
                    foreach ($parents as $newParentId) {
                        /** @var EBonDwnl $newParentData */
                        $newParentData = $mapByIdCompress[$newParentId];
                        $newParentPvOwn = isset($mapPv[$newParentId]) ? $mapPv[$newParentId] : 0;
                        $newParentTv = $newParentData->getTv();
                        /* validate parent qualification */
                        $ctxHlpQ = new \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase2\IsQualified\Context();
                        $ctxHlpQ->setCustId($newParentId);
                        $ctxHlpQ->setPv($newParentPvOwn);
                        $ctxHlpQ->setTv($newParentTv);
                        $ctxHlpQ->setScheme($scheme);
                        $ctxHlpQ->setCfgParams($cfgParams);
                        $isNewParentQualifiedAsMgr = $this->hlpIsQualified->exec($ctxHlpQ);
                        if ($isNewParentQualifiedAsMgr) {
                            $foundParentId = $newParentId;
                            break;
                        }
                        $fatherIsUnqual = true; // customer's father or higher is distributor
                        $prevParentId = $newParentId; // save the last distributor before manager
                    }
                    unset($parents);
                    if (is_null($foundParentId)) {
                        /* no qualified parent up to the root, make this customer as root customer  */
                        $entryDwnl->setParentRef($custId);
                    } elseif ($fatherIsUnqual && ($scheme == Cfg::SCHEMA_EU)) {
                        /* EU: there is qualified grand for unqualified father, should not compress */
                        $entryDwnl->setParentRef($prevParentId);
                    } else {
                        $entryDwnl->setParentRef($foundParentId);
                    }
                }

                /* add entry to results */
                $outDownline[$custId] = $entryDwnl;
            }
        }
        /* get paths & depths for downline tree (is & parentId only present in results ) */
        $snap = $this->hlpTree->expandMinimal($outDownline, EBonDwnl::A_PARENT_REF);
        /* go through the downline snapshot and move depth & path info into results */
        foreach ($outDownline as $id => $one) {
            $depth = $snap[$id][\Praxigento\Downline\Repo\Data\Snap::A_DEPTH];
            $path = $snap[$id][\Praxigento\Downline\Repo\Data\Snap::A_PATH];
            /** @var EBonDwnl $entry */
            $entry = $outDownline[$id];
            $entry->setDepth($depth);
            $entry->setPath($path);
        }
        /* clean up memory */
        unset($mapByTeamPlain);
        unset($mapByIdPlain);
        unset($mapByDepthCompress);
        unset($mapByTeamCompress);
        unset($mapByIdCompress);

        /* put result data into output */
        $result = new \Praxigento\Core\Data();
        $result->set(self::OUT_DWNL_PHASE2, $outDownline);
        $result->set(self::OUT_LEGS, $outLegs);
        return $result;
    }

    /**
     * Get configuration for Override & Infinity bonuses ordered by scheme and leg max/medium/min desc.
     *
     * @return array [$scheme=>[$rankId=>[...], ...], ...]
     *
     * TODO: move this func closer to \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase2\IsQualified
     */
    private function getCfgParams()
    {
        $result = [];
        $order = [
            ECfgParam::A_SCHEME . ' ASC',
            ECfgParam::A_LEG_MAX . ' DESC',
            ECfgParam::A_LEG_MEDIUM . ' DESC',
            ECfgParam::A_LEG_MIN . ' DESC'
        ];
        $data = $this->daoCfgParam->get(null, $order);
        /** @var ECfgParam $one */
        foreach ($data as $one) {
            $scheme = $one->getScheme();
            $rankId = $one->getRankId();
            $result[$scheme][$rankId] = $one;
        }
        return $result;
    }

}


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

namespace cascade\components\web\form;

use cascade\components\db\fields\Model as ModelField;
use cascade\components\db\fields\Relation as RelationField;
use canis\helpers\Html;
use canis\web\grid\Grid;
use Yii;

/**
 * Segment [[@doctodo class_description:cascade\components\web\form\Segment]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class Segment extends FormObject
{
    /**
     * @var [[@doctodo var_type:cellClass]] [[@doctodo var_description:cellClass]]
     */
    public $cellClass = 'cascade\components\web\form\fields\Cell';
    /**
     * @var [[@doctodo var_type:subform]] [[@doctodo var_description:subform]]
     */
    public $subform;
    /**
     * @var [[@doctodo var_type:relationSettings]] [[@doctodo var_description:relationSettings]]
     */
    public $relationSettings = true;
    /**
     * @var [[@doctodo var_type:relationField]] [[@doctodo var_description:relationField]]
     */
    public $relationField;

    /**
     * @var [[@doctodo var_type:_name]] [[@doctodo var_description:_name]]
     */
    protected $_name;
    /**
     * @var [[@doctodo var_type:_model]] [[@doctodo var_description:_model]]
     */
    protected $_model;
    /**
     * @var [[@doctodo var_type:_settings]] [[@doctodo var_description:_settings]]
     */
    protected $_settings;
    /**
     * @var [[@doctodo var_type:_grid]] [[@doctodo var_description:_grid]]
     */
    protected $_grid;
    /**
     * @var [[@doctodo var_type:_fields]] [[@doctodo var_description:_fields]]
     */
    protected $_fields;

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();

        $this->isValid =  $this->model->setFormValues($this->name);
        if (!empty($this->settings['ignoreInvalid'])) {
            $this->isValid = true;
            $this->model->clearErrors();
        }
    }

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

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

    /**
     * Set settings.
     *
     * @param [[@doctodo param_type:settings]] $settings [[@doctodo param_description:settings]]
     *
     * @throws Exception [[@doctodo exception_description:Exception]]
     */
    public function setSettings($settings)
    {
        if (is_null($this->model)) {
            throw new Exception("You must set the model before you can set the settings.");
        }
        $this->_settings = $this->model->formSettings($this->name, $settings);
        if (is_null($this->_settings) and !empty($settings)) {
            $this->_settings = $settings;
        }
        if (empty($this->_settings['fields'])) {
            $this->_settings['fields'] = [];
        }
    }

    /**
     * Get model.
     *
     * @return unknown
     */
    public function getModel()
    {
        return $this->_model;
    }

    /**
     * Get settings.
     *
     * @return unknown
     */
    public function getSettings()
    {
        if (!is_null($this->_settings)) {
            $this->settings = [];
        }

        return $this->_settings;
    }

    /**
     * Get name.
     *
     * @return unknown
     */
    public function getName()
    {
        return $this->_name;
    }

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

    /**
     * [[@doctodo method_description:hasFile]].
     *
     * @return [[@doctodo return_type:hasFile]] [[@doctodo return_description:hasFile]]
     */
    public function hasFile()
    {
        if ($this->model->getBehavior('Storage') !== null) {
            return true;
        }

        foreach ($this->fields as $field) {
            if ($field->hasFile()) {
                return true;
            }
        }

        return false;
    }

    /**
     * [[@doctodo method_description:generate]].
     *
     * @return unknown
     */
    public function generate()
    {
        $this->getFields();
        $result = [];
        if (!empty($this->_settings['title'])) {
            $result[] = Html::beginTag('fieldset');
            $result[] = Html::tag('legend', $this->_settings['title']);
        }
        $result[] = $this->grid->generate();
        if (!empty($this->_settings['title'])) {
            $result[] = Html::endTag('fieldset');
        }

        return implode("\n", $result);
    }

    /**
     * Get fields.
     *
     * @return unknown
     */
    protected function getFields()
    {
        $settings = $this->settings;
        if (is_null($this->_fields)) {
            $this->_fields = [];
            if (is_array($settings)) {
                $this->_settings = $settings;
            } else {
                $this->_settings = [];
            }
            if (!isset($this->_settings['fieldSettings'])) {
                $this->_settings['fieldSettings'] = [];
            }
            if (!isset($this->_settings['formField'])) {
                $this->_settings['formField'] = [];
            }
            if (!isset($this->_settings['ignoreFields'])) {
                $this->_settings['ignoreFields'] = [];
            }
            if (is_array($this->_settings['fields']) && empty($this->_settings['fields'])) {
                $this->_settings['fields'] = null;
            }
            $fields = $this->_model->getFields($this);
            if (!isset($this->_model->_moduleHandler)) {
                $modelClass = get_class($this->_model);
                $this->_model->_moduleHandler = $modelClass::FORM_PRIMARY_MODEL;
            }
            $requiredFields = true;
            $fieldsTemplate = false;
            if (!is_null($this->relationField)) {
                $fieldName = $this->relationField->modelRole . ':' . $this->relationField->baseModel->objectType->systemId;
                if (isset($fields[$fieldName])) {
                    $fields[$fieldName]->baseModel = $this->relationField->baseModel;
                    $fields[$fieldName]->model = $this->relationField->model;
                    $fields[$fieldName]->formField = $this->relationField->formField;
                    $fields[$fieldName]->required = true;
                    $this->relationField->formField->inlineRelation = true;
                    if (!$this->relationField->model->isNewRecord && $this->relationField->companion->hasDashboard) {
                        $fieldsTemplate = [[$fieldName]];
                        $requiredFields = false;
                    }
                }
            }
            if ($requiredFields) {
                $requiredFields = $this->_model->getRequiredFields($this);
            } else {
                $requiredFields = [$fieldName => $fields[$fieldName]];
            }
            if (!$fieldsTemplate) {
                if (!empty($this->subform)) {
                    $fieldsTemplate = [[$this->subform => ['relationSettings' => $this->relationSettings]]];
                } elseif (!isset($this->_settings['fields'])) {
                    $fieldsTemplate = [];
                    foreach ($fields as $fieldName => $field) {
                        if (!$field->human) {
                            continue;
                        }
                        //if (!$field->required) { continue; }
                        if (!($field instanceof ModelField)) {
                            continue;
                        }
                        $fieldsTemplate[] = [$fieldName];
                    }
                } else {
                    $fieldsTemplate = $this->_settings['fields'];
                }
            }
            if ($fieldsTemplate !== false) {
                $this->_settings['fields'] = [];
                foreach ($fields as $fieldKey => $field) {
                    if (!is_object($field->model)) {
                        \d($field);
                        exit;
                    }
                    if ($field->model->isNewRecord) {
                        continue;
                    }
                    if ($field->human) {
                        continue;
                    }
                    if (!$field->required) {
                        continue;
                    }
                    $this->grid->prepend($field->formField);
                }
                $fields['_moduleHandler']->formField->owner = $this;
                $this->grid->prepend($fields['_moduleHandler']->formField);
                $cellClass = $this->cellClass;

                // make sure all required fields are part of the form
                if (empty($this->subform)) {
                    if (!empty($requiredFields)) {
                        foreach ($fieldsTemplate as $rowFields) {
                            foreach ($rowFields as $fieldKey => $fieldSettings) {
                                if (is_numeric($fieldKey)) {
                                    $fieldKey = $fieldSettings;
                                    $fieldSettings = [];
                                }
                                unset($requiredFields[$fieldKey]);
                            }
                        }
                    }

                    foreach ($requiredFields as $fieldName => $field) {
                        if (in_array($fieldName, $this->_settings['ignoreFields'])) {
                            continue;
                        }
                        $fieldsTemplate[] = [$fieldName];
                    }
                }

                foreach ($fieldsTemplate as $rowFields) {
                    $rowItems = [];
                    foreach ($rowFields as $fieldKey => $fieldSettings) {
                        if (is_numeric($fieldKey)) {
                            $fieldKey = $fieldSettings;
                            $fieldSettings = [];
                        }
                        if ($fieldKey === false || $fieldKey === ':empty') {
                            $rowItems[] = Yii::createObject(['class' => $cellClass, 'content' => ' ']);
                            continue;
                        }

                        if ($fieldKey === ':separator') {
                            $rowItems[] = Yii::createObject(['class' => $cellClass, 'content' => '']);
                            continue;
                        }

                        if (!isset($fields[$fieldKey])) {
                            \d([$fieldKey, array_keys($fields)]);
                            continue;
                        }

                        $this->_fields[$fieldKey] = $fields[$fieldKey];
                        if ($fieldKey === false) {
                            $rowItems[] = false;
                        } else {
                            //\d([$fieldKey, $fieldSettings]);
                            $cellOptions = ['class' => $cellClass, 'content' => $fields[$fieldKey]->formField->configure($fieldSettings)];
                            if (isset($cellOptions['content']->columns)) {
                                $cellOptions['columns'] = $cellOptions['content']->columns;
                            }
                            $rowItems[] = Yii::createObject($cellOptions);
                        }
                    }
                    $this->grid->addRow($rowItems);
                }
            }
        }
        //\d($this->_fields);exit;
        return $this->_fields;
    }

    /**
     * Get grid.
     *
     * @return [[@doctodo return_type:getGrid]] [[@doctodo return_description:getGrid]]
     */
    public function getGrid()
    {
        if (is_null($this->_grid)) {
            $this->_grid = new Grid();
        }

        return $this->_grid;
    }
}


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

namespace cascade\components\dataInterface\connectors\file;

use cascade\components\dataInterface\RecursionException;

/**
 * DataItem data item for file data connectors.
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class DataItem extends \cascade\components\dataInterface\connectors\generic\DataItem
{
    /**
     * @var Model the deferred model, without loaded attributes
     */
    public $deferredModel;
    /**
     * @inheritdoc
     */
    public function getId()
    {
        if ($this->isForeign) {
            if (isset($this->deferredModel)) {
                return $this->deferredModel->id;
            } elseif (isset($this->foreignObject)) {
                return $this->foreignObject->primaryKey;
            }
        } else {
            if (isset($this->localPrimaryKey)) {
                return $this->localPrimaryKey;
            } elseif (isset($this->localObject)) {
                return $this->localObject->primaryKey;
            }
        }
        if (isset($this->primaryObject)) {
            return $this->primaryObject->primaryKey;
        }

        return;
    }

    /**
     * fill absent relation attributes.
     *
     * @param array      $config      relationship configuration
     * @param Model $otherObject the other object to fill in the relation config data
     */
    protected function fillRelationConfig(&$config, $otherObject)
    {
        if (isset($config['parent_object_id'])) {
            $config['child_object_id'] = $otherObject;
        } elseif (isset($config['child_object_id'])) {
            $config['parent_object_id'] = $otherObject;
        }
    }

    /**
     * @inheritdoc
     */
    protected function handleLocal($baseAttributes = [])
    {
        if ($this->ignoreLocalObject) {
            return false;
        }
        // local to foreign

        // find
        return false;
    }

    /**
     * Load the foreign object from the foreign data source.
     *
     * @throws RecursionException on recursive call when the object is already loading the same object
     */
    protected function loadForeignObject()
    {
        if ($this->_isLoadingForeignObject) {
            throw new RecursionException('Ran into recursion while loading foreign object');
        }
        $this->_isLoadingForeignObject = true;
        if (isset($this->deferredModel) && ($attributes = $this->deferredModel->attributes)) {
            $this->foreignObject = $this->dataSource->createModel($this->deferredModel->id, $this->deferredModel->attributes);
        }
        $this->_isLoadingForeignObject = false;
    }

    /**
     * Load the local object.
     *
     * @throws RecursionException on recursive call when the object is already loading the same object
     */
    protected function loadLocalObject()
    {
        if ($this->_isLoadingLocalObject) {
            throw new RecursionException('Ran into recursion while loading local object');
        }
        $this->_isLoadingLocalObject = true;
        if (isset($this->foreignObject) && !isset($this->_localObject)) {
            $keyTranslation = $this->dataSource->getKeyTranslation($this->foreignObject);
            if (!empty($keyTranslation) && ($localObject = $keyTranslation->object)) {
                $this->localObject = $localObject;
            }
        }
        $this->_isLoadingLocalObject = false;
    }
}


<?php

namespace Mediawiki\Db\Service;

use FluentPDO;
use Mediawiki\DataModel\Log;
use Mediawiki\DataModel\LogList;
use Mediawiki\DataModel\PageIdentifier;
use Mediawiki\DataModel\Title;
use MediaWiki\Services\LogListGetter;
use PDO;

/**
 * @author Addshore
 * @author Bene* < benestar.wikimedia@gmail.com >
 */
class DatabaseLogListGetter implements LogListGetter {

	/**
	 * @var FluentPDO
	 */
	private $db;

	/**
	 * @param PDO $db
	 */
	public function __construct( PDO $db ) {
		$this->db = new FluentPDO( $db );
	}

	/**
	 * @param string|null $type filter log entries by type
	 * @param string|null $action filter log entries by action, overrides $type
	 * @param int $namespace filter log entries in the given namespace
	 *
	 * @return LogList
	 */
	public function getLogList( $type = null, $action = null, $namespace = 0 ) {
		$query = $this->db->from( 'logging' )
			->select( array(
				'log_id', 'log_type', 'log_action', 'log_timestamp', 'log_user',
				'log_namespace', 'log_title', 'log_comment', 'log_page', 'log_params'
			) )
			->where( 'log_type', $type )
			->where( 'log_action', $action )
			->where( 'log_namespace', $namespace );

		$rows = $query->fetchAll();
		$logList = new LogList();

		foreach( $rows as $row ) {
			$logList->addLog( $this->getLogFromRow( $row ) );
		}

		return $logList;
	}

	private function getLogFromRow( array $row ) {
		return new Log(
			intval( $row['log_id'] ),
			$row['log_type'],
			$row['log_action'],
			$row['log_timestamp'],
			$row['log_user'],
			new PageIdentifier(
				new Title( $row['log_title'], intval( $row['log_namespace'] ) ),
				intval( $row['log_page'] )
			),
			$row['log_comment'],
			$row['log_params']
		);
	}

}


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

namespace Praxigento\BonusHybrid\Service\Calc;

use Praxigento\BonusHybrid\Config as Cfg;
use Praxigento\BonusHybrid\Service\Calc\SignUpDebit\A\Repo\Query\GetOrders as QBGetOrders;

class SignUpDebit
    implements \Praxigento\Core\Api\App\Service\Process
{
    /** @var \Praxigento\BonusBase\Repo\Dao\Calculation */
    private $daoCalc;
    /** @var  \Praxigento\Core\Api\Helper\Period */
    private $hlpPeriod;
    /** @var \Praxigento\Core\Api\App\Logger\Main */
    private $logger;
    /** @var  \Praxigento\BonusHybrid\Service\Calc\SignUpDebit\A\ProcessOrders */
    private $ownProcessOrders;
    /** @var \Praxigento\BonusHybrid\Service\Calc\SignUpDebit\A\Repo\Query\GetOrders */
    private $qbGetOrders;
    /** @var \Praxigento\BonusBase\Service\Period\Calc\Get\IBasis */
    private $servPeriodGetBasis;

    public function __construct(
        \Praxigento\Core\Api\App\Logger\Main $logger,
        \Praxigento\Core\Api\Helper\Period $hlpPeriod,
        \Praxigento\BonusBase\Repo\Dao\Calculation $daoCalc,
        \Praxigento\BonusHybrid\Service\Calc\SignUpDebit\A\Repo\Query\GetOrders $qbGetOrders,
        \Praxigento\BonusBase\Service\Period\Calc\Get\IBasis $servPeriodGetBasis,
        \Praxigento\BonusHybrid\Service\Calc\SignUpDebit\A\ProcessOrders $ownProcessOrders
    )
    {
        $this->logger = $logger;
        $this->hlpPeriod = $hlpPeriod;
        $this->daoCalc = $daoCalc;
        $this->qbGetOrders = $qbGetOrders;
        $this->servPeriodGetBasis = $servPeriodGetBasis;
        $this->ownProcessOrders = $ownProcessOrders;
    }

    public function exec(\Praxigento\Core\Data $ctx)
    {
        /**
         * perform processing
         */
        $ctx->set(self::CTX_OUT_SUCCESS, false);
        /* get dependent calculation data */
        list($periodData, $calcData) = $this->getCalcData();
        $this->logger->info("'Sign Up Volume Debit' bonus is started.");
        $periodId = $periodData->getId();
        $calcId = $calcData->getId();
        $periodBegin = $periodData->getDstampBegin();
        $periodEnd = $periodData->getDstampEnd();
        $calcState = $calcData->getState();
        $this->logger->info("Processing period #$periodId ($periodBegin-$periodEnd), Sign Up Volume Debit calculation #$calcId ($calcState).");
        if ($calcState != Cfg::CALC_STATE_COMPLETE) {
            $dateApplied = $this->hlpPeriod->getTimestampUpTo($periodEnd);
            /* get first orders for just signed up customers */
            $orders = $this->getOrders($periodBegin, $periodEnd);
            $this->ownProcessOrders->exec($orders, $dateApplied, $calcId);
            /* mark this calculation complete */
            $this->daoCalc->markComplete($calcId);
            /* mark process as successful */
            $ctx->set(self::CTX_OUT_SUCCESS, true);
        }
        $this->logger->info("'Sign Up Volume Debit' bonus is completed.");
    }

    /**
     * Get data for dependent calculation.
     *
     * @return array [$periodData, $calcData]
     * @throws \Exception
     */
    private function getCalcData()
    {
        /* get period & calc data (first calc in the chain) */
        $ctx = new \Praxigento\Core\Data();
        $ctx->set($this->servPeriodGetBasis::CTX_IN_CALC_CODE, Cfg::CODE_TYPE_CALC_BONUS_SIGN_UP_DEBIT);
        $ctx->set($this->servPeriodGetBasis::CTX_IN_ASSET_TYPE_CODE, Cfg::CODE_TYPE_ASSET_PV);
        $ctx->set($this->servPeriodGetBasis::CTX_IN_PERIOD_TYPE, \Praxigento\Core\Api\Helper\Period::TYPE_MONTH);
        $this->servPeriodGetBasis->exec($ctx);
        $periodData = $ctx->get($this->servPeriodGetBasis::CTX_OUT_PERIOD_DATA);
        $calcData = $ctx->get($this->servPeriodGetBasis::CTX_OUT_CALC_DATA);
        $result = [$periodData, $calcData];
        return $result;
    }

    /**
     * @param string $dateFrom
     * @param string $dateTo
     * @return array
     */
    private function getOrders($dateFrom, $dateTo)
    {
        /** @var  $query */
        $query = $this->qbGetOrders->build();
        $conn = $query->getConnection();
        /** TODO: fix backward dependency for customer group ID
         * (bonus module should not be dependent from project module - \Praxigento\Santegra\Helper\...)
         */
        $from = $this->hlpPeriod->getTimestampFrom($dateFrom);
        $upTo = $this->hlpPeriod->getTimestampNextFrom($dateTo);
        $rs = $conn->fetchAll($query, [
            QBGetOrders::BND_DATE_FROM => $from,
            QBGetOrders::BND_DATE_TO => $upTo,
            /* TODO: reversed dependency from project module (create helper for the group ID)*/
            QBGetOrders::BND_CUST_GROUP_ID => \Praxigento\Santegra\Helper\Odoo\BusinessCodes::M_CUST_GROUP_DISTRIBUTOR
        ]);
        /* only customer's first order should be included in the result set (apply to the bonus) */
        $result = [];
        foreach ($rs as $one) {
            $custId = $one[QBGetOrders::A_CUST_ID];
            if (!isset($result[$custId])) {
                $result[$custId] = $one;
            }
        }
        return $result;
    }
}


<?php

/**
 * Manage Benchmark
 *
 * @category  	lib
 * @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;

use \Venus\lib\Log\LoggerAwareInterface as LoggerAwareInterface;
use \Venus\lib\Log\LoggerInterface as LoggerInterface;

/**
 * This class manage the Benchmark
 *
 * @category  	lib
 * @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
 *
 * @tutorial	$oBenchmark = new \Venus\lib\Benchmark;
 * 				echo $oBenchmark->getUrl('css/style.css');
 */
class Benchmark implements LoggerAwareInterface
{
	/**
	 * start Benchmark
	 *
	 * @access private
	 * @var    float
	 */
	private static $_fStart = 0;

	/**
	 * start Benchmark
	 *
	 * @access private
	 * @var    \Venus\lib\Debug
	 */
	private $_oLogger;

	/**
	 * assign a variable for the Benchmark
	 *
	 * @access public
	 * @return void
	 */
	public static function start()
	{
		self::$_fStart = microtime(true);
	}

	/**
	 * assign a variable for the Benchmark
	 *
	 * @access public
	 * @return float
	 */
	public static function getPoint() : float
	{
		return microtime(true) - self::$_fStart;
	}

	/**
	 * assign a variable for the Benchmark
	 *
	 * @access public
	 * @param  string $sName name of point
	 * @return void
	 */
	public static function setPointInLog(string $sName = 'default')
	{
	    $oLogger = Debug::getInstance();
		$oLogger->info('BENCHMARK: Time at this point '.(microtime(true) - self::$_fStart).' - '.$sName);
	}

	/**
	 * Sets a logger instance on the object
	 *
	 * @access public
	 * @param  LoggerInterface $logger
	 * @return void
	 */
	public function setLogger(LoggerInterface $logger)
	{
	    if ($this->_oLogger === null) { $this->_oLogger = $logger; }
	}

	/**
	 * get the logger instance on the object
	 *
	 * @access public
	 * @return LoggerInterface
	 */
	public function getLogger()
	{
	   return $this->_oLogger;
	}
}


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

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

namespace EasyWeChat\Material;

use EasyWeChat\Core\AbstractAPI;
use EasyWeChat\Core\Exceptions\InvalidArgumentException;
use EasyWeChat\Message\Article;

/**
 * Class Material.
 */
class Material extends AbstractAPI
{
    /**
     * Allow media type.
     *
     * @var array
     */
    protected $allowTypes = ['image', 'voice', 'video', 'thumb', 'news_image'];

    const API_GET = 'https://api.weixin.qq.com/cgi-bin/material/get_material';
    const API_UPLOAD = 'https://api.weixin.qq.com/cgi-bin/material/add_material';
    const API_DELETE = 'https://api.weixin.qq.com/cgi-bin/material/del_material';
    const API_STATS = 'https://api.weixin.qq.com/cgi-bin/material/get_materialcount';
    const API_LISTS = 'https://api.weixin.qq.com/cgi-bin/material/batchget_material';
    const API_NEWS_UPLOAD = 'https://api.weixin.qq.com/cgi-bin/material/add_news';
    const API_NEWS_UPDATE = 'https://api.weixin.qq.com/cgi-bin/material/update_news';
    const API_NEWS_IMAGE_UPLOAD = 'https://api.weixin.qq.com/cgi-bin/media/uploadimg';

    /**
     * Upload image.
     *
     * @param string $path
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function uploadImage($path)
    {
        return $this->uploadMedia('image', $path);
    }

    /**
     * Upload voice.
     *
     * @param string $path
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function uploadVoice($path)
    {
        return $this->uploadMedia('voice', $path);
    }

    /**
     * Upload thumb.
     *
     * @param string $path
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function uploadThumb($path)
    {
        return $this->uploadMedia('thumb', $path);
    }

    /**
     * Upload video.
     *
     * @param string $path
     * @param string $title
     * @param string $description
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function uploadVideo($path, $title, $description)
    {
        $params = [
            'description' => json_encode(
                [
                    'title' => $title,
                    'introduction' => $description,
                ], JSON_UNESCAPED_UNICODE),
        ];

        return $this->uploadMedia('video', $path, $params);
    }

    /**
     * Upload articles.
     *
     * @param array|Article $articles
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function uploadArticle($articles)
    {
        if (!empty($articles['title']) || $articles instanceof Article) {
            $articles = [$articles];
        }

        $params = ['articles' => array_map(function ($article) {
            if ($article instanceof Article) {
                return $article->only([
                    'title', 'thumb_media_id', 'author', 'digest',
                    'show_cover_pic', 'content', 'content_source_url',
                    ]);
            }

            return $article;
        }, $articles)];

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

    /**
     * Update article.
     *
     * @param string $mediaId
     * @param array  $article
     * @param int    $index
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function updateArticle($mediaId, $article, $index = 0)
    {
        $params = [
            'media_id' => $mediaId,
            'index' => $index,
            'articles' => isset($article['title']) ? $article : (isset($article[$index]) ? $article[$index] : []),
        ];

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

    /**
     * Upload image for article.
     *
     * @param string $path
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function uploadArticleImage($path)
    {
        return $this->uploadMedia('news_image', $path);
    }

    /**
     * Fetch material.
     *
     * @param string $mediaId
     *
     * @return mixed
     */
    public function get($mediaId)
    {
        $response = $this->getHttp()->json(self::API_GET, ['media_id' => $mediaId]);

        foreach ($response->getHeader('Content-Type') as $mime) {
            if (preg_match('/(image|video|audio)/i', $mime)) {
                return $response->getBody();
            }
        }

        $json = $this->getHttp()->parseJSON($response);

        // XXX: 微信开发这帮混蛋，尼玛文件二进制输出不带header，简直日了!!!
        if (!$json) {
            return $response->getBody();
        }

        $this->checkAndThrow($json);

        return $json;
    }

    /**
     * Delete material by media ID.
     *
     * @param string $mediaId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function delete($mediaId)
    {
        return $this->parseJSON('json', [self::API_DELETE, ['media_id' => $mediaId]]);
    }

    /**
     * List materials.
     *
     * example:
     *
     * {
     *   "total_count": TOTAL_COUNT,
     *   "item_count": ITEM_COUNT,
     *   "item": [{
     *             "media_id": MEDIA_ID,
     *             "name": NAME,
     *             "update_time": UPDATE_TIME
     *         },
     *         // more...
     *   ]
     * }
     *
     * @param string $type
     * @param int    $offset
     * @param int    $count
     *
     * @return array
     */
    public function lists($type, $offset = 0, $count = 20)
    {
        $params = [
            'type' => $type,
            'offset' => intval($offset),
            'count' => min(20, $count),
        ];

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

    /**
     * Get stats of materials.
     *
     * @return array
     */
    public function stats()
    {
        return $this->parseJSON('get', [self::API_STATS]);
    }

    /**
     * Upload material.
     *
     * @param string $type
     * @param string $path
     * @param array  $form
     *
     * @return \EasyWeChat\Support\Collection
     *
     * @throws InvalidArgumentException
     */
    protected function uploadMedia($type, $path, array $form = [])
    {
        if (!file_exists($path) || !is_readable($path)) {
            throw new InvalidArgumentException("File does not exist, or the file is unreadable: '$path'");
        }

        $form['type'] = $type;

        return $this->parseJSON('upload', [$this->getAPIByType($type), ['media' => $path], $form]);
    }

    /**
     * Get API by type.
     *
     * @param string $type
     *
     * @return string
     */
    public function getAPIByType($type)
    {
        switch ($type) {
            case 'news_image':
                $api = self::API_NEWS_IMAGE_UPLOAD;
                break;
            default:
                $api = self::API_UPLOAD;
        }

        return $api;
    }
}


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

namespace wula\cms;

use wulaphp\app\App;
use wulaphp\app\Module;
use wulaphp\db\DatabaseConnection;

abstract class CmfModule extends Module {
	public $isKernel = false;

	/**
	 * 安装.
	 *
	 * @param DatabaseConnection $con
	 * @param int                $kernel 1代表安装的是内核模块.
	 *
	 * @return bool
	 */
	public final function install($con, $kernel = 0) {
		if ($con->select('id')->from('{module}')->where(['name' => $this->namespace])->exist('id')) {
			return true;
		}
		$rst = $this->upgrade($con, $this->currentVersion);
		if ($rst) {
			$data['name']        = $this->namespace;
			$data['version']     = $this->currentVersion;
			$data['create_time'] = $data['update_time'] = time();
			$data['kernel']      = $kernel;
			$rst                 = $con->insert($data)->into('{module}')->exec(true);
		}

		return $rst;
	}

	/**
	 * 卸载.
	 * @return bool
	 * @throws
	 */
	public final function uninstall() {
		if (!App::db()->select('id')->from('{module}')->where(['name' => $this->namespace])->exist('id')) {
			return false;
		}
		$rst = $this->onUninstall();
		if ($rst) {
			$db     = App::db();
			$tables = $this->getDefinedTables($db->getDialect());
			if ($tables ['tables']) {
				foreach ($tables ['tables'] as $table) {
					$db->exec('DROP TABLE IF EXISTS ' . $table);
				}
			}
			if ($tables ['views']) {
				foreach ($tables ['views'] as $table) {
					$db->exec('DROP VIEW IF EXISTS ' . $table);
				}
			}
			$db->delete()->from('{module}')->where(['name' => $this->namespace])->exec();
			App::cfg();
		}

		return $rst;
	}

	/**
	 * @return bool
	 * @throws \Exception
	 */
	public final function stop() {
		if (!App::db()->select('id')->from('{module}')->where(['name' => $this->namespace])->exist('id')) {
			return false;
		}

		App:: db()->update('{module}')->set(['status' => 0])->where([
			'name'   => $this->namespace,
			'kernel' => 0
		])->exec();

		return true;
	}

	/**
	 * @return bool
	 * @throws \Exception
	 */
	public final function start() {
		if (!App::db()->select('id')->from('{module}')->where(['name' => $this->namespace])->exist('id')) {
			return false;
		}

		App:: db()->update('{module}')->set(['status' => 1])->where([
			'name' => $this->namespace
		])->exec();

		return true;
	}

	/**
	 * @param DatabaseConnection $db
	 * @param string             $toVer
	 * @param string             $fromVer
	 *
	 * @return bool
	 * @throws
	 */
	public final function upgrade($db, $toVer, $fromVer = '0.0.0') {
		if ($fromVer !== '0.0.0' && !$db->select('id')->from('{module}')->where(['name' => $this->namespace])->exist('id')) {
			return false;
		}
		$prev = $fromVer;
		foreach ($this->getVersionList() as $ver => $chang) {
			$func = 'upgradeTo' . str_replace('.', '_', $ver);
			if (version_compare($ver, $toVer, '<=') && version_compare($ver, $fromVer, '>')) {
				$sqls = $this->getSchemaSQLs($ver, $prev);
				$prev = $ver;
				if ($sqls) {
					$sr = ['{prefix}', '{encoding}'];
					$rp = [$db->getDialect()->getTablePrefix(), $db->getDialect()->getCharset()];
					foreach ($sqls as $_sql) {
						if (!$_sql) {
							continue;
						}
						$_sql = (array)$_sql;
						foreach ($_sql as $sql) {
							$sql = str_replace($sr, $rp, $sql);
							$rst = $db->exec($sql);
							if (!$rst) {
								throw_exception($db->error);
							}
						}
					}
				}
				if ($func && method_exists($this, $func)) {
					$rst = $this->{$func}($db);
					if (!$rst) {
						return false;
					}
				}
			}
		}

		if ($fromVer != '0.0.0') {
			$db->update('{module}')->set(['version' => $toVer])->where(['name' => $this->namespace])->exec();
		}

		return true;
	}

	/**
	 * 取当前模板所定义的表.
	 *
	 * @param \wulaphp\db\dialect\DatabaseDialect $dialect
	 *
	 * @return array
	 */
	public function getDefinedTables($dialect) {
		$sqlFile = MODULES_PATH . $this->dirname . DS . 'schema.sql.php';
		if (is_file($sqlFile)) {
			$file = file_get_contents($sqlFile);

			return $dialect->getTablesFromSQL($file);
		}

		return [];
	}

	protected function onUninstall() {
		return true;
	}

	/**
	 * 加载SQL语句
	 *
	 * @param string $toVer
	 * @param string $fromVer
	 *
	 * @return array
	 */
	protected final function getSchemaSQLs($toVer, $fromVer = '0.0.0') {
		$sqls    = [];
		$sqlFile = MODULES_PATH . $this->dirname . DS . 'schema.sql.php';
		if (is_file($sqlFile)) {
			$tables = [];
			@include $sqlFile;
			if (!empty ($tables)) {
				foreach ($tables as $ver => $var) {
					if ($var && version_compare($ver, $toVer, '<=') && version_compare($ver, $fromVer, '>')) {
						$sqls = array_merge($sqls, (array)$var);
					}
				}
			}
		}

		return $sqls;
	}
}


<?php

/*
 * This file is part of the Сáша framework.
 *
 * (c) tchiotludo <http://github.com/tchiotludo>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types = 1);

namespace Cawa\Renderer;

use DeepCopy\DeepCopy;

class PhtmlHtmlContainer extends HtmlContainer
{
    use PhtmlTrait {
        PhtmlTrait::render as private phtmlRender;
    }

    use ContainerTrait {
        ContainerTrait::render as private containerRender;
    }

    /**
     * {@inheritdoc}
     */
    public function render()
    {
        /* @var \Cawa\Renderer\PhtmlHtmlContainer $clone */
        $deepcopy = new DeepCopy();
        $clone = $deepcopy->copy($this);

        $content = $clone->content ?: $clone->containerRender();
        $clone->addViewData('content', $content);
        $clone->content = $clone->phtmlRender();

        $clone->clear();

        return $clone->renderClone();
    }

    /**
     * @return string
     */
    private function renderClone()
    {
        return parent::render();
    }
}


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

namespace RznViewComponent\Service;
use Zend\ServiceManager\ServiceLocatorInterface;
use RznViewComponent\Container\Result;

trait IncludeComponentTrait
{

    /**
     * @var ServiceLocatorInterface
     */
    protected $serviceLocator;

    /**
     * Configuration array.
     *
     * @var array
     */
    protected $config = array();

    /**
     * @param $service aim service name
     * @param $template template for render after service data return
     * @param array $inputData data wich will be set to the service
     * @param array $params parameters
     * @return Result
     */
    public function __invoke($service, $template, $inputData = array(), $params = array())
    {
        $applicationService = $this->serviceLocator->getServiceLocator();
        if ($this->config['cache_allow'] and $this->config['cache_service'])
            $cache = $this->config['cache_service'];
        else
            $cache = false;

        if ($cache) {
            $cacheKey = $this->_buildCacheKey($service, $template, $inputData);
            /** @var \Zend\Cache\Storage\StorageInterface $cacheService */
            $cacheService = $applicationService->get($this->config['cache_service']);
            if ($this->config['cache_remove_item_key']
                and isset($_GET[$this->config['cache_remove_item_key']])
                and $_GET[$this->config['cache_remove_item_key']]) {
                $cacheService->removeItem($cacheKey);
                $cache = false;
            }
            else {
                $result = $cacheService->getItem($cacheKey);
                if (!empty($result)) {
                    return $result;
                    $result = @unserialize($result);
                    if ($result) {
                        return $result;
                    }
                }

            }
        }

        $result = $this-> _getResult($service, $template, $inputData, $params);
        if ($cache) {
            $applicationService->get($this->config['cache_service'])->addItem($cacheKey, $result);
        }
        return $result;
    }

    /**
     * Set the service locator.
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return CustomHelper
     */
    public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
    {
        $this->serviceLocator = $serviceLocator;

        $config = $serviceLocator->getServiceLocator()->get('config');

        if (isset($config['rznviewcomponent'])) {
            $this->config = $config['rznviewcomponent'];
        }

        return $this;
    }

    /**
     * Get the service locator.
     *
     * @return ServiceLocatorInterface
     */
    public function getServiceLocator()
    {
        return $this->serviceLocator;
    }
}


<?php
namespace eMacros\Runtime\Collection;

use eMacros\Runtime\GenericFunction;

class Cdr extends GenericFunction {
	/**
	 * Returns a list without its first element
	 * Usage: (Array::cdr (array 1 2 3))
	 * Returns: array
	 * (non-PHPdoc)
	 * @see \eMacros\Runtime\GenericFunction::execute()
	 */
	public function execute(array $arguments) {
		if (empty($arguments)) throw new \BadFunctionCallException("Cdr: No parameters found.");
		list($list) = $arguments;

		if (is_array($list)) {
			if (empty($list)) return null;
			return array_slice($list, 1);
		}

		if ($list instanceof \Iterator || $list instanceof \IteratorAggregate) {
			$it = $list instanceof \Iterator ? $list : $list->getIterator();
			$it->rewind();
			//empty list?
			if (!$it->valid()) return null;
			$result = [];
			for ($it->next(); $it->valid(); $it->next())
				$result[] = $it->current();
			return $result;
		}

		throw new \InvalidArgumentException('Cdr: Parameter is not a list.');
	}
}
?>


<?php
namespace Ecompassaro\Login;

use Ecompassaro\Acesso\Controller as AcessoController;
use Ecompassaro\Notificacao\FlashMessagesContainerTrait;

class Controller extends AcessoController
{
    use FlashMessagesContainerTrait;

    protected $resource = 'login';

    /**
     * Mostra a página de login
     *
     * @return LoginViewModel
     */
    public function indexAction()
    {
        $viewModel = $this->getViewModel();
        return $viewModel->setTemplate('login/index');
    }

    /**
     * Verifica o login se estiver correto redireciona para a página passada no
     * POST caso contrário redireciona para a página atual
     */
    public function entrarAction()
    {
        $viewModel = $this->getViewModel();
        if ($viewModel->validaLogin($this->params()
            ->fromPost())) {
                $redirect = $this->params()
                ->fromPost('routeRedirect');
            return $this->redirect()->toRoute($redirect?$redirect:'site');
        }

        $this->setFlashMessagesFromNotificacoes($viewModel->getNotificacoes());
        return $this->redirect()->toRoute('login');
    }
}


<?php

namespace carlosV2\DumbsmartRepositoriesBundle\Repository;

use Everzet\PersistedObjects\FileRepository;
use Everzet\PersistedObjects\InMemoryRepository;
use Everzet\PersistedObjects\ObjectIdentifier;
use Everzet\PersistedObjects\Repository;

class RepositoryFactory
{
    const TYPE_IN_MEMORY = 'in_memory';
    const TYPE_FILE = 'file';

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

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

    /**
     * @param string $type
     * @param string $path
     */
    public function __construct($type, $path)
    {
        $this->type = $type;
        $this->path = $path;
    }

    /**
     * @param string           $className
     * @param ObjectIdentifier $identifier
     *
     * @return Repository
     */
    public function createRepository($className, ObjectIdentifier $identifier)
    {
        switch ($this->type) {
            case self::TYPE_FILE:
                return new FileRepository($this->getFileName($className), $identifier);

            default:
                return new InMemoryRepository($identifier);
        }
    }

    /**
     * @param string $className
     *
     * @return string
     *
     * @throws \InvalidArgumentException
     */
    private function getFileName($className)
    {
        return sprintf(
            '%s%s%s.repository',
            rtrim($this->path, DIRECTORY_SEPARATOR),
            DIRECTORY_SEPARATOR,
            str_replace('\\', '_', $className)
        );
    }
}


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

/**
 * Validator for number
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
class NumberValidator extends ValidatorAbstract{

	/**
	 * {@inheritdoc}
	 */
	public function validate($value){
		$empty=false;

		try{
			$empty=$this->getOption('empty');
		}
		catch(ValueNotFoundException $e){
			//ignore
		}

		if(!$value && $empty){
            return null;
		}

		if(!is_numeric($value))
			return 'Value is not number.';

		try{
			$min=$this->getOption('min');
			if($value<$min){
				return 'Value is too small.';
			}
		}
		catch(ValueNotFoundException $e){
			//ignore
		}

		try{
			$max=$this->getOption('max');
			if($value>$max){
				return 'Value is too height.';
			}
		}
		catch(ValueNotFoundException $e){
			//ignore
		}
        return null;
	}
}


<?php
/**
 * Copyright (c) 2018 Konstantin Deryabin
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Kod\BootstrapSlim\Sample;

use Kod\BootstrapSlim\Bootstrap;
use Slim\App;

/**
 * Class SampleBootstrap
 * @package Kod\BootstrapSlim\Sample
 */
class SampleBootstrap extends Bootstrap
{
    /**
     * Set default application middleware
     * @return static
     */
    public function addAppMiddleware()
    {
        return $this->addMiddleware(
            SampleMiddleware::class
        );
    }

    /**
     * Sample adding DI
     * @return static
     */
    public function addAppDependencies()
    {
        /**
         * @var \Pimple\Container $container
         */
        $container = $this->getContainer();
        $container['person'] = $container->protect(function ($name) {
            return 'Person name: ' . $name;
        });

        return $this;
    }

    /**
     * Set default routes
     * @return static
     */
    public function addAppRoutes()
    {
        return $this->addRouteDefinitions(
            SampleRoute::class,
            SampleRoute2::class
        );
    }
}


<?php
/**
* Tiny library for WordPress plug-ins.
*
* @author Ondrej Donek, <ondrejd@gmail.com>
* @license https://www.mozilla.org/MPL/2.0/ Mozilla Public License 2.0
*/

namespace odwp;

require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';

/**
 * ...
 *
 * @author Ondřej Donek, <ondrejd@gmail.com>
 * @since 0.2
 */
abstract class ListTable extends \WP_List_Table {

    /**
     * Holds Twig templating engine.
     * @var \Twig_Environment $tplEngine
     */
    protected $twig;

	/**
	 * @var array $column_headers
	 */
	protected $columns;

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

	/**
	 * @var string $column_headers
	 */
	protected $page;

    /**
     * Constructor.
     *
     * @since 0.2
	 * @param \Twig_Environment $twig
     * @return void
     */
    public function __construct($id, $items, \Twig_Environment $twig) {
		$this->page = $page;
		$this->items = $items;
		$this->twig = $twig;

		add_action('admin_head', array($this, 'render_admin_header'));
		add_filter('set-screen-option', 'set_option', 10, 3);
	}

	/**
     * @since 0.2
	 * @return array Returns table columns.
	 */
	abstract public function get_columns();

	/**
     * @since 0.2
	 * @return array Returns hidden table columns.
	 */
	abstract public function get_hidden_columns();

	/**
     * @since 0.2
	 * @return array Returns sortable table columns.
	 */
	abstract public function get_sortable_columns();

	/**
     * @since 0.2
	 * @return string Returns name of defaultly sorted column.
	 */
	abstract public function get_default_sort_column();

	/**
     * @since 0.2
	 * @return array Returns table items.
	 */
	abstract public function get_items();

	/**
     * @since 0.2
	 * @return string Returns message that no items are in the table.
	 */
	abstract public function no_items();

	/**
	 * Returns supported bulk actions.
	 *
     * @since 0.2
	 * @return array
	 */
	function get_bulk_actions() {
		$actions = array(
			'delete' => 'Delete'
		);

		return $actions;
	}

	/**
	 * Retrieve contents for checkbox cell.
	 *
     * @since 0.2
	 * @param mixed $item
	 * @param string $column
	 * @return string
	 */
	public function cell_checkbox($item, $column) {
		return sprintf(
			'<input type="checkbox" name="book[]" value="%s"/>', $item[$column]
		);
    }

	/**
	 * Retrieve contents for normal cell.
	 *
     * @since 0.2
	 * @param mixed $item
	 * @param string $column
	 * @return string
	 */
	public function cell_default($item, $column) {
		$ret = $this->val($item, $column);

		return is_null($ret) ? '' : $ret;
	}

	/**
	 * Retrieve contents for cell with actions within.
	 *
     * @since 0.2
	 * @param mixed $item
	 * @param string $column
	 * @return string
	 */
	public function cell_with_actions($item, $column) {
		return sprintf('%s', $item[$column]);
    }

	/**
	 * Prepare table items.
	 *
     * @since 0.2
	 * @return void
	 */
	function prepare_items() {
		$this->columns = array(
			$this->get_columns(),
			$this->get_hidden_columns(),
			$this->get_sortable_columns()
		);

		$this->items = $this->get_items();

		usort($this->example_data, array($this, 'usort_reorder'));

		//paging
		//$per_page = $this->get_items_per_page('books_per_page', 5);
		//$current_page = $this->get_pagenum();
	}

	/**
	 * @param xxx $status
	 * @param string $option
	 * @param mixed $value
	 * @return mixed
	 */
	function set_option($status, $option, $value) {
		return $value;
	}

	/**
	 * Render table.
	 *
     * @since 0.2
	 * @return string
	 */
	public function render() {
		$params = array();

		$this->prepare_items();

		// ... TBD ...

		return $this->twig->render('list_table.twig', $params);
	}

	/**
	 * Render admin header.
	 *
     * @since 0.2
	 * @return void
	 */
	public function render_admin_header() {
		//$page = (isset($_GET['page'])) ? esc_attr($_GET['page']) : false;
		$page = filter_input(INPUT_GET, 'page');
		if ($this->page != $page) {
			return;
		}

		echo '<style type="text/css">';
		echo $this->twig->render('list_table.css.twig', array());
		echo '</style>';
	}

	/**
	 * @internal
     * @since 0.2
	 * @param mixed $item1
	 * @param mixed $item2
	 * @return integer
	 */
	protected function usort_reorder($item1, $item2) {
		$orderby = filter_input(INPUT_GET, 'orderby');
		if (empty($orderby)) {
			return 0;
		}

		$order = filter_input(INPUT_GET, 'order');
		if (empty($orderby)) {
			return 0;
		}

		$first = $this->val($item1, $orderby);
		$second = $this->val($item2, $orderby);
		if (is_null($first) && is_null($second)) {
			return 0;
		}

		$result = strcmp($first, $second);

		return ($order === 'asc') ? $result : -$result;
	}

	/**
	 * @internal
	 * @since 0.2
	 * @param mixed $data
	 * @param string $key
	 * @return mixed
	 */
	protected function val($data, $key) {
		if (is_array($data)) {
			if (array_key_exists($key, $data)) {
				return $a[$key];
			}
		}

		if (is_object($data)) {
			if (property_exists($data, $key)) {
				return $a->$key;
			}
		}
	}
}


<?php

/*
 * This file is part of Transfer.
 *
 * For the full copyright and license information, please view the LICENSE file located
 * in the root directory.
 */

namespace Bridge\Console\Command;

use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Command for clearing cache.
 */
class CacheClearCommand extends BridgeCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        parent::configure();

        $this
            ->setName('cache:clear')
            ->setDescription('Clear cache for a cache pool')
            ->addArgument('name', InputArgument::REQUIRED, 'Pool name');
    }

    /**
     * {@inheritdoc}
     */
    public function execute(InputInterface $input, OutputInterface $output)
    {
        parent::execute($input, $output);

        $name = $input->getArgument('name');

        $output->writeln(sprintf('Clearing cache for pool "%s"...', $name));

        if ($this->registry->getCachePool($name)->clear()) {
            $output->writeln('<info>Cache pool has been successfully cleared.</info>');
        } else {
            $output->writeln(sprintf('<error>An error occurred while clearing cache pool "%s"</error>', $name));
        }
    }
}


<?php

/**
 * @file
 * Contains Pipeware\Stack
 */

namespace Pipeware;

use Pipeware\Pipeline\Pipeline;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use SyberIsle\Pipeline\Processor;

/**
 * Generic Middleware stack
 *
 * @package Pipeware
 */
class Stack
	implements RequestHandlerInterface
{
	/**
	 * @var Pipeline
	 */
	protected $pipeline;

	/**
	 * @var Processor
	 */
	protected $processor;

	/**
	 * Stack constructor.
	 *
	 * @param Pipeline  $pipeline
	 * @param Processor $processor
	 */

	public function __construct(Pipeline $pipeline, Processor $processor)
	{
		$this->pipeline  = $pipeline;
		$this->processor = $processor;
	}

	/**
	 * Reverses the direction of the pipeline
	 */
	public function reverse()
	{
		$this->pipeline = $this->pipeline->withReversedOrder();

		return $this;
	}

	/**
	 * Pushes middleware on the stack
	 *
	 * @param $middleware
	 * @return Stack
	 */
	public function push($middleware)
	{
		$this->pipeline = $this->pipeline->pipe($middleware);

		return $this;
	}

	/**
	 * Replaces middleware on the stack
	 *
	 * @param $middleware
	 * @param $with
	 * @return $this
	 */
	public function replace($middleware, $with)
	{
		$this->pipeline = $this->pipeline->replace($middleware, $with);

		return $this;
	}

	/**
	 * {@inheritdoc}
	 */
	public function handle(ServerRequestInterface $request): ResponseInterface
	{
		return $this->processor->process($this->pipeline, $request);
	}
}


<?php

/**
 * Bomifier class.
 * @author _alK13
 */
class Bomifier
{

    /**
     * The file path.
     * @var string
     */
    protected $uri;

    /**
     * The uri is null to assume backward compatibility.
     * @param string $uri
     */
    public function __construct($uri = null)
    {
        $this->setUri($uri);
    }

    /**
     * Return the BOM if the file if it exists.
     * @return int|string
     */
    public function detect()
    {
        $str = file_get_contents($this->uri);

        foreach ($this->getBom('all') as $encoding => $bom) {
            if (0 === strncmp($str, $bom, strlen($bom))) {
                return $encoding;
            }
        }
    }

    /**
     * Add a BOM at the beginning of the file.
     * @param string $encoding
     * @return int
     */
    public function add($encoding = 'UTF-8')
    {
        $str = file_get_contents($this->uri);
        return file_put_contents($this->uri, $this->getBom($encoding) . $str);
    }

    /**
     * Remove the given BOM from the file.
     * @param string $encoding
     * @return int
     */
    public function remove($encoding)
    {
        $str = file_get_contents($this->uri);
        return file_put_contents($this->uri, substr($str, (strlen($this->getBom($encoding)))));
    }

    /**
     * Return a BOM string or an array of all BOM.
     * @param string $encoding
     * @return array|string
     */
    public function getBom($encoding = 'UTF-8')
    {
        $boms = array(
            'UTF-8'                => pack('CCC', 0xef, 0xbb, 0xbf),
            'UTF-16 Big Endian'    => pack('CC', 0xfe, 0xff),
            'UTF-16 Little Endian' => pack('CC', 0xff, 0xfe),
            'UTF-32 Big Endian'    => pack('CCCC', 0x00, 0x00, 0xfe, 0xff),
            'UTF-32 Little Endian' => pack('CCCC', 0xff, 0xfe, 0x00, 0x00),
            'SCSU'                 => pack('CCC', 0x0e, 0xfe, 0xff),
            'UTF-7 (1)'            => pack('CCCC', 0x2b, 0x2f, 0x76, 0x38),
            'UTF-7 (2)'            => pack('CCCC', 0x2b, 0x2f, 0x76, 0x39),
            'UTF-7 (3)'            => pack('CCCC', 0x2b, 0x2f, 0x76, 0x2b),
            'UTF-7 (4)'            => pack('CCCC', 0x2b, 0x2f, 0x76, 0x2f),
            'UTF-7 (5)'            => pack('CCCCC', 0x2b, 0x2f, 0x76, 0x38, 0x2d),
            'UTF-1'                => pack('CCC', 0xF7, 0x64, 0x4c),
            'UTF-EBCDIC'           => pack('CCCC', 0xdd, 0x73, 0x66, 0x73),
            'BOCU-1'               => pack('CCC', 0xfb, 0xee, 0x28),
            'GB-18030'             => pack('CCCC', 0x84, 0x31, 0x95, 0x33),
        );

        if ('all' == $encoding) {
            return $boms;
        }
        return $boms[$encoding];
    }

    /**
     * Get the URI file.
     * @return string
     */
    public function getUri()
    {
        return $this->uri;
    }

    /**
     * Set the URI File
     * @param $uri
     * @return $this
     * @throws Exception
     */
    public function setUri($uri)
    {
        if (!empty($uri) && !is_file($uri)) {
            throw new \Exception(sprintf('File %s not found.', $uri));
        }
        $this->uri = $uri;
        return $this;
    }

}


<?php

namespace NodePub\Common\Collections;

use Doctrine\Common\Collections\ArrayCollection;

class TaggedCollection extends ArrayCollection
{
    const DATE_FORMAT = 'F Y';

    protected $taggings;

    public function __construct(array $items = array())
    {
        parent::__construct($items);
        $this->expand();
    }

    /**
     * Returns associative array of tags and the slugs of items
     * with those tags
     * i.e. 'tagfoo' => array('foo', 'bar')
     *
     * Caches the result so it does the loop once.
     */
    public function getTaggings()
    {
        if (is_null($this->taggings)) {
            foreach ($this as $key => $item) {
                if (empty($item['tags'])) {
                    continue;
                }
                foreach ($item['tags'] as $tagging) {
                    if (!in_array($tagging, array_keys($item['tags']))) {
                        $this->taggings[$tagging] = array();
                    }

                    $this->taggings[$tagging][] = $key;
                }
            }
        }

        return $this->taggings;
    }

    /**
     * Returns array of all tag names
     */
    public function getTags()
    {
        return array_keys($this->getTaggings());
    }

    /**
     * Returns array of items tagged with the given tag
     */
    public function getByTag($tag)
    {
        $taggings = $this->getTaggings();

        if (array_key_exists($tag, $taggings)) {
            return $taggings[$tag];
        }

        return array();
    }

    /**
     * Expands each collection item with extra data
     */
    protected function expand()
    {
        foreach ($this as $key => $item) {
            $item['slug'] = $key;

            if (isset($item['date'])) {
                $item['formatted_date'] = date(self::DATE_FORMAT, $item['date']);
            }

            $this->set($key, $item);
        }
    }
}


<?php

/**
 * @file
 *
 * @package In2pire
 * @subpackage Cli
 * @author Nhat Tran <nhat.tran@inspire.vn>
 */

namespace In2pire\Cli\Command;

use In2pire\Component\Utility\Text;

/**
 * Command container.
 */
final class Container
{
    /**
     * Create command from id.
     *
     * @param string $command
     *   Command ID.
     * @param In2pire\Cli\CliApplication $app
     *   The running application
     *
     * @return In2pire\Cli\Command\CliCommand
     *   The created command.
     */
    public static function create($command, $app)
    {
        static $cache = [];
        $cacheKey = $command;

        if (isset($cache[$cacheKey]))  {
            $class = $cache[$cacheKey]['class'];
            $command = $cache[$cacheKey]['command'];
        } else {
            if (false === strpos($command, '.')) {
                // Not FQCN
                $class = __NAMESPACE__ . '\\' . String::convertToCamelCase($command);
            } else {
                // FQCN
                $class = explode('.', $command);
                $class = array_map(array('In2pire\\Component\\Utility\\Text', 'convertToCamelCase'), $class);
                $class = implode('\\', $class);
                $command = substr($command, strrpos($command, '.') + 1);
            }

            $cache[$cacheKey] = [
                'class' => $class,
                'command' => $command
            ];
        }

        if (!class_exists($class)) {
            throw new \RuntimeException('Unknow command ' . $cacheKey);
        }

        return new $class($app);
    }
}


<?php
/**
 * This file is part of the "Easy System" package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @author Damon Smith <damon.easy.system@gmail.com>
 */
namespace Es\Modules\Listener;

use Es\Cache\AbstractCache;
use Es\Modules\ModulesEvent;
use Es\Services\ServicesTrait;
use Es\System\ConfigTrait;

/**
 * Stores the system configuration in cache and restores it, if the
 * configuration was previously stored and the cache is enabled.
 */
class CacheConfigListener
{
    use ConfigTrait, ServicesTrait;

    /**
     * The cache adapter.
     *
     * @var \Es\Cache\Adapter\AbstractCache
     */
    protected $cache;

    /**
     * Sets the cache.
     *
     * @param \Es\Cache\AbstractCache $cache The cache adapter
     */
    public function setCache(AbstractCache $cache)
    {
        $this->cache = $cache->withNamespace('system');
    }

    /**
     * Gets the cache.
     *
     * @return \Es\Cache\AbstractCache The cache adapter
     */
    public function getCache()
    {
        if (! $this->cache) {
            $services = $this->getServices();
            $cache    = $services->get('Cache');
            $this->setCache($cache);
        }

        return $this->cache;
    }

    /**
     * Restores the system configuration from cache.
     *
     * @param \Es\Modules\ModulesEvent $event The modules event
     */
    public function doRestore(ModulesEvent $event)
    {
        $cache = $this->getCache();
        $data  = $cache->get('config');
        if ($data) {
            $services = $this->getServices();
            $services->set('Config', $data);
            $event->stopPropagation(true);
        }
    }

    /**
     * Stores the system configuration to cache.
     *
     * @param \Es\Modules\ModulesEvent $event The modules event
     */
    public function doStore(ModulesEvent $event)
    {
        $cache  = $this->getCache();
        $config = $this->getConfig();
        $cache->set('config', $config);
    }
}


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

use Xloit\Bridge\Zend\Validator\Username as UsernameValidator;
use Zend\Filter;
use Zend\Form\Element\Text;
use Zend\Form\ElementPrepareAwareInterface;
use Zend\Form\FormInterface;

/**
 * An {@link Username} class.
 *
 * @package Xloit\Bridge\Zend\Form\Element
 */
class Username extends Text implements ElementPrepareAwareInterface
{
    /**
     * Constructor to prevent {@link Username} from being loaded more than once.
     *
     * @param string|null $name
     * @param array       $options
     *
     * @throws \Zend\Form\Exception\InvalidArgumentException
     */
    public function __construct($name = 'username', $options = [])
    {
        $this->setLabel('Username');
        $this->setAttribute('placeholder', 'Username');
        $this->setAttribute('autocomplete', 'off');

        parent::__construct($name, $options);
    }

    /**
     * Remove the password before rendering if the form fails in order to avoid any security issue.
     *
     * @param FormInterface $form
     *
     * @return void
     */
    public function prepareElement(FormInterface $form)
    {
        $this->setValue('');
    }

    /**
     * Provide default input rules for this element and attaches an password validator.
     *
     * @return array
     */
    public function getInputSpecification()
    {
        return [
            'name'       => $this->getName(),
            'required'   => true,
            'filters'    => [
                Filter\StringTrim::class    => [
                    'name' => Filter\StringTrim::class
                ],
                Filter\StripNewlines::class => [
                    'name' => Filter\StripNewlines::class
                ]
            ],
            'validators' => [
                UsernameValidator::class => [
                    'name' => UsernameValidator::class
                ]
            ]
        ];
    }
}


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

use Zend\Filter;
use Zend\Form\Element\Select;
use Zend\Validator;

/**
 * A {@link YesNoSelect} class.
 *
 * @package Xloit\Bridge\Zend\Form\Element
 */
class YesNoSelect extends Select
{
    /**
     * Constructor to prevent {@link YesNoSelect} from being loaded more than once.
     *
     * @param string|null $name    Optional name for the element.
     * @param array       $options Optional options for the element.
     *
     * @throws \Zend\Form\Exception\InvalidArgumentException
     */
    public function __construct($name = null, $options = [])
    {
        parent::__construct($name, $options);

        $this->setEmptyOption('');
    }

    /**
     * Provide default input rules for this element and attaches an password validator.
     *
     * @return array
     */
    public function getInputSpecification()
    {
        return [
            'name'       => $this->getName(),
            'required'   => true,
            'filters'    => [
                Filter\StringTrim::class    => [
                    'name' => Filter\StringTrim::class
                ],
                Filter\StripNewlines::class => [
                    'name' => Filter\StripNewlines::class
                ],
                Filter\StripTags::class     => [
                    'name' => Filter\StripTags::class
                ]
            ],
            'validators' => [
                Validator\InArray::class => [
                    'name'    => Validator\InArray::class,
                    'options' => [
                        'haystack' => [
                            1 => 'Yes',
                            0 => 'No'
                        ]
                    ]
                ]
            ]
        ];
    }
}


<?php

namespace Bridge;

use Bridge\Action\AbstractAction;
use Bridge\Event\BridgeEvents;
use Bridge\Event\PostActionEvent;
use Bridge\Event\PreActionEvent;
use Bridge\Exception\KeyNotFoundInSetException;

/**
 * Service group.
 */
class Group
{
    /**
     * @var array Action collection
     */
    private $actions = array();

    /**
     * @var string Group name
     */
    private $name;

    /**
     * @var Service
     */
    private $service;

    /**
     * @param string $name Group name
     */
    public function __construct($name)
    {
        $this->name = $name;
    }

    /**
     * @param Service $service
     */
    public function setService(Service $service)
    {
        $this->service = $service;
    }

    /**
     * @return Service
     */
    public function getService()
    {
        return $this->service;
    }

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

    /**
     * Adds action.
     *
     * @param AbstractAction $action Group action
     *
     * @return $this
     */
    public function addAction(AbstractAction $action)
    {
        $action->setGroup($this);

        $this->actions[$action->getName()] = $action;

        return $this;
    }

    /**
     * @param string $name Action name
     *
     * @throws KeyNotFoundInSetException If action does not exist
     *
     * @return AbstractAction
     */
    public function getAction($name)
    {
        if (array_key_exists($name, $this->actions)) {
            return $this->actions[$name];
        }

        throw new KeyNotFoundInSetException($name, array_keys($this->actions), 'actions');
    }

    /**
     * Returns actions.
     *
     * @return AbstractAction[]
     */
    public function getActions()
    {
        return $this->actions;
    }

    /**
     * @param string $name      Action name
     * @param array  $arguments Arguments to be passed to action execution method
     *
     * @return mixed Action response
     */
    public function call($name, $arguments = array())
    {
        /** @var AbstractAction $action */
        $action = $this->getAction($name);

        if ($action instanceof RegistryAwareInterface) {
            $action->setRegistry($this->service->getRegistry());
        }

        $this->dispatchPreActionEvent($arguments, $action);

        $start = microtime(true);

        $response = $action->execute($arguments);

        $event = $this->dispatchPostActionEvent($arguments, $action, $response, microtime(true) - $start, $action->getExtraData());

        $response = $event->getResponse();

        return $response;
    }

    /**
     * @see Group::call()
     */
    public function __call($name, $arguments)
    {
        return $this->call($name, $arguments);
    }

    /**
     * @param array          $arguments Argument collection
     * @param AbstractAction $action    Action object
     */
    private function dispatchPreActionEvent(array $arguments, AbstractAction $action)
    {
        $this->service->getEventDispatcher()->dispatch(
            BridgeEvents::PRE_ACTION,
            new PreActionEvent($action, $arguments)
        );
    }

    /**
     * @param array          $arguments     Argument collection
     * @param AbstractAction $action        Action object
     * @param mixed          $response      Action response
     * @param float          $executionTime Total execution time
     * @param array          $extraData     Extra Data
     *
     * @return PostActionEvent
     */
    private function dispatchPostActionEvent(array $arguments, AbstractAction $action, $response, $executionTime, $extraData)
    {
        return $this->service->getEventDispatcher()->dispatch(
            BridgeEvents::POST_ACTION,
            new PostActionEvent($action, $arguments, $response, $executionTime, $extraData)
        );
    }
}


<?php namespace Ordercloud\Cart\Entities;

use Ordercloud\Entities\Products\Product;
use Ordercloud\Entities\Products\ProductOption;
use Ordercloud\Entities\Products\ProductOptionSet;

class CartItemOption
{
    /** @var ProductOptionSet */
    private $optionSet;
    /** @var ProductOption */
    private $option;

    /**
     * @param $optionSet
     * @param $option
     */
    public function __construct($optionSet, $option)
    {
        $this->optionSet = $optionSet;
        $this->option = $option;
    }

    /**
     * @param array   $selectedOptions
     * @param Product $product
     *
     * @return array|static[]
     */
    public static function createFromArray(array $selectedOptions, Product $product) // TODO
    {
        $options = [];

        foreach ($selectedOptions as $optionSetId => $optionId) {
            $optionSet = $product->getOptionSetByID($optionSetId);

            $option = $optionSet->getOptionByID($optionId);

            $options[] = new static($optionSet, $option);
        }

        return $options;
    }

    /**
     * @return ProductOptionSet
     */
    public function getOptionSet()
    {
        return $this->optionSet;
    }

    /**
     * @return ProductOption
     */
    public function getOption()
    {
        return $this->option;
    }
}


<?php

namespace Weew\Container;

use Weew\Container\Definitions\ClassDefinition;
use Weew\Container\Definitions\InterfaceDefinition;
use Weew\Container\Definitions\WildcardDefinition;
use Weew\Container\Exceptions\ImplementationNotFoundException;
use Weew\Container\Exceptions\TypeMismatchException;
use Weew\Container\Exceptions\ValueNotFoundException;

class Resolver {
    /**
     * @var IContainer
     */
    protected $container;

    /**
     * @var Reflector
     */
    protected $reflector;

    /**
     * @var bool
     */
    protected $strictMode = true;

    /**
     * @param IContainer $container
     * @param Reflector $reflector
     */
    public function __construct(
        IContainer $container,
        Reflector $reflector
    ) {
        $this->container = $container;
        $this->reflector = $reflector;
    }

    /**
     * @param string $id
     * @param array $args
     *
     * @return mixed
     * @throws ImplementationNotFoundException
     * @throws TypeMismatchException
     * @throws ValueNotFoundException
     */
    public function resolveWithoutDefinition($id, array $args = []) {
        if (class_exists($id)) {
            return $this->getClass(new ClassDefinition($id, null), $args);
        }

        if (interface_exists($id)) {
            throw new ImplementationNotFoundException(
                s('No implementation found in container for interface %s.', $id)
            );
        }

        throw new ValueNotFoundException(
            s('No value found in container for id %s.', $id)
        );
    }

    /**
     * @param IDefinition $definition
     * @param $id
     * @param array $args
     *
     * @return mixed
     * @throws TypeMismatchException
     */
    public function resolveDefinition(IDefinition $definition, $id, array $args = []) {
        if ($definition instanceof WildcardDefinition) {
            $value = $this->getWildcard($definition, $id, $args);
        } else if ($definition instanceof InterfaceDefinition) {
            $value = $this->getInterface($definition, $args);
        } else if ($definition instanceof ClassDefinition) {
            $value = $this->getClass($definition, $args);
        } else {
            $value = $definition->getValue();
        }

        return $value;
    }

    /**
     * @param ClassDefinition $definition
     * @param array $args
     *
     * @return mixed
     * @throws TypeMismatchException
     */
    public function getClass(ClassDefinition $definition, array $args = []) {
        $abstract = $definition->getValue();
        $class = $definition->getId();

        if (is_callable($abstract)) {
            $instance = $this->container->call($abstract, $args);
        } else if (is_object($abstract)) {
            $instance = $abstract;
        } else {
            if ($abstract === null) {
                $abstract = $class;
            }

            $instance = $this->reflector
                ->resolveClass($this->container, $abstract, $args);
        }

        $this->matchClassType($class, $instance);

        return $instance;
    }

    /**
     * @param InterfaceDefinition $definition
     * @param array $args
     *
     * @return mixed
     * @throws TypeMismatchException
     */
    public function getInterface(InterfaceDefinition $definition, array $args = []) {
        $abstract = $definition->getValue();
        $interface = $definition->getId();
        $instance = $this->resolveAbstract($abstract, $args);
        $this->matchClassType($interface, $instance);

        return $instance;
    }

    /**
     * @param IDefinition $definition
     * @param $id
     * @param $args
     *
     * @return mixed|null
     * @throws TypeMismatchException
     */
    public function getWildcard(IDefinition $definition, $id, $args) {
        $abstract = $definition->getValue();
        $args['abstract'] = $id;
        $instance = $this->resolveAbstract($abstract, $args);
        $this->matchClassType($id, $instance);

        return $instance;
    }

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

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

    /**
     * @param $abstract
     * @param array $args
     *
     * @return mixed
     */
    protected function resolveAbstract($abstract, array $args) {
        if (is_callable($abstract)) {
            return $this->container->call($abstract, $args);
        } else if (is_object($abstract)) {
            return $abstract;
        } else if (class_exists($abstract)) {
            return $this->getClass(new ClassDefinition($abstract, null), $args);
        }

        return null;
    }

    /**
     * @param $class
     * @param $instance
     *
     * @throws TypeMismatchException
     */
    protected function matchClassType($class, $instance) {
        if ( ! $this->isInStrictMode()) {
            return;
        }

        if ( ! $instance instanceof $class) {
            throw new TypeMismatchException(
                s(
                    'Container expects an implementation of type %s, %s given.',
                    $class, get_type($instance)
                )
            );
        }
    }
}


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

namespace cascade\components\web\themes;

/**
 * IdentityAsset [[@doctodo class_description:cascade\components\web\themes\IdentityAsset]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
abstract class IdentityAsset extends AssetBundle
{
    /**
     * Get logo path.
     */
    abstract public function getLogoPath();

    /**
     * Get logo.
     *
     * @param [[@doctodo param_type:size]] $size [[@doctodo param_description:size]] [optional]
     *
     * @return [[@doctodo return_type:getLogo]] [[@doctodo return_description:getLogo]]
     */
    public function getLogo($size = null)
    {
        if (!$this->logoPath || !file_exists($this->logoPath)) {
            return;
        }
        $cacheLogo = $this->sizeImageCache($this->logoPath, $size);
        if ($cacheLogo) {
            return $this->getCacheAssetUrl($cacheLogo);
        }

        return false;
    }
}


<?php
namespace asbamboo\di;

use asbamboo\di\exception\NotExistedServiceMappingException;

/**
 * 用于[asbamboo\di\ServiceMapping(ServiceMappingCollectionInterface  $mappings)]
 *
 * @author 李春寅 <licy2013@aliyun.com>
 * @since 2018年3月16日
 */
class ServiceMappingCollection implements ServiceMappingCollectionInterface
{
    /**
     * @var array
     */
    protected $service_mappings = [];

    /**
     * {@inheritDoc}
     * @see \asbamboo\di\ServiceMappingCollectionInterface::add()
     */
    public function add(ServiceMappingInterface $ServiceMapping): ServiceMappingCollectionInterface
    {
        $this->service_mappings[$ServiceMapping->getId()]  = $ServiceMapping;

        return $this;
    }

    /**
     * {@inheritDoc}
     * @see \Countable::count()
     */
    public function count()
    {
        return count($this->service_mappings);
    }

    /**
     * {@inheritDoc}
     * @see \IteratorAggregate::getIterator()
     */
    public function getIterator()
    {
        return new \ArrayIterator($this->service_mappings);
    }

    /**
     * {@inheritDoc}
     * @see \asbamboo\di\ServiceMappingCollectionInterface::remove()
     */
    public function remove(string $id): ServiceMappingCollectionInterface
    {
        unset($this->service_mappings[$id]);

        return $this;
    }

    /**
     *
     * {@inheritDoc}
     * @see \asbamboo\di\ServiceMappingCollectionInterface::get()
     */
    public function get(string $id): ServiceMappingInterface
    {
        if(!$this->has($id)){
            throw new NotExistedServiceMappingException(sprintf('唯一标识符为%s的服务配置信息不存在。', $id));
        }
        return $this->service_mappings[$id];
    }

    /**
     * {@inheritDoc}
     * @see \asbamboo\di\ServiceMappingCollectionInterface::has()
     */
    public function has(string $id): bool
    {
        return isset($this->service_mappings[$id]);
    }
}