<?php
namespace Poirot\Queue\Queue;

use Poirot\Queue\Exception\exIOError;
use Poirot\Queue\Exception\exReadError;
use Poirot\Queue\Exception\exWriteError;
use Poirot\Queue\Interfaces\iPayload;
use Poirot\Queue\Interfaces\iPayloadQueued;
use Poirot\Queue\Interfaces\iQueueDriver;
use Poirot\Queue\Payload\QueuedPayload;
use Poirot\Storage\Interchange\SerializeInterchange;

class PdoQueue
    implements iQueueDriver
{
    /** @var \PDO */
    protected $conn;
    protected $table;

    /** @var SerializeInterchange */
    protected $_c_interchangable;

    /**
     * Constructor.
     *
     * @param \PDO   $conn
     * @param string $table
     */
    function __construct(\PDO $conn, $table = null)
    {
        $this->conn  = $conn;
        $this->table = ($table === null) ? 'Queue' : (string) $table;
    }

    /**
     * Push To Queue
     *
     * @param iPayload|iPayloadQueued $payload Serializable payload
     * @param string   $queue
     *
     * @return iPayloadQueued
     * @throws exIOError
     */
    function push($payload, $queue = null)
    {
        $payload = clone $payload;

        if (null === $queue && $payload instanceof iPayloadQueued)
            $queue = $payload->getQueue();

        try
        {
            $qPayload = $payload;
            if (! $payload instanceof iPayloadQueued ) {
                $qPayload = new QueuedPayload($payload);
                $qPayload = $qPayload
                    ->withUID( \Poirot\Std\generateUniqueIdentifier(24) )
                ;
            }

            $qPayload = $qPayload->withQueue( $this->_normalizeQueueName($queue) );

            ## Persist Queued Payload
            #
            $uid      = $qPayload->getUID();
            $qName    = $qPayload->getQueue();
            $sPayload = addslashes(serialize($qPayload));
            $time     = $qPayload->getCreatedTimestamp();

            $sql = "INSERT INTO `{$this->table}`
                   (`task_id`, `queue_name`, `payload`, `created_timestamp`, `is_pop`)
                   VALUES ('$uid', '$qName', '$sPayload', '$time', '0');
            ";

            if ( false === $this->conn->exec($sql) )
                throw new \Exception( $this->conn->errorInfo() );

        } catch (\Exception $e) {
            throw new exWriteError($e->getMessage(), $e->getCode(), $e);
        }

        ## Persist Queue Job
        #
        return $qPayload;
    }

    /**
     * Pop From Queue
     *
     * note: when you pop a message from queue you have to
     *       release it when worker done with it.
     *
     *
     * @param string $queue
     *
     * @return iPayloadQueued|null
     * @throws exIOError
     */
    function pop($queue = null)
    {
        $qName = $this->_normalizeQueueName($queue);

        try
        {
            // Find
            //
            $this->conn->beginTransaction();

            $sql = "SELECT * FROM `{$this->table}` WHERE `queue_name` = '$qName' and `is_pop` = 0;";
            $stm = $this->conn->prepare($sql);
            $stm->execute();
            $stm->setFetchMode(\PDO::FETCH_ASSOC);
            $queued = $stm->fetch();

            // Update
            //
            if ($queued ) {
                $sql = "UPDATE `{$this->table}` SET `is_pop` = 1 WHERE `task_id` = '{$queued['task_id']}';";
                $this->conn->exec($sql);
            }

            $this->conn->commit();

        } catch (\Exception $e) {
            throw new exReadError(sprintf('Error While Read From PDO Client: (%s).', $e->getCode()), 0, $e);
        }

        if (! $queued )
            // Nothing In Queue..
            return null;

        $payload = unserialize($queued['payload']);
        return $payload;
    }

    /**
     * Release an Specific From Queue By Removing It
     *
     * @param iPayloadQueued|string $id
     * @param null|string           $queue
     *
     * @return void
     * @throws exIOError
     */
    function release($id, $queue = null)
    {
        if ( $id instanceof iPayloadQueued ) {
            $arg   = $id;
            $id    = $arg->getUID();
            $queue = $arg->getQueue();
        }

        $queue = $this->_normalizeQueueName($queue);

        try {

            $sql = "DELETE FROM `{$this->table}` WHERE `task_id` = '{$id}' and `queue_name` = '{$queue}';";
            $this->conn->exec($sql);

        } catch (\Exception $e) {
            throw new exWriteError('Error While Delete From MySql Client.', $e->getCode(), $e);
        }
    }

    /**
     * Find Queued Payload By Given ID
     *
     * @param string $id
     * @param string $queue
     *
     * @return iPayloadQueued|null
     * @throws exIOError
     */
    function findByID($id, $queue = null)
    {
        $queue = $this->_normalizeQueueName($queue);

        try {
            $sql = "SELECT * FROM `{$this->table}` WHERE `queue_name` = '$queue' and `task_id` = '$id';";

            $stm = $this->conn->prepare($sql);
            $stm->execute();
            $stm->setFetchMode(\PDO::FETCH_ASSOC);

            if (! $queued = $stm->fetch() )
                return null;

        } catch (\Exception $e) {
            throw new exReadError('Error While Read From MySql Client.', $e->getCode(), $e);
        }

        $payload = unserialize($queued['payload']);
        return $payload;
    }

    /**
     * Get Queue Size
     *
     * @param string $queue
     *
     * @return int
     * @throws exIOError
     */
    function size($queue = null)
    {
        $queue = $this->_normalizeQueueName($queue);

        try {
            $sql = "SELECT COUNT(*) as `count_queue` FROM `{$this->table}` WHERE `queue_name` = '$queue';";

            $stm = $this->conn->prepare($sql);
            $stm->execute();
            $stm->setFetchMode(\PDO::FETCH_ASSOC);

            $queued = $stm->fetch();

        } catch (\Exception $e) {
            throw new exReadError('Error While Read From MySql Client.', $e->getCode(), $e);
        }

        return (int) $queued['count_queue'];
    }

    /**
     * Get Queues List
     *
     * @return string[]
     * @throws exIOError
     */
    function listQueues()
    {
        try {

            $sql = "SELECT `queue_name` FROM `{$this->table}` GROUP BY `queue_name`;";

            $stm = $this->conn->prepare($sql);
            $stm->execute();
            $stm->setFetchMode(\PDO::FETCH_ASSOC);

            $csr = $stm->fetchAll();

        } catch (\Exception $e) {
            throw new exReadError('Error While Read From MySql Client.', $e->getCode(), $e);
        }

        $list = [];
        foreach ($csr as $item)
            $list[] = $item['queue_name'];

        return $list;
    }

    // ..

    /**
     * @return SerializeInterchange
     */
    protected function _interchangeable()
    {
        if (! $this->_c_interchangable)
            $this->_c_interchangable = new SerializeInterchange;

        return $this->_c_interchangable;
    }

    /**
     * @param string $queue
     * @return string
     */
    protected function _normalizeQueueName($queue)
    {
        if ($queue === null)
            return $queue = 'general';

        return strtolower( (string) $queue );
    }
}


<?php

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

namespace Chill\CustomFieldsBundle\CustomFields;

use Chill\CustomFieldsBundle\CustomFields\CustomFieldInterface;
use Chill\CustomFieldsBundle\Entity\CustomField;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\GreaterThanOrEqual;
use Symfony\Component\Validator\Constraints\LessThanOrEqual;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Bundle\TwigBundle\TwigEngine;
use Chill\MainBundle\Templating\TranslatableStringHelper;

/**
 * Create a custom field number.
 *
 * This number may have a min and max value, and a precision.
 *
 * @author Julien Fastré <julien.fastre@champs-libres.coop>
 * @author Marc Ducobu <marc@champs-libres.coop>
 */
class CustomFieldNumber extends AbstractCustomField
{
    /**
     * key for the minimal value of the field
     */
    const MIN = 'min';
    const MAX = 'max';
    const SCALE = 'scale';
    const POST_TEXT = 'post_text';

    /**
     *
     * @var TwigEngine
     */
    private $templating = NULL;

    /**
     *
     * @var TranslatableStringHelper
     */
    private $translatableStringHelper = NULL;

    public function __construct(TwigEngine $templating, TranslatableStringHelper $translatableStringHelper)
    {
        $this->templating = $templating;
        $this->translatableStringHelper = $translatableStringHelper;
    }

    public function buildForm(FormBuilderInterface $builder, CustomField $customField)
    {
        $options = $customField->getOptions();

        //select the type depending to the SCALE
        $type = ($options[self::SCALE] === 0 or $options[self::SCALE] === NULL)?
                'integer' : 'number';

        $fieldOptions = $this->prepareFieldOptions($customField, $type);

        $builder->add($customField->getSlug(), $type, $fieldOptions);
    }

    /**
     * prepare the options'form field
     *
     * @param CustomField $customField
     * @param string $type
     * @return mixed[]
     */
    private function prepareFieldOptions(CustomField $customField, $type)
    {
        $options = $customField->getOptions();

        /**
         * @var mixed[] the formField options
         */
        $fieldOptions = array();

        // add required
        $fieldOptions['required'] = False;

        //add label
        $fieldOptions['label'] = $this->translatableStringHelper->localize($customField->getName());

        // add constraints if required
        if ($options[self::MIN] !== NULL) {
            $fieldOptions['constraints'][] = new GreaterThanOrEqual(array('value' => $options[self::MIN]));
        }
        if ($options[self::MAX] !== NULL) {
            $fieldOptions['constraints'][] = new LessThanOrEqual(array('value' => $options[self::MAX]));
        }

        // add precision to options if required
        if ($type === 'number') {
            $fieldOptions['scale'] = $options[self::SCALE];
        }

        if (!empty($options[self::POST_TEXT])) {
            $fieldOptions['post_text'] = $options[self::POST_TEXT];
        }

        return $fieldOptions;
    }

    public function buildOptionsForm(FormBuilderInterface $builder)
    {
        return $builder
                ->add(self::MIN, 'number', array(
                    'scale' => 2,
                    'label' => 'Greater or equal than',
                    'required' => false
                ))
                ->add(self::MAX, 'number', array(
                    'scale' => 2,
                    'label' => 'Lesser or equal than',
                    'required' => false
                ))
                ->add(self::SCALE, 'integer', array(
                    'scale' => 0,
                    'label' => 'Precision',
                    'constraints' => array(
                        new GreaterThanOrEqual(array('value' => 0))
                    )
                ))
                ->add(self::POST_TEXT, 'text', array(
                    'label' => 'Text after the field'
                ))
                ;

    }

    public function deserialize($serialized, CustomField $customField)
    {
        return $serialized;
    }

    public function getName()
    {
        return 'Number';
    }

    public function render($value, CustomField $customField, $documentType = 'html')
    {
        $template = 'ChillCustomFieldsBundle:CustomFieldsRendering:number.'
                .$documentType.'.twig';
        $options = $customField->getOptions();

        return $this->templating
            ->render($template, array(
                'number' => $value,
                'scale' => $options[self::SCALE],
                'post' => $options[self::POST_TEXT]
                ));
    }

    public function serialize($value, CustomField $customField)
    {
        return $value;
    }

}


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

namespace Praxigento\BonusHybrid\Service\Calc\Bonus;

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

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

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

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

    /**
     * Get period and calculation data for all related calculation types.
     *
     * @return array [$compressCalc, $courtesyPeriod, $courtesyCalc]
     * @throws \Exception
     */
    private function getCalcData()
    {
        /**
         * Get period & calc data for Courtesy based on TV.
         */
        $req = new AGetPeriodRequest();
        $req->setBaseCalcTypeCode(Cfg::CODE_TYPE_CALC_VALUE_TV);
        $req->setDepCalcTypeCode(Cfg::CODE_TYPE_CALC_BONUS_COURTESY);
        /** @var AGetPeriodResponse $resp */
        $resp = $this->servPeriodGet->exec($req);
        /** @var \Praxigento\BonusBase\Repo\Data\Period $courtesyPeriod */
        $courtesyPeriod = $resp->getDepPeriodData();
        /** @var \Praxigento\BonusBase\Repo\Data\Calculation $courtesyCalc */
        $courtesyCalc = $resp->getDepCalcData();
        /**
         * Get period and calc data for compression calc (basic for TV volumes).
         */
        $req = new AGetPeriodRequest();
        $req->setBaseCalcTypeCode(Cfg::CODE_TYPE_CALC_COMPRESS_PHASE1);
        $req->setDepCalcTypeCode(Cfg::CODE_TYPE_CALC_VALUE_TV);
        $req->setDepIgnoreComplete(true);
        /** @var AGetPeriodResponse $resp */
        $resp = $this->servPeriodGet->exec($req);
        /** @var \Praxigento\BonusBase\Repo\Data\Calculation $compressCalc */
        $compressCalc = $resp->getBaseCalcData();
        /**
         * Compose result.
         */
        $result = [$compressCalc, $courtesyPeriod, $courtesyCalc];
        return $result;
    }

    /**
     * Convert bonus data to transactions data.
     *
     * @param \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Data\Bonus[] $bonus [custId => bonusValue]
     * @param \Praxigento\BonusBase\Repo\Data\Period $period
     * @return \Praxigento\Accounting\Repo\Data\Transaction[]
     */
    private function getTransactions($bonus, $period)
    {
        $dsEnd = $period->getDstampEnd();
        $dateApplied = $this->hlpPeriod->getTimestampUpTo($dsEnd);
        $yyyymm = substr($dsEnd, 0, 6);
        $note = "Courtesy ($yyyymm)";
        $result = $this->hlpTrans->exec($bonus, $dateApplied, $note);
        return $result;
    }

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

            ]);
        }
    }

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


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

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

namespace EasyWeChat\Card;

use Doctrine\Common\Cache\Cache;
use Doctrine\Common\Cache\FilesystemCache;
use EasyWeChat\Core\AbstractAPI;
use EasyWeChat\Support\Arr;
use Psr\Http\Message\ResponseInterface;

class Card extends AbstractAPI
{
    /**
     * Cache.
     *
     * @var Cache
     */
    protected $cache;

    /**
     * Ticket cache key.
     *
     * @var string
     */
    protected $ticketCacheKey;

    /**
     * Ticket cache prefix.
     *
     * @var string
     */
    protected $ticketCachePrefix = 'overtrue.wechat.card_api_ticket.';

    const API_GET_COLORS = 'https://api.weixin.qq.com/card/getcolors';
    const API_CREATE_CARD = 'https://api.weixin.qq.com/card/create';
    const API_CREATE_QRCODE = 'https://api.weixin.qq.com/card/qrcode/create';
    const API_SHOW_QRCODE = 'https://mp.weixin.qq.com/cgi-bin/showqrcode';
    const API_GET_CARD_TICKET = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket';
    const API_CREATE_LANDING_PAGE = 'https://api.weixin.qq.com/card/landingpage/create';
    const API_DEPOSIT_CODE = 'https://api.weixin.qq.com/card/code/deposit';
    const API_GET_DEPOSIT_COUNT = 'https://api.weixin.qq.com/card/code/getdepositcount';
    const API_CHECK_CODE = 'https://api.weixin.qq.com/card/code/checkcode';
    const API_GET_HTML = 'https://api.weixin.qq.com/card/mpnews/gethtml';
    const API_SET_TEST_WHITE_LIST = 'https://api.weixin.qq.com/card/testwhitelist/set';
    const API_GET_CODE = 'https://api.weixin.qq.com/card/code/get';
    const API_CONSUME_CARD = 'https://api.weixin.qq.com/card/code/consume';
    const API_DECRYPT_CODE = 'https://api.weixin.qq.com/card/code/decrypt';
    const API_GET_CARD_LIST = 'https://api.weixin.qq.com/card/user/getcardlist';
    const API_GET_CARD = 'https://api.weixin.qq.com/card/get';
    const API_LIST_CARD = 'https://api.weixin.qq.com/card/batchget';
    const API_UPDATE_CARD = 'https://api.weixin.qq.com/card/update';
    const API_SET_PAY_CELL = 'https://api.weixin.qq.com/card/paycell/set';
    const API_MODIFY_STOCK = 'https://api.weixin.qq.com/card/modifystock';
    const API_UPDATE_CODE = 'https://api.weixin.qq.com/card/code/update';
    const API_DELETE_CARD = 'https://api.weixin.qq.com/card/delete';
    const API_DISABLE_CARD = 'https://api.weixin.qq.com/card/code/unavailable';
    const API_ACTIVATE_MEMBER_CARD = 'https://api.weixin.qq.com/card/membercard/activate';
    const API_ACTIVATE_MEMBER_USER_FORM = 'https://api.weixin.qq.com/card/membercard/activateuserform/set';
    const API_GET_MEMBER_USER_INFO = 'https://api.weixin.qq.com/card/membercard/userinfo/get';
    const API_UPDATE_MEMBER_CARD_USER = 'https://api.weixin.qq.com/card/membercard/updateuser';
    const API_CREATE_SUB_MERCHANT = 'https://api.weixin.qq.com/card/submerchant/submit';
    const API_UPDATE_SUB_MERCHANT = 'https://api.weixin.qq.com/card/submerchant/update';
    const API_GET_SUB_MERCHANT = 'https://api.weixin.qq.com/card/submerchant/get';
    const API_LIST_SUB_MERCHANT = 'https://api.weixin.qq.com/card/submerchant/batchget';
    const API_GET_CATEGORIES = 'https://api.weixin.qq.com/card/getapplyprotocol';
    const API_ACTIVATE_GENERAL_CARD = 'https://api.weixin.qq.com/card/generalcard/activate';
    const API_UPDATE_GENERAL_CARD_USER = 'https://api.weixin.qq.com/card/generalcard/updateuser';

    /**
     * 获取卡券颜色.
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function getColors()
    {
        return $this->parseJSON('get', [self::API_GET_COLORS]);
    }

    /**
     * 创建卡券.
     *
     * @param string $cardType
     * @param array  $baseInfo
     * @param array  $especial
     * @param array  $advancedInfo
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function create($cardType = 'member_card', array $baseInfo = [], array $especial = [], array $advancedInfo = [])
    {
        $params = [
            'card' => [
                'card_type' => strtoupper($cardType),
                strtolower($cardType) => array_merge(['base_info' => $baseInfo], $especial, ['advanced_info' => $advancedInfo]),
            ],
        ];

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

    /**
     * 创建二维码.
     *
     * @param array $cards
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function QRCode(array $cards = [])
    {
        return $this->parseJSON('json', [self::API_CREATE_QRCODE, $cards]);
    }

    /**
     * ticket 换取二维码图片.
     *
     * @param string $ticket
     *
     * @return array
     */
    public function showQRCode($ticket = null)
    {
        $params = [
            'ticket' => $ticket,
        ];

        $http = $this->getHttp();

        /** @var ResponseInterface $response */
        $response = $http->get(self::API_SHOW_QRCODE, $params);

        return [
            'status' => $response->getStatusCode(),
            'reason' => $response->getReasonPhrase(),
            'headers' => $response->getHeaders(),
            'body' => strval($response->getBody()),
            'url' => self::API_SHOW_QRCODE.'?'.http_build_query($params),
        ];
    }

    /**
     * 通过ticket换取二维码 链接.
     *
     * @param string $ticket
     *
     * @return string
     */
    public function getQRCodeUrl($ticket)
    {
        return self::API_SHOW_QRCODE.'?ticket='.$ticket;
    }

    /**
     * 获取 卡券 Api_ticket.
     *
     * @param bool $refresh 是否强制刷新
     *
     * @return string $apiTicket
     */
    public function getAPITicket($refresh = false)
    {
        $key = $this->getTicketCacheKey();

        $ticket = $this->getCache()->fetch($key);

        if (!$ticket || $refresh) {
            $result = $this->parseJSON('get', [self::API_GET_CARD_TICKET, ['type' => 'wx_card']]);

            $this->getCache()->save($key, $result['ticket'], $result['expires_in'] - 500);

            return $result['ticket'];
        }

        return $ticket;
    }

    /**
     * 微信卡券：JSAPI 卡券发放.
     *
     * @param array $cards
     *
     * @return string
     */
    public function jsConfigForAssign(array $cards)
    {
        return json_encode(array_map(function ($card) {
            return $this->attachExtension($card['card_id'], $card);
        }, $cards));
    }

    /**
     * 生成 js添加到卡包 需要的 card_list 项.
     *
     * @param string $cardId
     * @param array  $extension
     *
     * @return string
     */
    public function attachExtension($cardId, array $extension = [])
    {
        $timestamp = time();
        $ext = [
            'code' => Arr::get($extension, 'code'),
            'openid' => Arr::get($extension, 'openid', Arr::get($extension, 'open_id')),
            'timestamp' => $timestamp,
            'outer_id' => Arr::get($extension, 'outer_id'),
            'balance' => Arr::get($extension, 'balance'),
            'fixed_begintimestamp' => Arr::get($extension, 'fixed_begintimestamp'),
            'outer_str' => Arr::get($extension, 'outer_str'),
        ];
        $ext['signature'] = $this->getSignature(
            $this->getAPITicket(),
            $timestamp,
            $cardId,
            $ext['code'],
            $ext['openid'],
            $ext['balance']
        );

        return [
            'cardId' => $cardId,
            'cardExt' => json_encode($ext),
        ];
    }

    /**
     * 生成签名.
     *
     * @return string
     */
    public function getSignature()
    {
        $params = func_get_args();
        sort($params, SORT_STRING);

        return sha1(implode($params));
    }

    /**
     * 创建货架接口.
     *
     * @param string $banner
     * @param string $pageTitle
     * @param bool   $canShare
     * @param string $scene     [SCENE_NEAR_BY 附近,SCENE_MENU 自定义菜单,SCENE_QRCODE 二维码,SCENE_ARTICLE 公众号文章,
     *                          SCENE_H5 h5页面,SCENE_IVR 自动回复,SCENE_CARD_CUSTOM_CELL 卡券自定义cell]
     * @param array  $cardList
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function createLandingPage($banner, $pageTitle, $canShare, $scene, $cardList)
    {
        $params = [
            'banner' => $banner,
            'page_title' => $pageTitle,
            'can_share' => $canShare,
            'scene' => $scene,
            'card_list' => $cardList,
        ];

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

    /**
     * 导入code接口.
     *
     * @param string $cardId
     * @param array  $code
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function deposit($cardId, $code)
    {
        $params = [
            'card_id' => $cardId,
            'code' => $code,
        ];

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

    /**
     * 查询导入code数目.
     *
     * @param string $cardId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function getDepositedCount($cardId)
    {
        $params = [
            'card_id' => $cardId,
        ];

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

    /**
     * 核查code接口.
     *
     * @param string $cardId
     * @param array  $code
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function checkCode($cardId, $code)
    {
        $params = [
            'card_id' => $cardId,
            'code' => $code,
        ];

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

    /**
     * 查询Code接口.
     *
     * @param string $code
     * @param bool   $checkConsume
     * @param string $cardId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function getCode($code, $checkConsume, $cardId)
    {
        $params = [
            'code' => $code,
            'check_consume' => $checkConsume,
            'card_id' => $cardId,
        ];

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

    /**
     * 核销Code接口.
     *
     * @param string $code
     * @param string $cardId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function consume($code, $cardId = null)
    {
        if (strlen($code) === 28 && $cardId && strlen($cardId) !== 28) {
            list($code, $cardId) = [$cardId, $code];
        }

        $params = [
            'code' => $code,
        ];

        if ($cardId) {
            $params['card_id'] = $cardId;
        }

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

    /**
     * Code解码接口.
     *
     * @param string $encryptedCode
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function decryptCode($encryptedCode)
    {
        $params = [
            'encrypt_code' => $encryptedCode,
        ];

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

    /**
     * 图文消息群发卡券.
     *
     * @param string $cardId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function getHtml($cardId)
    {
        $params = [
            'card_id' => $cardId,
        ];

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

    /**
     * 设置测试白名单.
     *
     * @param array $openids
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function setTestWhitelist($openids)
    {
        $params = [
            'openid' => $openids,
        ];

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

    /**
     * 设置测试白名单(by username).
     *
     * @param array $usernames
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function setTestWhitelistByUsername($usernames)
    {
        $params = [
            'username' => $usernames,
        ];

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

    /**
     * 获取用户已领取卡券接口.
     *
     * @param string $openid
     * @param string $cardId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function getUserCards($openid, $cardId = '')
    {
        $params = [
            'openid' => $openid,
            'card_id' => $cardId,
        ];

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

    /**
     * 查看卡券详情.
     *
     * @param string $cardId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function getCard($cardId)
    {
        $params = [
            'card_id' => $cardId,
        ];

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

    /**
     * 批量查询卡列表.
     *
     * @param int    $offset
     * @param int    $count
     * @param string $statusList
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function lists($offset = 0, $count = 10, $statusList = 'CARD_STATUS_VERIFY_OK')
    {
        $params = [
            'offset' => $offset,
            'count' => $count,
            'status_list' => $statusList,
        ];

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

    /**
     * 更改卡券信息接口 and 设置跟随推荐接口.
     *
     * @param string $cardId
     * @param string $type
     * @param array  $baseInfo
     * @param array  $especial
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function update($cardId, $type, $baseInfo = [], $especial = [])
    {
        $card = [];
        $card['card_id'] = $cardId;
        $card[$type] = [];

        $cardInfo = [];
        if ($baseInfo) {
            $cardInfo['base_info'] = $baseInfo;
        }

        $card[$type] = array_merge($cardInfo, $especial);

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

    /**
     * 设置微信买单接口.
     * 设置买单的 card_id 必须已经配置了门店，否则会报错.
     *
     * @param string $cardId
     * @param bool   $isOpen
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function setPayCell($cardId, $isOpen = true)
    {
        $params = [
            'card_id' => $cardId,
            'is_open' => $isOpen,
        ];

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

    /**
     * 增加库存.
     *
     * @param string $cardId
     * @param int    $amount
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function increaseStock($cardId, $amount)
    {
        return $this->updateStock($cardId, $amount, 'increase');
    }

    /**
     * 减少库存.
     *
     * @param string $cardId
     * @param int    $amount
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function reduceStock($cardId, $amount)
    {
        return $this->updateStock($cardId, $amount, 'reduce');
    }

    /**
     * 修改库存接口.
     *
     * @param string $cardId
     * @param int    $amount
     * @param string $action
     *
     * @return \EasyWeChat\Support\Collection
     */
    protected function updateStock($cardId, $amount, $action = 'increase')
    {
        $key = $action === 'increase' ? 'increase_stock_value' : 'reduce_stock_value';
        $params = [
            'card_id' => $cardId,
            $key => abs($amount),
        ];

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

    /**
     * 更改Code接口.
     *
     * @param string $code
     * @param string $newCode
     * @param array  $cardId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function updateCode($code, $newCode, $cardId = [])
    {
        $params = [
            'code' => $code,
            'new_code' => $newCode,
            'card_id' => $cardId,
        ];

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

    /**
     * 删除卡券接口.
     *
     * @param string $cardId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function delete($cardId)
    {
        $params = [
            'card_id' => $cardId,
        ];

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

    /**
     * 设置卡券失效.
     *
     * @param string $code
     * @param string $cardId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function disable($code, $cardId = '')
    {
        $params = [
            'code' => $code,
            'card_id' => $cardId,
        ];

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

    /**
     * 会员卡接口激活.
     *
     * @param array $info
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function activate($info = [], $cardType = 'member_card')
    {
        if ($cardType === 'general_card') {
            return $this->parseJSON('json', [self::API_ACTIVATE_GENERAL_CARD, $info]);
        }

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

    /**
     * 设置开卡字段接口.
     *
     * @param string $cardId
     * @param array  $requiredForm
     * @param array  $optionalForm
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function activateUserForm($cardId, array $requiredForm = [], array $optionalForm = [])
    {
        $params = array_merge(['card_id' => $cardId], $requiredForm, $optionalForm);

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

    /**
     * 拉取会员信息接口.
     *
     * @param string $cardId
     * @param string $code
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function getMemberCardUser($cardId, $code)
    {
        $params = [
            'card_id' => $cardId,
            'code' => $code,
        ];

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

    /**
     * 更新会员信息.
     *
     * @param array $params
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function updateMemberCardUser(array $params = [])
    {
        return $this->parseJSON('json', [self::API_UPDATE_MEMBER_CARD_USER, $params]);
    }

    /**
     * 更新通用员信息.
     *
     * @param array $params
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function updateGeneralCardUser(array $params = [])
    {
        return $this->parseJSON('json', [self::API_UPDATE_GENERAL_CARD_USER, $params]);
    }

    /**
     * 添加子商户.
     *
     * @param array $info
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function createSubMerchant(array $info = [])
    {
        $params = [
            'info' => Arr::only($info, [
                'brand_name',
                'logo_url',
                'protocol',
                'end_time',
                'primary_category_id',
                'secondary_category_id',
                'agreement_media_id',
                'operator_media_id',
                'app_id',
            ]),
        ];

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

    /**
     * 更新子商户.
     *
     * @param int   $merchantId
     * @param array $info
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function updateSubMerchant($merchantId, array $info = [])
    {
        $params = [
            'info' => array_merge(['merchant_id' => $merchantId],
                Arr::only($info, [
                    'brand_name',
                    'logo_url',
                    'protocol',
                    'end_time',
                    'primary_category_id',
                    'secondary_category_id',
                    'agreement_media_id',
                    'operator_media_id',
                    'app_id',
                ])),
        ];

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

    /**
     * 获取子商户信息.
     *
     * @param int $merchantId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function getSubMerchant($merchantId)
    {
        return $this->parseJSON('json', [self::API_GET_SUB_MERCHANT, ['merchant_id' => $merchantId]]);
    }

    /**
     * 批量获取子商户信息.
     *
     * @param int    $beginId
     * @param int    $limit
     * @param string $status
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function listSubMerchants($beginId = 0, $limit = 50, $status = 'CHECKING')
    {
        $params = [
            'begin_id' => $beginId,
            'limit' => $limit,
            'status' => $status,
        ];

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

    /**
     * 卡券开放类目查询接口.
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function getCategories()
    {
        return $this->parseJSON('get', [self::API_GET_CATEGORIES]);
    }

    /**
     * Set cache manager.
     *
     * @param \Doctrine\Common\Cache\Cache $cache
     *
     * @return $this
     */
    public function setCache(Cache $cache)
    {
        $this->cache = $cache;

        return $this;
    }

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

    /**
     * Set Api_ticket cache prifix.
     *
     * @param string $prefix
     *
     * @return $this
     */
    public function setTicketCachePrefix($prefix)
    {
        $this->ticketCachePrefix = $prefix;

        return $this;
    }

    /**
     * Set Api_ticket cache key.
     *
     * @param string $cacheKey
     *
     * @return $this
     */
    public function setTicketCacheKey($cacheKey)
    {
        $this->ticketCacheKey = $cacheKey;

        return $this;
    }

    /**
     * Get ApiTicket token cache key.
     *
     * @return string
     */
    public function getTicketCacheKey()
    {
        if (is_null($this->ticketCacheKey)) {
            return $this->ticketCachePrefix.$this->getAccessToken()->getAppId();
        }

        return $this->ticketCacheKey;
    }

    /**
     * Set current url.
     *
     * @param string $url
     *
     * @return Card
     */
    public function setUrl($url)
    {
        $this->url = $url;

        return $this;
    }
}


<?php

declare (strict_types=1);

namespace Coshi\Variator;

use Coshi\Variator\Variation\AbstractVariation;
use Coshi\Variator\Variation\Type as VariationType;

class VariationFactory
{
    protected $map = [
        'int' => VariationType\IntVariation::class,
        'enum' => VariationType\EnumVariation::class,
        'callback' => VariationType\CallbackVariation::class,
    ];

    /**
     * @var ConfigResolver
     */
    protected $configResolver;

    /**
     * @param string $name
     * @param array  $parameters
     *
     * @return AbstractVariation
     *
     * @throws \InvalidArgumentException
     */
    public function createNew(string $name, array $parameters)
    {
        if (!$this->configResolver instanceof ConfigResolver) {
            $this->configResolver = $this->getResolver();
        }

        if (!isset($this->map[$parameters['type']])) {
            throw new \InvalidArgumentException(sprintf('Variation type %s is not valid', $parameters['type']));
        }
        $class = $this->map[$parameters['type']];
        $class::validateParameters($parameters);

        return new $class($name, $parameters, $this->configResolver);
    }

    /**
     * @param string $type
     * @param $value
     *
     * @throws \InvalidArgumentException
     */
    public function validateValue(string $type, $value)
    {
        if (!isset($this->map[$type])) {
            throw new \InvalidArgumentException(sprintf('Variation type %s is not valid', $type));
        }
        $class = $this->map[$type];

        if (false === $class::validateValue($value)) {
            $stringType = in_array(gettype($value), ['string', 'float'], true) ? $value : gettype($value);

            throw new \InvalidArgumentException(sprintf('"%s" is not a valid value for type "%s"', $stringType, $type));
        }
    }

    /**
     * @param string $type
     * @param string $className
     */
    public function registerType(string $type, string $className)
    {
        $this->map[$type] = $className;
    }

    /**
     * @return ConfigResolver
     */
    protected function getResolver()
    {
        return new ConfigResolver();
    }
}


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

namespace cascade\components\db\fields;

/**
 * Taxonomy [[@doctodo class_description:cascade\components\db\fields\Taxonomy]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class Taxonomy extends Base
{
    /**
     * @inheritdoc
     */
    public $formFieldClass = 'cascade\components\web\form\fields\Taxonomy';
    /**
     * @inheritdoc
     */
    protected $_human = true;
    /**
     * @var [[@doctodo var_type:_moduleHandler]] [[@doctodo var_description:_moduleHandler]]
     */
    protected $_moduleHandler;
    /**
     * @var [[@doctodo var_type:taxonomy]] [[@doctodo var_description:taxonomy]]
     */
    public $taxonomy;

    /**
     * @var [[@doctodo var_type:_moduleHandlers]] [[@doctodo var_description:_moduleHandlers]]
     */
    protected static $_moduleHandlers = [];

    /**
     * Get module handler.
     *
     * @return [[@doctodo return_type:getModuleHandler]] [[@doctodo return_description:getModuleHandler]]
     */
    public function getModuleHandler()
    {
        if (is_null($this->_moduleHandler)) {
            $stem = $this->field;
            if (!isset(self::$_moduleHandlers[$stem])) {
                self::$_moduleHandlers[$stem] = [];
            }
            $n = count(self::$_moduleHandlers[$stem]);
            $this->_moduleHandler = $this->field . ':_' . $n;
            self::$_moduleHandlers[$stem][] = $this->_moduleHandler;
        }

        return $this->_moduleHandler;
    }
    /**
     * @inheritdoc
     */
    public function getFilterSettings()
    {
        return false;
    }
}


<?php
/*
 * This file is part of the infotech/document-generator package.
 *
 * (c) Infotech, Ltd
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Infotech\DocumentGenerator\DataStructure\Definition;

use Infotech\DocumentGenerator\DataStructure\Definition\Exception\DefinitionDuplicateException;
use Infotech\DocumentGenerator\DataStructure\Definition\Exception\InvalidDefinitionException;

class CommonStructureDefinition implements StructureDefinitionInterface
{
    private $placeholders = array();
    private $children = array();

    /**
     * @param array $fields      {@see addPlaceholders()}
     * @param array $structures  {@see addChildren()}
     *
     * @throws DefinitionDuplicateException if fields or structures has names conflicts of definitions
     * @throws InvalidDefinitionException   if any definition of field or structure is malformed
     */
    public function __construct(array $fields, array $structures)
    {
        $this->addPlaceholders($fields);
        $this->addChildren($structures);
    }

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

    /**
     * {@inheritdoc}
     */
    public function hasPlaceholders()
    {
        return (boolean)$this->placeholders;
    }

    /**
     * {@inheritdoc}
     */
    public function getChildren()
    {
        return array_values($this->children);
    }

    /**
     * {@inheritdoc}
     */
    public function hasChildren()
    {
        return (boolean)$this->children;
    }

    /**
     * {@inheritdoc}
     */
    public function getSamples()
    {
        return $this->getMetadataMap('sample');
    }

    /**
     * {@inheritdoc}
     */
    public function getEmptyValues()
    {
        return $this->getMetadataMap('empty');
    }

    /**
     * {@inheritdoc}
     */
    public function getDescriptions()
    {
        return $this->getMetadataMap('description');
    }

    /**
     * Add placeholder definition to structure
     *
     * @param string $placeholder
     * @param string $description
     * @param string $sampleValue
     * @param string $emptyValue
     *
     * @throws DefinitionDuplicateException if new definition conflicts with existing one
     */
    public function addPlaceholder($placeholder, $description, $sampleValue, $emptyValue)
    {
        if (isset($this->placeholders[$placeholder])) {
            throw new DefinitionDuplicateException(
                sprintf('Field with same placeholder "%s" already exists in structure', $placeholder)
            );
        }

        $this->placeholders[$placeholder] = array(
            'placeholder' => $placeholder,
            'description' => $description,
            'sample' => $sampleValue,
            'empty' => $emptyValue,
        );
    }

    /**
     * Add linked structure definition
     *
     * @param string $structureName
     * @param string $prefix
     * @param string $suffix
     *
     * @throws DefinitionDuplicateException if new definition conflicts with existing one
     */
    public function addChild($structureName, $prefix = '', $suffix = '')
    {
        if (isset($this->children[$structureName])) {
            throw new DefinitionDuplicateException(
                sprintf('Child structure with same name "%s" already exists', $structureName)
            );
        }

        $this->children[$structureName] = array(
            'name' => $structureName,
            'prefix' => (string)$prefix,
            'suffix' => (string)$suffix
        );
    }

    private function getArrayValue(array $field, $parameter, $default = null)
    {
        $value = isset($field[$parameter]) ? $field[$parameter] : $default;

        if (null === $value) {
            throw new InvalidDefinitionException(sprintf('Definition parameter "%s" must be set', $parameter));
        }

        return $value;
    }

    /**
     * @param array $fields Fields definitions.
     *
     *     [
     *         [
     *             'placeholder' => string,
     *             'description' => string,
     *             'sample' => string,
     *             'empty' => string opt
     *         ],
     *         ...
     *     ]
     *
     *
     * @throws DefinitionDuplicateException if definition with same placeholder's name already exists
     * @throws InvalidDefinitionException if definition malformed
     */
    public function addPlaceholders(array $fields)
    {
        foreach ($fields as $placeholder => $fieldDef) {
            if (!is_array($fieldDef)) {
                throw new InvalidDefinitionException(
                    sprintf('Invalid definition of field "%s". Definition should be an array', $placeholder)
                );
            }

            try {
                $description = $this->getArrayValue($fieldDef, 'description');
                $sampleValue = $this->getArrayValue($fieldDef, 'sample');
                $emptyValue = $this->getArrayValue($fieldDef, 'empty', '');
                $placeholder = is_string($placeholder) ? $placeholder : $this->getArrayValue($fieldDef, 'placeholder');
            } catch (InvalidDefinitionException $e) {
                throw new InvalidDefinitionException(
                    sprintf('Invalid definition of field "%s". %s', $placeholder, $e->getMessage())
                );
            }

            $this->addPlaceholder($placeholder, $description, $sampleValue, $emptyValue);
        }
    }

    /**
     * @param array $structures Child structures.
     *
     *     [
     *         [
     *             'name' => string,
     *             'prefix' => string opt,
     *             'suffix' => string opt
     *         ],
     *         ...
     *     ]
     *
     *
     * @throws DefinitionDuplicateException if definition with same structure's name already exists
     * @throws InvalidDefinitionException if definition malformed
     */
    public function addChildren(array $structures)
    {
        foreach ($structures as $structureName => $structureDef) {
            if (is_int($structureName) && is_string($structureDef)) {
                $structureName = $structureDef;
                $structureDef = array();
            }

            if (!is_array($structureDef)) {
                throw new InvalidDefinitionException(
                    sprintf('Invalid definition of child structure "%s". Definition should be an array', $structureName)
                );
            }

            try {
                $prefix = $this->getArrayValue($structureDef, 'prefix', '');
                $suffix = $this->getArrayValue($structureDef, 'suffix', '');
                $structureName = is_string($structureName)
                    ? $structureName
                    : $this->getArrayValue($structureDef, 'name');
            } catch (InvalidDefinitionException $e) {
                throw new InvalidDefinitionException(
                    sprintf('Invalid definition of child structure "%s". %s', $structureName, $e->getMessage())
                );
            }

            $this->addChild($structureName, $prefix, $suffix);
        }
    }

    /**
     * @param string $metadata
     *
     * @return array [<placeholder> => <metadata value>]
     */
    private function getMetadataMap($metadata)
    {
        return array_reduce(
            $this->placeholders,
            function (array $acc, $definition) use ($metadata) {
                return array_merge($acc, array($definition['placeholder'] => $definition[$metadata]));
            },
            array()
        );
    }
}


<?php

namespace Nether;
use \Nether;

use \Exception;

Option::Define([
	'cache-autostash'    => true,
	/*//option/
	@type boolean
	define if cache should automatically attempt to stash itself when created.
	//*/

	'cache-stash-name'   => 'cache',
	/*//option/
	@type string
	the key name the cache will auto stash under.
	//*/

	'cache-verbose-get'  => true,
	/*//option/
	@type boolean
	if true successful cache hits will return an object with properites which
	will say which cache the data was fetched from, the key, the full key, and
	the data. if false, only the data is returned as it was.
	//*/

	'cache-key-prefix'   => 'nether-cache',
	/*//option/
	@type string
	define a prefix to add to cache keys so that multiple applications could
	share cache servers if they had to.
	//*/

	'cache-drivers-load' => [
		'App'  => 'Nether\\Cache\\Appcache',
		'Mem'  => 'Nether\\Cache\\Memcache',
		'Disk' => 'Nether\\Cache\\Diskcache'
	],
	/*//option/
	@type array
	define a list of cache drivers to automatically load. specfied as an array
	with the key being the alias you use to reference the cache, and the value
	being the class which extends Nether\Cache\DriverInterface.
	//*/

	'cache-drivers-use'  => ['App','Mem']
	/*//option/
	@type array
	a list of cache drivers to use automatically when performing operations when
	specific drivers are not listed. this will allow you to cache most things
	like user objects in all the quick volitile caches automatically. when you
	want to cache something special to disk only (like a huge cron'd query) you
	can specify the disk driver in the use parametre of the methods on this
	class.
	//*/

]);

class Cache {

	protected $Drivers = [];
	/*//
	@type array
	list of currently active driver objects.
	//*/

	protected $HitCount = 0;
	/*//
	@type int
	number of cache requests that ended in hits.
	//*/

	protected $MissCount = 0;
	/*//
	@type int
	number of cache requests that ended in misses.
	//*/

	////////////////
	////////////////

	protected $Logging = false;
	/*//
	@type bool
	if we should log the cache commands or not.
	//*/

	protected $LoggingData = [];
	/*//
	@type array
	a list of all the cache commands.
	//*/

	protected function Log($cmd,$key,$res=null) {
		$line = "{$cmd}({$res}): {$key}";
		$this->LoggingData[] = $line;
		return;
	}

	public function EnableLogging($state) {
		$this->Logging = $state;
		return $this;
	}

	public function GetLoggingData() {
		return $this->LoggingData;
	}

	////////////////
	////////////////

	public function __construct() {

		if(Option::Get('cache-autostash'))
		Stash::Set(Option::Get('cache-stash-name'),$this);

		$this->LoadDrivers();
		return;
	}

	////////////////
	////////////////

	public function GetDriver($key) {
	/*//
	@argv string Key
	fetch a driver. mainly so we can query memcache about shit.
	//*/
		if(array_key_exists($key,$this->Drivers)) return $this->Drivers[$key];
		else return false;
	}

	protected function LoadDrivers() {
	/*//
	spool up the specified drivers.
	//*/

		$drivers = Option::Get('cache-drivers-load');

		/*//todo/
		log instead of throwing exception
		//*/

		if(!is_array($drivers))
		throw new Exception('cache-drivers-load not an array');

		foreach($drivers as $key => $class) {
			if(!class_exists($class))
			throw new Exception("unable to load cache driver {$class}");

			$this->Drivers[$key] = new $class;
		}

		return;
	}

	protected function GetFullKey($key) {
	/*//
	@argv string Key
	prepend the defined cache-key-prefix to the requested key so that the data
	stores can prevent collisions if a single memcache is running multiple
	applications, or something like that.
	//*/
		return sprintf(
			'%s-%s',
			Nether\Option::Get('cache-key-prefix'),
			$key
		);
	}

	////////////////
	////////////////

	public function Drop($key,$use=null) {
	/*//
	@argv string Key
	@argv string Key, array Drivers
	drop a specific key from the cache.
	//*/

		if(!$use)
		$use = Option::Get('cache-drivers-use');

		foreach($this->Drivers as $dkey => $driver) {
			if(!in_array($dkey,$use)) continue;

			$driver->Drop($this->GetFullKey($key));
		}

		return;
	}

	public function Flush($use=null) {
	/*//
	@argv array Drivers
	drop all things from the cache.
	//*/

		if(!$use)
		$use = Option::Get('cache-drivers-use');

		foreach($this->Drivers as $dkey => $driver) {
			if(!in_array($dkey,$use)) continue;

			$driver->Flush();
		}

		return;
	}

	public function Get($key,$use=null) {
	/*//
	@argv string Key
	@argv string Key, array Drivers
	get the value stored under the specified key from a cache.
	//*/

		if(!$use)
		$use = Option::Get('cache-drivers-use');

		$missed = [];
		foreach($this->Drivers as $dkey => $driver) {
			if(!in_array($dkey,$use)) continue;

			$value = $driver->Get($this->GetFullKey($key));

			if($value !== null) {
				if($dkey != 'App') {
					$this->Log('get',$key,$dkey);
					$this->HitCount++;
				}

				// back fill any closer caches if we found something.
				$this->Set($key,$value,$missed);

				if(Option::Get('cache-verbose-get')) {
					return (object)[
						'Cache'   => $dkey,
						'Key'     => $key,
						'FullKey' => $this->GetFullKey($key),
						'Value'   => $value
					];
				} else {
					return $value;
				}
			}

			$missed[] = $dkey;
		}

		$this->MissCount++;
		$this->Log('get',$key,'false');
		return null;
	}

	public function Set($key,$value,$use=null) {
	/*//
	@argv string Key, mixed Value
	@argv string Key, mixed Value, array Drivers
	store a specified value under the key name in the cache.
	//*/

		if(!is_array($use)) $use = Option::Get('cache-drivers-use');

		foreach($this->Drivers as $dkey => $driver) {
			if(!in_array($dkey,$use)) continue;

			$driver->Set($this->GetFullKey($key),$value);
			$this->Log('set',$key,$dkey);
		}

		return;
	}

	////////////////
	////////////////

	public function GetStats($use=null) {
	/*//
	@return array
	returns an object with the hit/miss statistics of the cache.
	//*/

		if(!$use)
		$use = Option::Get('cache-drivers-use');

		$hit = 0;
		$miss = 0;

		foreach($use as $dkey) {
			if(!array_key_exists($dkey,$this->Drivers)) continue;

			$hit += $this->Drivers[$dkey]->GetHitCount();
			$miss += $this->Drivers[$dkey]->GetMissCount();
		}

		return (object)[
			'HitCount'   => $this->HitCount,
			'MissCount'  => $this->MissCount,
			'QueryCount' => ($this->HitCount+$this->MissCount),
			'ConnectTime' => 0,
			'QueryTime' => 0
		];
	}

}


<?php
namespace app\manage\controller;

use cms\Common;
use think\Request;
use core\manage\logic\FileLogic;

class File extends Base
{

    /**
     * 文件列表
     *
     * @param Request $request
     * @return string
     */
    public function index(Request $request)
    {
        $this->site_title = '附件列表';
        $file_logic = FileLogic::instance();

        $map = [];

        // 类型
        $type = $request->param('type', '');
        if (! empty($type)) {
            $map['file_type'] = $type;
        }
        $this->assign('type', $type);

        // 开始时间
        $start_time = $request->param('start_time', '');
        $this->assign('start_time', $start_time);

        // 结束时间
        $end_time = $request->param('end_time', '');
        $this->assign('end_time', $end_time);

        // 时间
        if (! empty($start_time) && ! empty($end_time)) {
            $map['create_time'] = [
                'between',
                [
                    strtotime($start_time),
                    strtotime($end_time)
                ]
            ];
        } elseif (! empty($start_time)) {
            $map['create_time'] = [
                'egt',
                strtotime($start_time)
            ];
        } elseif (! empty($end_time)) {
            $map['create_time'] = [
                'elt',
                strtotime($end_time)
            ];
        }

        // 关键词
        $keyword = $request->param('keyword', '');
        if (! empty($keyword)) {
            $map['file_hash'] = [
                'like',
                '%' . $keyword . '%'
            ];
        }
        $this->assign('keyword', $keyword);

        // 总数
        $total_count = $file_logic->model->where($map)->count();
        $this->assign('total_count', $total_count);

        // 列表
        $list = $file_logic->model->where($map)
            ->order('id desc')
            ->paginate($this->rows_num);

        // 文件大小格式化
        $res = array();
        foreach ($list as $vo) {
            $vo['file_size'] = Common::formatBytes($vo['file_size']);
            $res[] = $vo;
        }
        $this->assign('list', $res);
        $this->assign('page', $list->render());

        // 上传类型
        $upload_type_list = $file_logic->getUploadTypeSelect();
        $this->assign('upload_type_list', $upload_type_list);

        return $this->fetch();
    }

    /**
     * 删除文件
     *
     * @param Request $request
     * @return mixed
     */
    public function delFile(Request $request)
    {
        $file_id = $request->param('file_id');
        if (empty($file_id)) {
            return $this->error('文件ID为空');
        }

        $res = FileLogic::instance()->delFile($file_id);
        if ($res['code'] == 1) {
            return $this->success('删除文件成功', 'history.go(0)');
        } else {
            return $this->error($res['msg']);
        }
    }

    /**
     * 上传文件
     *
     * @return string
     */
    public function upload()
    {
        $this->site_title = '文件上传';

        return $this->fetch();
    }
}


<?php
namespace eMacros\Runtime\Environment;

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

class EnvironmentUse implements Applicable {
	/**
	 * Imports a function into current environment
	 * Usage: (use utf8_decode) (use utf8_encode utf8enc)
	 * (non-PHPdoc)
	 * @see \eMacros\Applicable::apply()
	 */
	public function apply(Scope $scope, GenericList $arguments) {
		foreach ($arguments as $name) {
			if ($name instanceof Symbol)
				$func = $alias = $name->symbol;
			elseif ($name instanceof GenericList) {
				//obtain symbol pair
				list($func, $alias) = $name;
				if (!($func instanceof Symbol))
					throw new \InvalidArgumentException(sprintf("Use: Expected symbol as first argument, %s found instead.", substr(strtolower(strstr(get_class($func), '\\')), 1)));
				if (!($alias instanceof Symbol))
					throw new \InvalidArgumentException(sprintf("Use: Expected symbol as second argument, %s found instead.", substr(strtolower(strstr(get_class($alias), '\\')), 1)));
				$func = $func->symbol;
				$alias = $alias->symbol;
			}
			else throw new \InvalidArgumentException(sprintf("Use: Unexpected %s %s as argument.", substr(strtolower(strstr(get_class($name), '\\')), 1), $name->__toString()));
			if (!function_exists($func)) throw new \UnexpectedValueException("Use: Function $func not found.");
			$scope->symbols[$alias] = new PHPFunction($func);
		}
	}
}
?>


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

namespace cascade\components\db\behaviors;

use Yii;

/**
 * Familiarity [[@doctodo class_description:cascade\components\db\behaviors\Familiarity]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class Familiarity extends \canis\db\behaviors\ActiveRecord
{
    /**
     * @var [[@doctodo var_type:objectField]] [[@doctodo var_description:objectField]]
     */
    public $objectField = 'object_id';
    /**
     * @var [[@doctodo var_type:userField]] [[@doctodo var_description:userField]]
     */
    public $userField = 'user_id';
    /**
     * @var [[@doctodo var_type:_familiarity]] [[@doctodo var_description:_familiarity]]
     */
    protected $_familiarity = [];

    /**
     * @inheritdoc
     */
    public function events()
    {
        return [
            \canis\db\ActiveRecord::EVENT_AFTER_INSERT => 'afterInsert',
            \canis\db\ActiveRecord::EVENT_AFTER_UPDATE => 'afterUpdate',
        ];
    }

    /**
     * [[@doctodo method_description:afterUpdate]].
     */
    public function afterUpdate()
    {
        if ($this->user) {
            $familiarityClass = Yii::$app->classes['ObjectFamiliarity'];
            $familiarityClass::modified($this->owner, $this->getUser(false));
        }
    }

    /**
     * [[@doctodo method_description:afterInsert]].
     */
    public function afterInsert()
    {
        if ($this->user) {
            $familiarityClass = Yii::$app->classes['ObjectFamiliarity'];
            $familiarityClass::created($this->owner, $this->user);
        }
    }

    /**
     * Get user.
     *
     * @param boolean $owner [[@doctodo param_description:owner]] [optional]
     *
     * @return [[@doctodo return_type:getUser]] [[@doctodo return_description:getUser]]
     */
    public function getUser($owner = true)
    {
        if ($owner && $this->owner->getBehavior('Ownable') !== null && isset($this->owner->objectOwner)) {
            return $this->owner->objectOwner;
        } elseif (isset(Yii::$app->user) && isset(Yii::$app->user->identity->primaryKey)) {
            return Yii::$app->user->identity;
        }

        return false;
    }

    /**
     * [[@doctodo method_description:watch]].
     *
     * @param boolean                      $doWatch [[@doctodo param_description:doWatch]] [optional]
     * @param [[@doctodo param_type:user]] $user    [[@doctodo param_description:user]] [optional]
     *
     * @return [[@doctodo return_type:watch]] [[@doctodo return_description:watch]]
     */
    public function watch($doWatch = true, $user = null)
    {
        $familiarity = $this->getFamiliarity($user);
        if (!$familiarity) {
            return false;
        }
        if ($doWatch) {
            $familiarity->watching = 1;
        } else {
            $familiarity->watching = 0;
        }

        return $familiarity->save();
    }

    /**
     * Get familiarity.
     *
     * @param [[@doctodo param_type:user]] $user [[@doctodo param_description:user]] [optional]
     *
     * @return [[@doctodo return_type:getFamiliarity]] [[@doctodo return_description:getFamiliarity]]
     */
    public function getFamiliarity($user = null)
    {
        if (is_null($user)) {
            $user = $this->getUser(false);
        }
        if (is_object($user)) {
            $user = $user->primaryKey;
        }
        $familarityKey = md5($user);
        if (!isset($this->_familiarity[$familarityKey])) {
            $this->_familiarity[$familarityKey] = false;
            $familiarityClass = Yii::$app->classes['ObjectFamiliarity'];
            if (!empty($user)) {
                $attributes = [];
                $attributes[$this->objectField] = $this->owner->primaryKey;
                $attributes[$this->userField] = $user;
                $this->_familiarity[$familarityKey] = $familiarityClass::find()->where($attributes)->one();
                if (empty($this->_familiarity[$familarityKey])) {
                    $this->_familiarity[$familarityKey] = new $familiarityClass();
                    $this->_familiarity[$familarityKey]->attributes = $attributes;
                }
            }
        }

        return $this->_familiarity[$familarityKey];
    }
}


<?php

declare(strict_types=1);

namespace Ruwork\Reform\Mapper;

use Symfony\Component\Form\DataMapperInterface;
use Symfony\Component\Form\Extension\Core\DataMapper\PropertyPathMapper;

abstract class AbstractSwitchMapper implements DataMapperInterface
{
    private $switchName;
    private $mapper;

    public function __construct(string $switchName, DataMapperInterface $mapper = null)
    {
        $this->switchName = $switchName;
        $this->mapper = $mapper ?? new PropertyPathMapper();
    }

    /**
     * {@inheritdoc}
     */
    public function mapDataToForms($data, $forms)
    {
        $this->mapper->mapDataToForms($data, $forms);

        foreach ($forms as $name => $form) {
            if ($name === $this->switchName) {
                $form->setData($this->getSwitchValueForData($data, $form->getData()));
                break;
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function mapFormsToData($forms, &$data)
    {
        foreach ($forms as $name => $form) {
            if ($name === $this->switchName) {
                $data = $this->getDataForSwitchValue($form->getData(), $data);
                break;
            }
        }

        $this->mapper->mapFormsToData($forms, $data);
    }

    abstract protected function getSwitchValueForData($data, $switchValue);

    abstract protected function getDataForSwitchValue($switchValue, $data);
}


<?php

namespace OpenOrchestra\ModelBundle\DataFixtures\MongoDB\DemoContent;

use OpenOrchestra\ModelBundle\Document\Block;
use OpenOrchestra\ModelBundle\Document\Node;
use OpenOrchestra\DisplayBundle\DisplayBlock\Strategies\TinyMCEWysiwygStrategy;
use OpenOrchestra\ModelInterface\Model\NodeInterface;
use OpenOrchestra\ModelBundle\Document\Area;

/**
 * Class AutoPublishDataGenerator
 */
class AutoPublishDataGenerator extends AbstractDataGenerator
{
    /**
     * @return Node
     */
    protected function generateNodeFr()
    {
        $htmlContent = <<<EOF

Entreprise

Open Orchestra est une marque déposée de Business & Decision

Dénomination sociale : Business & Decision S.A. (tél : 01 56 21 21 21)

Société anonyme au capital de 551 808,25 €

Enregistré au RCS Paris : 384 518 114 B

Siége social: 153 rue de Courcelles, 75817 Paris cedex 17

Directeur de publication: Patrick Bensabat, PDG

EOF;
        $name = "Dépublication auto";
        $language = "fr";
        $routePattern = "depublication-auto";

        $node = $this->generateNodeGlobal($htmlContent, $name, $language, $routePattern);
        $node->setUnpublishDate(\DateTime::createFromFormat('j-M-Y', '28-Feb-2016'));

        return $node;
    }

    /**
     * @return Node
     */
    protected function generateNodeEn()
    {
        $htmlContent = <<<EOF

Éditeur

Open Orchestra is a registered trademark of Business & Decision

Company name: Business & Decision S.A. (Tel.: 01 56 21 21 21)

Public limited company with a capital of EUR 551,808.25

Registered at RCS Paris under number: 384 518 114 B

Headquarters: 153 rue de Courcelles, 75817 Paris cedex 17

Publication Director: Patrick Bensabat, CEO

EOF;
        $name = "Auto publish";
        $language = "en";
        $routePattern = "auto-publish";

        $node = $this->generateNodeGlobal($htmlContent, $name, $language, $routePattern);
        $node->setPublishDate(\DateTime::createFromFormat('j-M-Y', '01-Jan-2016'));
        $node->setStatus($this->fixture->getReference('status-pending'));

        return $node;
    }

    /**
     * Useless method here
     */
    protected function generateNodeDe()
    {
        $htmlContent = <<<EOF

Herausgeber

Open Orchestra ist ein eingetragenes Warenzeichen von Business & Decision

Firmenname: Unternehmen & Entscheidung S.A. (Tel .: 01 56 21 21 21)

Aktiengesellschaft mit einem Kapital von EUR 551.808,25

Eingetragen bei RCS Paris unter der Nummer: 384 518 114 B

Hauptsitz: 153 rue de Courcelles, 75817 Paris cedex 17

Herausgeber: Patrick Bensabat, CEO

EOF;
        $name = "Automatisch veröffentlichen";
        $language = "de";
        $routePattern = "auto-publish";

        $node = $this->generateNodeGlobal($htmlContent, $name, $language, $routePattern);
        $node->setPublishDate(\DateTime::createFromFormat('j-M-Y', '01-Jan-2016'));
        $node->setStatus($this->fixture->getReference('status-pending'));

        return $node;
    }

    /**
     * @param string $htmlContent
     * @param string $name
     * @param string $language
     * @param string $routePattern
     *
     * @return Node
     */
    protected function generateNodeGlobal($htmlContent, $name, $language, $routePattern)
    {
        $nodeAutoPublishBlock = new Block();
        $nodeAutoPublishBlock->setLabel('Wysiwyg');
        $nodeAutoPublishBlock->setLanguage($language);
        $nodeAutoPublishBlock->setComponent(TinyMCEWysiwygStrategy::NAME);
        $nodeAutoPublishBlock->setAttributes(array(
            "htmlContent" => $htmlContent
        ));

        $nodeAutoPublishBlock = $this->generateBlock($nodeAutoPublishBlock);

        $main = new Area();
        $main->addBlock($nodeAutoPublishBlock);

        $nodeAutoPublish = $this->createBaseNode();
        $nodeAutoPublish->setArea('main', $main);

        $nodeAutoPublish->setNodeId('fixture_auto_unpublish');
        $nodeAutoPublish->setName($name);
        $nodeAutoPublish->setVersionName($this->getVersionName($nodeAutoPublish));
        $nodeAutoPublish->setLanguage($language);
        $nodeAutoPublish->setParentId(NodeInterface::ROOT_NODE_ID);
        $nodeAutoPublish->setOrder(15);
        $nodeAutoPublish->setRoutePattern($routePattern);
        $nodeAutoPublish->setInFooter(false);
        $nodeAutoPublish->setInMenu(false);

        return $nodeAutoPublish;
    }
}


<?php

/*
 * This file is part of Laravel Database.
 *
 * (c) Graham Campbell <graham@mineuk.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace GrahamCampbell\Database\Providers\Common;

use Illuminate\Pagination\Paginator;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * This is the paginate provider trait.
 *
 * @author Graham Campbell <graham@mineuk.com>
 */
trait PaginateProviderTrait
{
    /**
     * The paginated links generated by the paginate method.
     *
     * @var string
     */
    protected $paginateLinks;

    /**
     * Get a paginated list of the models.
     *
     * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
     *
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function paginate()
    {
        $model = $this->model;

        if (property_exists($model, 'order')) {
            $paginator = $model::orderBy($model::$order, $model::$sort)->paginate($model::$paginate, $model::$index);
        } else {
            $paginator = $model::paginate($model::$paginate, $model::$index);
        }

        if (!$this->isPageInRange($paginator) && !$this->isFirstPage($paginator)) {
            throw new NotFoundHttpException();
        }

        if ($paginator->getTotal()) {
            $this->paginateLinks = $paginator->links();
        }

        return $paginator;
    }

    /**
     * Is this current page in range?
     *
     * @param \Illuminate\Pagination\Paginator $paginator
     *
     * @return bool
     */
    protected function isPageInRange(Paginator $paginator)
    {
        return ($paginator->getFactory()->getCurrentPage() <= $paginator->getLastPage());
    }

    /**
     * Is the current page the first page?
     *
     * @param \Illuminate\Pagination\Paginator $paginator
     *
     * @return bool
     */
    protected function isFirstPage(Paginator $paginator)
    {
        return ($paginator->getFactory()->getCurrentPage() === 1);
    }

    /**
     * Get the paginated links.
     *
     * @return string
     */
    public function links()
    {
        return $this->paginateLinks;
    }
}


<?php

namespace kehikko\Composer;

use Composer\Installer\LibraryInstaller;
use Composer\Package\PackageInterface;

class RouteInstaller extends LibraryInstaller
{
	/**
	 * {@inheritDoc}
	 */
	public function getInstallPath(PackageInterface $package)
	{
		$prefix = substr($package->getPrettyName(), 0, 14);
		if ('kehikko/route-' !== $prefix)
		{
			throw new \InvalidArgumentException(
				'Unable to install template, kehikko routes should always start their package name with '
				. '"kehikko/route/"'
			);
		}

		return 'routes/' . substr($package->getPrettyName(), 14);
	}

	/**
	 * {@inheritDoc}
	 */
	public function supports($packageType)
	{
		return 'kehikko-route' === $packageType;
	}
}


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

use Xloit\Std\ArrayUtils;
use Zend\Form\Element;
use Zend\Validator\NotEmpty;

/**
 * An {@link ElementRequireAttributesProviderTrait} trait.
 *
 * @package Xloit\Bridge\Zend\Form
 *
 * @method Element get($elementOrFieldset)
 */
trait ElementRequireAttributesProviderTrait
{
    /**
     * Add attributes to required fields.
     *
     * @param array $specifications
     *
     * @return $this
     * @throws \Xloit\Std\Exception\RuntimeException
     */
    final protected function addRequiredAttributeToFields(array $specifications)
    {
        /** @var array $data */
        foreach ($specifications as $field => $data) {
            if (!$this->has($field)) {
                continue;
            }

            $validators = ArrayUtils::get($data, 'validators', []);
            $isRequired = (bool) ArrayUtils::get(
                $data,
                'required',
                ArrayUtils::get($validators, NotEmpty::class, ArrayUtils::get($validators, 'NotEmpty'))
            );

            if ($isRequired) {
                $this->get($field)->setAttribute('required', 'required');
            }
        }

        return $this;
    }
}


<?php

namespace SwooleFlierMouseBase\http;

use SwooleFlierMouseBase\Conf;
use SwooleFlierMouseBase\RequestException;

abstract class Request
{
	protected $method;
	protected $request_uri;
	protected $http_protocol;
	protected $raw_context;
	protected $header;
	protected $body;
	protected $get;
	protected $files;
	protected $cookie;

	protected $data;
	protected $session_id;

	public function checkPack ($recv_buffer)
	{
		if (!strpos($recv_buffer, "\r\n\r\n")) {
			throw new RequestException('recv_buffer error');
		}

		return $this;
	}

	public function unpack ($recv_buffer)
	{
		$this->checkPack($recv_buffer);

		$this->data = explode("\r\n\r\n", $recv_buffer);
		$header     = explode("\r\n", $this->data[0]);
		unset($this->data[0]);

		$this->raw_context = join("\r\n\r\n", $this->data);
		foreach ($header as $key => $val) {
			if ($key === 0) {
				@list($this->method, $this->request_uri, $this->http_protocol) = explode(" ", $val, 3);
			}
			else {
				$header_row = explode(":", $val);
				if (isset($header_row[1])) $this->header[ strtolower($header_row[0]) ] = trim($header_row[1], ' ');
			}
		}

		if (@$this->header['content-type']) {
			$content_type                 = explode(';', $this->header['content-type']);
			$this->header['content-type'] = $content_type[0];
			if (isset($content_type[1])) $content_type_params = @explode('=', $content_type[1]);
			if (isset($content_type_params[1])) $this->header['content-type-params'][ trim($content_type_params[0]) ] = $content_type_params[1];
		}

		if (!$this->method || !$this->http_protocol) {
			throw new RequestException('http request error!');
		}

		return $this;
	}

	/**
	 *  格式化payload
	 */
	public function content ()
	{
		$contentType = @$this->header['content-type'];

		$this->deCookie();
		$this->deUrls();

		switch (strtolower($contentType)) {
			case "application/x-www-form-urlencoded":
				parse_str($this->raw_context, $output);
				$this->body = $output ?: [];
				break;
			case "multipart/form-data":
				$this->multipartFromData();
				break;
			default:

				break;
		}

		return $this;
	}

	/**
	 * 解析cookie
	 *
	 * @return bool
	 */
	public function deCookie ()
	{
		if (isset($this->header['cookie'])) {
			$cookies = explode(';', $this->header['cookie']);
			foreach ($cookies as $val) {
				$_tmp                           = explode('=', $val);
				$this->cookie[ trim($_tmp[0]) ] = $_tmp[1];
			}
		}

		if (isset($this->cookie['SFMBSESSION'])) {
			$this->session_id = $this->cookie['SFMBSESSION'];
		}
		else {
			$this->session_id = md5(uniqid());
		}
	}

	/**
	 * 解析url 参数
	 */
	public function deUrls ()
	{
		$url_params = @explode('?', $this->request_uri)[1];
		if (strstr($url_params, '#')) {
			$url_params = explode('#', $url_params)[0];
		}
		parse_str($url_params, $this->get);
	}

	/**
	 * 文件上传 或者 form-data
	 */
	private function multipartFromData ()
	{
		$body = explode('--' . $this->header['content-type-params']['boundary'], $this->raw_context);
		unset($body[0], $body[ count($body) ]);

		foreach ($body as $value) {
			$_     = explode("\r\n\r\n", $value);
			$_info = explode("\r\n", $_[0]);

			$_tmp = [];

			$_tmp_arr = explode(';', $_info[1]);

			foreach ($_tmp_arr as $k => $v) {
				if (0 === $k) {
					$__tmp                   = explode(':', $v);
					$_tmp[ trim($__tmp[0]) ] = trim($__tmp[1]);
				}
				else {
					$__tmp                   = explode('=', $v);
					$_tmp[ trim($__tmp[0]) ] = trim($__tmp[1], '"');
				}
			}
			if (isset($_tmp['filename'])) {
				$file_path     = Conf::createTempFile($this->session_id, 'haoge.tmpfile.' . uniqid(), $_[ count($_) - 1 ]);
				$this->files[] = [
					'size'  => filesize($file_path),
					'name'  => $_tmp['filename'],
					'tmp'   => $file_path,
					//					'tmp_name' => $file_path,
					'error' => !(bool)$file_path,
					'type'  => trim(explode(':', $_info[2])[1])
				];
			}
			else {
				$this->body[ $_tmp['name'] ] = trim($_[ count($_) - 1 ]);
			}

		}
	}

	public function destroy ()
	{
		$this->method        = NULL;
		$this->request_uri   = NULL;
		$this->http_protocol = NULL;
		$this->raw_context   = NULL;
		$this->header        = NULL;
		$this->body          = NULL;
		$this->get           = NULL;
		$this->files         = NULL;
		$this->cookie        = NULL;
		$this->data          = NULL;
		$this->session_id    = NULL;
		$_GET                = NULL;
		$_POST               = NULL;
		$_FILES              = NULL;
		$_COOKIE             = NULL;
		$_REQUEST            = NULL;
		$_SERVER             = NULL;
	}

}


<?php namespace FHIR\Common;

use FHIR\Common\Exception\InvalidCollectionValueException;
use FHIR\Common\Exception\InvalidPropertyNameException;
use FHIR\Common\Exception\InvalidPropertyValueTypeException;

/**
 * Class AbstractFHIRObject
 * @package FHIR
 */
abstract class AbstractFHIRObject implements FHIRObjectInterface
{
    /**
     * @param string $param
     * @return InvalidPropertyNameException
     */
    protected function createInvalidPropertyNameException($param)
    {
        return new InvalidPropertyNameException(
            sprintf('Property "%s" does not exist on %s',
                $param,
                get_class($this)
            )
        );
    }

    /**
     * @param string $property
     * @param string $expected
     * @param mixed $actual
     * @return InvalidPropertyValueTypeException
     */
    protected function createInvalidPropertyValueTypeException($property, $expected, $actual)
    {
        return new InvalidPropertyValueTypeException(
            sprintf('Property %s::%s expected to be of type %s, %s seen.',
                get_class($this),
                $property,
                $expected,
                is_object($actual) ? get_class($actual) : gettype($actual)
            )
        );
    }

    /**
     * @param string $collection
     * @param string $expected
     * @param mixed $actual
     * @return InvalidCollectionValueException
     */
    protected function createInvalidCollectionValueException($collection, $expected, $actual)
    {
        return new InvalidCollectionValueException(
            sprintf('Collection %s::%s accepts values of type %s, %s seen.',
                get_class($this),
                $collection,
                $expected,
                is_object($actual) ? get_class($actual) : gettype($actual)
            )
        );
    }

    /**
     * @return array
     */
    public function jsonSerialize()
    {
        // TODO: Implement this...
    }

    /**
     * (PHP 5 >= 5.1.0)
     * String representation of object
     * @link http://php.net/manual/en/serializable.serialize.php
     * @return string the string representation of the object or null
     */
    public function serialize()
    {
        return serialize(get_object_vars($this));
    }

    /**
     * (PHP 5 >= 5.1.0)
     * Constructs the object
     * @link http://php.net/manual/en/serializable.unserialize.php
     * @param string $serialized The string representation of the object.
     * @return void
     */
    public function unserialize($serialized)
    {
        foreach(unserialize($serialized) as $k=>$v)
        {
            $this->$k = $v;
        }
    }

    /**
     * @return null|string
     */
    public function __toString()
    {
        return get_class($this);
    }
}


<?php

namespace Bridge\HttpApi\Worker;

use Bridge\Action\AbstractAction;
use Bridge\Registry;
use ProxyManager\Factory\LazyLoadingValueHolderFactory;
use ProxyManager\Proxy\LazyLoadingInterface;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Transfer\Worker\WorkerInterface;

class VirtualizationWorker implements WorkerInterface
{
    /**
     * @var array
     */
    private $arguments;

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

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

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

    /**
     * @param Registry $registry
     * @param $virtualProperties
     * @param array $deserialization
     * @param array $arguments
     */
    public function __construct($registry, $virtualProperties, $deserialization, $arguments)
    {
        $this->arguments = $arguments;
        $this->registry = $registry;
        $this->virtualProperties = $virtualProperties;
        $this->deserialization = $deserialization;
    }
    /**
     * {@inheritdoc}
     */
    public function handle($object)
    {
        $factory = new LazyLoadingValueHolderFactory();

        $initializer = function (&$wrappedObject, LazyLoadingInterface $proxy, $method, array $parameters, &$initializer) use ($object) {
            static $tracker = array();

            $wrappedObject = $object;

            if ($this->registry === null) {
                return true;
            }

            if (!in_array($method, $tracker)) {
                foreach ($this->virtualProperties as $name => $parameters) {
                    if (preg_match(sprintf('/^.*(%s|%s)$/', $name, ucfirst($name)), $method)) {
                        $action = $this->registry->get($parameters['action']);

                        if (!$action instanceof AbstractAction) {
                            throw new \LogicException(sprintf(
                                'Component "%s" must resolve to an action, "%s" given.',
                                $parameters['action'], get_class($action)
                            ));
                        }

                        $language = new ExpressionLanguage();

                        $parameters['arguments'] = array_map(
                            function ($argument) use ($object, $language) {
                                return $language->evaluate(
                                    $argument,
                                    array(
                                        'object' => $object,
                                        'parent_arguments' => $this->arguments,
                                    )
                                );
                            },
                            $parameters['arguments']
                        );

                        $result = $action->getGroup()->call($action->getName(), $parameters['arguments']);

                        $property = new \ReflectionProperty(get_class($object), $name);
                        $property->setAccessible(true);
                        $property->setValue($object, $result);

                        $tracker[] = $method;

                        break;
                    }
                }
            }

            return true;
        };

        return $factory->createProxy($this->deserialization['single_type'], $initializer);
    }
}


<?php

namespace Chill\CustomFieldsBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Chill\CustomFieldsBundle\Entity\CustomField;

/**
 * CustomField controller.
 *
 */
class CustomFieldController extends Controller
{

    /**
     * Creates a new CustomField entity.
     *
     */
    public function createAction(Request $request)
    {
        $entity = new CustomField();
        $form = $this->createCreateForm($entity, $request->query->get('type', null));
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            $this->addFlash('success', $this->get('translator')
                  ->trans('The custom field has been created'));

            return $this->redirect($this->generateUrl('customfieldsgroup_show',
                  array('id' => $entity->getCustomFieldsGroup()->getId())));
        }

        $this->addFlash('error', $this->get('translator')
              ->trans("The custom field form contains errors"));

        return $this->render('ChillCustomFieldsBundle:CustomField:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Creates a form to create a CustomField entity.
     *
     * @param CustomField $entity The entity
     * @param string
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(CustomField $entity, $type)
    {
        $form = $this->createForm('custom_field_choice', $entity, array(
            'action' => $this->generateUrl('customfield_create',
                  array('type' => $type)),
            'method' => 'POST',
            'type' => $type,
            'group_widget' => ($entity->getCustomFieldsGroup()) ? 'hidden' :'entity'
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new CustomField entity.
     *
     */
    public function newAction(Request $request)
    {
        $entity = new CustomField();

        //add the custom field group if defined in URL
        $cfGroupId = $request->query->get('customFieldsGroup', null);

        if ($cfGroupId !== null) {
            $cfGroup = $this->getDoctrine()->getManager()
                  ->getRepository('ChillCustomFieldsBundle:CustomFieldsGroup')
                  ->find($cfGroupId);
            if (!$cfGroup) {
                throw $this->createNotFoundException('CustomFieldsGroup with id '
                      . $cfGroupId.' is not found !');
            }
            $entity->setCustomFieldsGroup($cfGroup);
        }

        $form   = $this->createCreateForm($entity, $request->query->get('type'));

        return $this->render('ChillCustomFieldsBundle:CustomField:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Finds and displays a CustomField entity.
     *
     * @deprecated is not used since there is no link to show action
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ChillCustomFieldsBundle:CustomField')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find CustomField entity.');
        }

        return $this->render('ChillCustomFieldsBundle:CustomField:show.html.twig', array(
            'entity'      => $entity,        ));
    }

    /**
     * Displays a form to edit an existing CustomField entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ChillCustomFieldsBundle:CustomField')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find CustomField entity.');
        }

        $editForm = $this->createEditForm($entity, $entity->getType());

        return $this->render('ChillCustomFieldsBundle:CustomField:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
        ));
    }

    /**
    * Creates a form to edit a CustomField entity.
    *
    * @param CustomField $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(CustomField $entity, $type)
    {
        $form = $this->createForm('custom_field_choice', $entity, array(
            'action' => $this->generateUrl('customfield_update', array('id' => $entity->getId())),
            'method' => 'PUT',
            'type' => $type,
            'group_widget' => 'hidden'
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing CustomField entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ChillCustomFieldsBundle:CustomField')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find CustomField entity.');
        }

        $editForm = $this->createEditForm($entity, $entity->getType());
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            $this->addFlash('success', $this->get('translator')
                  ->trans("The custom field has been updated"));

            return $this->redirect($this->generateUrl('customfield_edit', array('id' => $id)));
        }

        $this->addFlash('error', $this->get('translator')
              ->trans("The custom field form contains errors"));

        return $this->render('ChillCustomFieldsBundle:CustomField:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
        ));
    }
}


<?php

/*
 * This file is part of the P13/DateTime package.
 *
 * (c) Wagner Sicca <wssicca@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace p13\datetime;

use \DatePeriod;

/**
 * Classe que representa um mês segundo a definição ISO-8601. Nela,
 * as semanas começam nas segundas (dia 1) e terminam no domingo (dia 7).
 *
 *
 * @author Wagner Sicca <wssicca@gmail.com>
 * @namespace p13\datetime
 * @package p13\datetime
 */
class Month extends DateRange
{

    /**
     * Indica o mês corrente
     * @const CURRENT_MONTH
     */
    const CURRENT_MONTH = 'CURRENT_MONTH';

    /**
     * Indica o ano corrente
     * @const CURRENT_YEAR
     */
    const CURRENT_YEAR = 'CURRENT_YEAR';

    /**
     * Número do mês
     * @var int
     */
    public $month;

    /**
     * Número do ano
     * @var int
     */
    public $year;

    /**
     *
     * @param int $month ISO-8601 week number of year, weeks starting on Monday
     * @param int $year
     */
    public function __construct($month = self::CURRENT_MONTH, $year = self::CURRENT_YEAR)
    {
        $this->month = $month == self::CURRENT_MONTH ? date('m') : $month;
        $this->year = $year == self::CURRENT_YEAR ? date('Y') : $year;

        $startDate = new Date();
        $startDate->setDate($this->year, $this->month, 1);

        $endDate = clone $startDate;
        $endDate->add(DateInterval::createFromDateString('1 month'));
        $endDate->sub(DateInterval::createFromDateString('1 day'));

        parent::__construct($startDate, $endDate);
    }

    /**
     * Retorna uma representação textual do mês no formato 'm/Y'
     * @return string
     */
    public function __toString()
    {
        return str_pad($this->month, 2, '0', STR_PAD_LEFT) . '/' . $this->year;
    }

    /**
     * Retorna uma instãncia de Month a partir de um número no formato YYYYMM
     * @param int $int
     * @return Month
     */
    public static function createFromInteger($int)
    {
        return new Month((int) mb_substr($int, 4), (int) mb_substr($int, 0, 4));
    }

    /**
     * Retorna um inteiro no formato Ym
     * @return int
     */
    public function getInt()
    {
        return (int) $this->year . str_pad($this->month, 2, '0', STR_PAD_LEFT);
    }

    /**
     * Retorna o objeto relativo ao quinto dia útil do mês
     * @return Date
     */
    public function getQuintoDiaUtil()
    {
        $contadorDosDiasUteis = 0;
        $quintoDiaUtil = null;
        foreach ($this->getDatePeriod() as $data) {
            if ($data->format('N') < 6) {
                $contadorDosDiasUteis++;
            }
            if ($contadorDosDiasUteis == 5) {
                $quintoDiaUtil = Date::cast($data);
                break;
            }
        }
        return $quintoDiaUtil;
    }

    /**
     * Retorna um array com as semanas deste mês
     * @return \p13\datetime\Week[]
     */
    public function getWeeks()
    {
        $intervaloSemanal = DateInterval::createFromDateString('1 week');
        $dataFim = clone $this->endDate;
        $periodo = new DatePeriod($this->startDate, $intervaloSemanal, $dataFim);
        $semanas = array();
        foreach ($periodo as $dia) {
            $semanas[] = new Week($dia->format('W'), $dia->format('Y'));
        }
        return $semanas;
    }

}