<?php

/*
 * This file is part of the RollerworksCache component package.
 *
 * (c) Sebastiaan Stok <s.stok@rollerscapes.net>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Rollerworks\Component\Cache;

use Symfony\Component\HttpFoundation\Session\SessionBagInterface;

/**
 * SessionCacheBag.
 *
 * Keeps the cached data in a session-bag.
 * And supports lifeTime for caching.
 *
 * @author Sebastiaan Stok <s.stok@rollerscapes.net>
 */
class SessionCacheBag implements SessionBagInterface
{
    /**
     * @var string
     */
    private $name = 'cache';

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

    /**
     * @var array
     */
    protected $data = array();

    /**
     * Constructor.
     *
     * @param string $storageKey The key used to store caches in the session
     */
    public function __construct($storageKey = '_rollerworks_cache')
    {
        $this->storageKey = $storageKey;
    }

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

    /**
     * Set the name of the bag.
     *
     * @param $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
     * {@inheritdoc}
     */
    public function initialize(array &$attributes)
    {
        $this->data = &$attributes;
    }

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

    /**
     * {@inheritdoc}
     */
    public function has($name)
    {
        if (!array_key_exists($name, $this->data)) {
            return false;
        }

        if (0 === $this->data[$name]['lifeTime']) {
            return true;
        }

        return $this->data[$name]['lifeTime'] > time();
    }

    /**
     * {@inheritdoc}
     */
    public function get($name, $default = null)
    {
        if (!array_key_exists($name, $this->data)) {
            return $default;
        }

        if (0 === $this->data[$name]['lifeTime']) {
            return $this->data[$name]['data'];
        }

        return $this->data[$name]['lifeTime'] < time() ? $default : $this->data[$name]['data'];
    }

    /**
     * {@inheritdoc}
     */
    public function set($name, $value, $lifeTime = 0)
    {
        if ($lifeTime > 0) {
            $lifeTime = time() + $lifeTime;
        }

        $this->data[$name] = array('data' => $value, 'lifeTime' => $lifeTime);
    }

    /**
     * Removes a cached item.
     *
     * @param string $name
     */
    public function remove($name)
    {
        if (array_key_exists($name, $this->data)) {
            unset($this->data[$name]);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function clear()
    {
        $return = $this->data;
        $this->data = array();

        return $return;
    }
}


<?php
/*
 * WellCommerce Open-Source E-Commerce Platform
 *
 * This file is part of the WellCommerce package.
 *
 * (c) Adam Piotrowski <adam@wellcommerce.org>
 *
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed with this source code.
 */
namespace WellCommerce\Bundle\ProductBundle\DataGrid;

use WellCommerce\Bundle\CoreBundle\DataGrid\AbstractDataGrid;
use WellCommerce\Component\DataGrid\Column\Column;
use WellCommerce\Component\DataGrid\Column\ColumnCollection;
use WellCommerce\Component\DataGrid\Column\Options\Appearance;
use WellCommerce\Component\DataGrid\Column\Options\Filter;
use WellCommerce\Component\DataGrid\Configuration\EventHandler\LoadedEventHandler;
use WellCommerce\Component\DataGrid\Configuration\EventHandler\ProcessEventHandler;
use WellCommerce\Component\DataGrid\Configuration\EventHandler\UpdateRowEventHandler;
use WellCommerce\Component\DataGrid\Options\OptionsInterface;

/**
 * Class ProductDataGrid
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class ProductDataGrid extends AbstractDataGrid
{
    /**
     * {@inheritdoc}
     */
    public function configureColumns(ColumnCollection $collection)
    {
        $collection->add(new Column([
            'id'         => 'id',
            'caption'    => $this->trans('common.label.id'),
            'appearance' => new Appearance([
                'width'   => 90,
                'visible' => false,
            ]),
            'filter'     => new Filter([
                'type' => Filter::FILTER_BETWEEN,
            ]),
        ]));

        $collection->add(new Column([
            'id'         => 'name',
            'caption'    => $this->trans('common.label.name'),
            'appearance' => new Appearance([
                'width' => 200,
            ]),
        ]));

        $collection->add(new Column([
            'id'       => 'sku',
            'editable' => true,
            'caption'  => $this->trans('common.label.sku'),
        ]));

        $collection->add(new Column([
            'id'      => 'category',
            'caption' => $this->trans('common.label.categories'),
            'filter'  => new Filter([
                'type'                => Filter::FILTER_TREE,
                'filtered_column'     => 'categoryId',
                'options'             => $this->get('category.repository')->getDataGridFilterOptions(),
                'load_children_route' => 'admin.category.ajax.get_children',
            ]),
        ]));

        $collection->add(new Column([
            'id'       => 'grossAmount',
            'caption'  => $this->trans('common.label.gross_price'),
            'editable' => true,
            'filter'   => new Filter([
                'type' => Filter::FILTER_BETWEEN,
            ]),
        ]));

        $collection->add(new Column([
            'id'       => 'stock',
            'caption'  => $this->trans('common.label.stock'),
            'editable' => true,
            'filter'   => new Filter([
                'type' => Filter::FILTER_BETWEEN,
            ]),
        ]));

        $collection->add(new Column([
            'id'       => 'weight',
            'caption'  => $this->trans('common.label.dimension.weight'),
            'editable' => true,
            'filter'   => new Filter([
                'type' => Filter::FILTER_BETWEEN,
            ]),
        ]));
    }

    /**
     * {@inheritdoc}
     */
    protected function configureOptions(OptionsInterface $options)
    {
        parent::configureOptions($options);

        $eventHandlers = $options->getEventHandlers();

        $eventHandlers->add(new UpdateRowEventHandler([
            'function' => $this->getJavascriptFunctionName('update'),
            'route'    => $this->getActionUrl('update'),
        ]));

        $eventHandlers->add(new ProcessEventHandler([
            'function' => $this->getJavascriptFunctionName('process'),
        ]));

        $eventHandlers->add(new LoadedEventHandler([
            'function' => $this->getJavascriptFunctionName('loaded'),
        ]));
    }
}


<?php
/*
 * Copyright (c) 2014 @trashtoy
 * https://github.com/trashtoy/
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
 * Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
/**
 * PHP class file.
 * @auhtor trashtoy
 * @since  2.0.0
 */
namespace Peach\Util;

/**
 * 値の各種変換を行うユーティリティクラスです.
 */
class Values
{
    /**
     * このクラスはインスタンス化することができません.
     */
    private function __construct() {}

    /**
     * 指定された値を整数に変換します.
     * この関数は変換処理に {@link http://jp1.php.net/manual/ja/function.intval.php intval()} を利用します.
     *
     * 最小値が指定されている場合,
     * 変換後の値が最小値より小さければ最小値を返します.
     *
     * 最小値と最大値の両方が指定されている場合,
     * 変換後の値が最大値より大きければ最大値を返します.
     *
     * 最小値が最大値より大きい場合, 最大値の指定は無視されます.
     * 最大値のみ指定したい場合は, 最小値を NULL にしてください.
     *
     * 引数にオブジェクトが指定された場合は 1 として扱います.
     *
     * @param  mixed $value 変換元の値
     * @param  int   $min   最小値 (省略可). 変換後の値がこの値よりも小さい場合は, この値を返す.
     * @param  int   $max   最大値 (省略可). 変換後の値がこの値よりも大きい場合は, この値を返す.
     * @return int          引数を整数に変換した値
     */
    public static function intValue($value, $min = null, $max = null)
    {
        if (is_object($value)) {
            return self::intValue(1, $min, $max);
        }
        if (!is_int($value)) {
            $iValue = intval($value);
            return self::intValue($iValue, $min, $max);
        }
        if (isset($min) && isset($max) && $max < $min) {
            return self::intValue($value, $min);
        }
        if (isset($min) && $value < $min) {
            return $min;
        }
        if (isset($max) && $max < $value) {
            return $max;
        }

        return $value;
    }

    /**
     * 指定された値を文字列型に変換します.
     *
     * __toString() が定義されているオブジェクトの場合は __toString() の結果,
     * それ以外のオブジェクトはクラス名を返します.
     * リソース型の場合は {@link http://jp1.php.net/manual/ja/function.get-resource-type.php get_resource_type()} にリソース ID
     * を付け足した結果を返します.
     * それ以外は string 型にキャストした結果を返します.
     *
     * @param  mixed  $value 変換対象の値
     * @return string        変換後の文字列
     */
    public static function stringValue($value)
    {
        if (is_object($value)) {
            return (method_exists($value, '__toString')) ? $value->__toString() : get_class($value);
        }
        if (is_resource($value)) {
            $parts = explode(" ", strval($value));
            $id    = array_pop($parts);
            return get_resource_type($value) . " " . $id;
        }

        return is_string($value) ? $value : strval($value);
    }

    /**
     * 指定された値を配列に変換します.
     * 引数が配列の場合は引数をそのまま返します.
     * 配列以外の値の場合は, 第二引数によって結果が変わります.
     *
     * - $wrap = TRUE の場合, 引数を長さ 1 の配列として返す.
     * - $wrap = FALSE の場合, 空の配列を返す.
     *
     * デフォルトでは $wrap = FALSE となります.
     *
     * @param  mixed $value 変換元の値.
     * @param  bool  $wrap  配列以外の値の場合に, 長さ 1 の配列に変換する場合は TRUE
     * @return array        変換後の配列
     */
    public static function arrayValue($value, $wrap = false)
    {
        if (is_array($value)) {
            return $value;
        }

        return $wrap ? array($value) : array();
    }

    /**
     * 指定された値を bool 型に変換します.
     * この関数は "Yes", "No", "True", "False", "OK", "NG" などの文字列を
     * bool に変換する用途を想定したものです.
     *
     * 引数が bool 型の場合は引数をそのまま返します.
     *
     * 引数が文字列型の場合,
     * 先頭の 1 バイトが T, Y, O のいずれかの場合は TRUE,
     * 先頭の 1 バイトが F, N のいずれかの場合は FALSE,
     * それ以外は文字列を bool にキャストした結果を返します.
     * (大文字・小文字は区別しません)
     *
     * 引数が数値型の場合, bool にキャストした結果を返します.
     * すなわち 0 以外の値は TRUE, 0 の場合は FALSE を返します.
     *
     * 以上の条件にあてはまらない値の場合,
     * $defaultValue が NULL または未指定の場合は第 1 引数を
     * bool にキャストした結果を返します.
     * $defaultValue が指定されている場合はその bool 値を返します.
     *
     * @param  mixed $value        変換対象の値
     * @param  bool  $defaultValue デフォルトの返り値
     * @return bool                変換後の bool 値
     */
    public static function boolValue($value, $defaultValue = null)
    {
        if (is_bool($value)) {
            return $value;
        }
        if (is_string($value)) {
            return self::stringToBool($value, $defaultValue);
        }
        if (is_numeric($value)) {
            return (bool) $value;
        }

        return self::handleBoolValue($value, $defaultValue);
    }

    /**
     * 文字列を bool 型にキャストします.
     * @param  string $value
     * @param  bool   $defaultValue
     * @return bool
     */
    private static function stringToBool($value, $defaultValue = null)
    {
        // @codeCoverageIgnoreStart
        static $tPrefix = null, $fPrefix = null;
        if (!isset($tPrefix)) {
            $tPrefix = array("t", "y", "o");
            $fPrefix = array("f", "n");
        }
        // @codeCoverageIgnoreEnd

        $prefix = strtolower(substr($value, 0, 1));
        if (in_array($prefix, $tPrefix)) {
            return true;
        }
        if (in_array($prefix, $fPrefix)) {
            return false;
        }

        return self::handleBoolValue($value, $defaultValue);
    }

    /**
     * デフォルト値に NULL 以外の値が指定されている場合はデフォルト値の bool 表現を,
     * そうでない場合は第一引数の bool 表現を返します.
     * @param  mixed $value
     * @param  bool  $defaultValue
     * @return bool
     */
    private static function handleBoolValue($value, $defaultValue = null)
    {
        return isset($defaultValue) ? (bool) $defaultValue : (bool) $value;
    }

    /**
     * 指定された値の型を返します.
     * 内部関数の {@link http://jp1.php.net/manual/ja/function.gettype.php gettype()} とほぼ同じ動作をしますが,
     * 引数にオブジェクトを指定した場合に文字列 "object"
     * ではなくその値のクラス名を返すところが異なります.
     *
     * @param mixed $var 検査対象の値
     */
    public static function getType($var)
    {
        return is_object($var) ? get_class($var) : gettype($var);
    }
}


<?php
/**
 * HAL.php
 *
 * Ariel Ferrandini <arielferrandini@gmail.com>
 * 27/09/14
 */

namespace PHPGames\Console\Helper;

use Symfony\Component\Console\Application;
use Symfony\Component\Console\Helper\Helper;
use Symfony\Component\Console\Output\OutputInterface;

class HAL
{
    /**
     * @var OutputInterface
     */
    private $output;

    /**
     * @var bool
     */
    private $center;

    /**
     * @var bool
     */
    private $showText;

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

    /**
     * @param OutputInterface $output
     * @param bool            $center
     */
    public function __construct(OutputInterface $output, $showText = true, $center = true)
    {
        $this->output = $output;
        $this->showText = (bool)$showText;
        $this->center = (bool)$center;

        if ($this->center) {
            $application = new Application();
            $this->screenSize = $application->getTerminalDimensions();
            unset($application);

            // If the screen size is 0 disable the center flag
            if (!$this->screenSize[0]) {
                $this->center = false;
            }
        }
    }

    /**
     * Writes HAL Logo
     */
    public function sayHello()
    {
        $text = $this->getHALLogo();

        if ($this->showText) {
            $text .= $this->getHelloDave();
        }

        $lines = explode("\n", $text);

        $spaces = '';
        if ($this->center) {
            $max_length = 0;
            foreach ($lines as $line) {
                $max_length = max($max_length, Helper::strlenWithoutDecoration($this->output->getFormatter(), $line));
            }

            $numberOfSpaces = floor(($this->screenSize[0] - $max_length) / 2);
            if ($numberOfSpaces > 0) {
                $spaces = str_repeat(' ', $numberOfSpaces);
            }
        }

        foreach ($lines as $line) {
            $this->output->writeln($spaces.$line);
        }
    }

    /**
     * Returns the HALLogo text
     * @return string
     */
    private function getHALLogo()
    {
        $spaces = '';
        if ($this->showText) {
            $spaces = str_repeat(' ', 35);
        }

        $halLogo = "
$spaces                  <bg=white>          </bg=white>
$spaces           <bg=white>                        </bg=white>
$spaces       <bg=white>      </bg=white>                    <bg=white>      </bg=white>
$spaces     <bg=white>      </bg=white>       <bg=red>          </bg=red>       <bg=white>      </bg=white>
$spaces    <bg=white>    </bg=white>    <bg=red>                    </bg=red>     <bg=white>    </bg=white>
$spaces  <bg=white>   </bg=white>     <bg=red>                        </bg=red>     <bg=white>    </bg=white>
$spaces  <bg=white>   </bg=white>    <bg=red>                            </bg=red>    <bg=white>   </bg=white>
$spaces <bg=white>   </bg=white>    <bg=red>                              </bg=red>    <bg=white>   </bg=white>
$spaces <bg=white>   </bg=white>   <bg=red>                                </bg=red>    <bg=white>  </bg=white>
$spaces<bg=white>   </bg=white>    <bg=red>              <bg=yellow>    </bg=yellow>              </bg=red>    <bg=white>   </bg=white>
$spaces<bg=white>   </bg=white>    <bg=red>              <bg=yellow>    </bg=yellow>              </bg=red>    <bg=white>   </bg=white>
$spaces <bg=white>  </bg=white>    <bg=red>                                </bg=red>    <bg=white>  </bg=white>
$spaces <bg=white>   </bg=white>    <bg=red>                              </bg=red>    <bg=white>   </bg=white>
$spaces  <bg=white>   </bg=white>    <bg=red>                            </bg=red>    <bg=white>   </bg=white>
$spaces  <bg=white>   </bg=white>     <bg=red>                        </bg=red>     <bg=white>    </bg=white>
$spaces    <bg=white>    </bg=white>      <bg=red>                  </bg=red>       <bg=white>   </bg=white>
$spaces     <bg=white>    </bg=white>       <bg=red>            </bg=red>        <bg=white>    </bg=white>
$spaces       <bg=white>      </bg=white>                   <bg=white>      </bg=white>
$spaces           <bg=white>                         </bg=white>
$spaces                  <bg=white>           </bg=white>
";

        return $halLogo;
    }

    /**
     * Returns the HELO DAVE text
     * @return string
     */
    private function getHelloDave()
    {
        return "

                                                                                <options=blink>:#######'</options=blink>
 @      :@ @@@@@@@@@ :@         @         +@@@@@@@@;         .@@@@@@@@+   @@@@@@@   @@@     @. @@@@@@@@@  <options=blink>+@@@@@@@@@@</options=blink>
,@.     #@ @@@@@@@@@ @@        `@.        @@@@@@@@@@         #@@@@@@@@@  ;@@@@@@@.  @@@`    @',@@@@@@@@@  <options=blink>@@@@@@@@@@@</options=blink>
,@.     #@ @:        #@        `@.        @@    #@@@         #@      @@  ;@    `@.  @@@`    @',@.         <options=blink>@@@@@@@@@@@</options=blink>
,@,     #@ @:        #@        `@.        @@    #@@@         #@      @@  ;@    `@.  @@@`    @',@.         <options=blink>@@@@@@@@@@@</options=blink>
,@.     #@ @@##@@@@+ #@        `@.        @@    #@@@         #@      @@  '@#####@#; @@@.  ,@@',@###@@@@'  <options=blink>@@@@@@@@@@@</options=blink>
,@@@@@@@@@ @@@@@@@@@ #@        `@.        @@    '@@@         #@      @@  ;@@@@@@@@@ @@@`  @@@;,@@@@@@@@@  <options=blink>@@@@@@@@@@@</options=blink>
:@@@@@@@@@ @@@       #@@@      `@@@       @@      @@         @@@+    @@ @@@      @@  .@.  @@  ,@@@        <options=blink>@@@@@@@@@@@</options=blink>
:@@@    #@ @@@       #@@@      `@@@       @@      @@         @@@#    @@ @@@      @@  .@.  @@  ,@@@        <options=blink>@@@@@@@@@@@</options=blink>
:@@@    #@ @@@       #@@@      `@@@       @@      @@         @@@#    @@ @@@      @@  .@.  @@  ,@@@        <options=blink>@@@@@@@@@@@</options=blink>
:@@@    #@ @@@       #@@@      `@@@       @@      @@         @@@#    @@ @@@      @@  .@`  @@  ,@@@        <options=blink>@@@@@@@@@@@</options=blink>
:@@@    #@ @@@@@@@@@ #@@@@@@@@@`@@@@@@@@@ @@@@@@@@@@         @@@@@@@@@@ @@@      @@  .@@@@@@  ,@@@@@@@@@  <options=blink>@@@@@@@@@@@</options=blink>
 '',     ' '';;'''''  ''''''''` ''''''''' ,####+'''.         .@@@@#'''; ;''      .;   ';;;;,   '';;'''''   <options=blink>@@@@@@@@@:</options=blink>
";
    }
}


<?php declare(strict_types=1);

namespace Identity\Events;

use GeneralForm\EventException;
use GeneralForm\IEvent;
use GeneralForm\IEventContainer;
use Identity\IdentityException;
use Identity\IIdentityModel;
use Nette\SmartObject;

/**
 * Class DibiForgottenEvent
 *
 * @author  geniv
 * @package Identity\Events
 */
class ForgottenStep2Event implements IEvent
{
    use SmartObject;

    /** @var IIdentityModel */
    private $identityModel;

    /**
     * ForgottenStep2Event constructor.
     *
     * @param IIdentityModel $identityModel
     */
    public function __construct(IIdentityModel $identityModel)
    {
        $this->identityModel = $identityModel;
    }

    /**
     * Update.
     *
     * @param IEventContainer $eventContainer
     * @param array           $values
     * @throws EventException
     * @throws \Dibi\Exception
     */
    public function update(IEventContainer $eventContainer, array $values)
    {
        try {
            $this->identityModel->processForgotten($values['hash'], $values['password']);
        } catch (IdentityException $e) {
            throw new EventException($e->getMessage());
        }
    }
}


<?php
/*
 * WellCommerce Open-Source E-Commerce Platform
 *
 * This file is part of the WellCommerce package.
 *
 * (c) Adam Piotrowski <adam@wellcommerce.org>
 *
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed with this source code.
 */

namespace WellCommerce\Bundle\ProductBundle\EventListener;

use Doctrine\Common\EventSubscriber;
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use WellCommerce\Bundle\ProductBundle\Entity\ProductInterface;
use WellCommerce\Bundle\ProductBundle\Entity\VariantInterface;
use WellCommerce\Bundle\TaxBundle\Helper\TaxHelper;

/**
 * Class ProductDoctrineEventSubscriber
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class ProductDoctrineEventSubscriber implements EventSubscriber
{
    public function getSubscribedEvents()
    {
        return [
            'prePersist',
            'preUpdate',
        ];
    }

    public function preUpdate(LifecycleEventArgs $args)
    {
        $this->onProductDataBeforeSave($args);
    }

    public function prePersist(LifecycleEventArgs $args)
    {
        $this->onProductDataBeforeSave($args);
    }

    public function onProductDataBeforeSave(LifecycleEventArgs $args)
    {
        $entity = $args->getObject();
        if ($entity instanceof ProductInterface) {
            $this->refreshProductSellPrices($entity);
            $this->refreshProductBuyPrices($entity);
            $this->syncProductStock($entity);
        }

        if ($entity instanceof VariantInterface) {
            $this->refreshProductVariantSellPrice($entity);
            $this->syncVariantStock($entity);
        }
    }

    /**
     * Recalculates sell prices for product
     *
     * @param ProductInterface $product
     */
    protected function refreshProductSellPrices(ProductInterface $product)
    {
        $sellPrice             = $product->getSellPrice();
        $grossAmount           = $sellPrice->getGrossAmount();
        $discountedGrossAmount = $sellPrice->getDiscountedGrossAmount();
        $taxRate               = $product->getSellPriceTax()->getValue();
        $netAmount             = TaxHelper::calculateNetPrice($grossAmount, $taxRate);
        $discountedNetAmount   = TaxHelper::calculateNetPrice($discountedGrossAmount, $taxRate);

        $sellPrice->setTaxRate($taxRate);
        $sellPrice->setTaxAmount($grossAmount - $netAmount);
        $sellPrice->setNetAmount($netAmount);
        $sellPrice->setDiscountedTaxAmount($discountedGrossAmount - $discountedNetAmount);
        $sellPrice->setDiscountedNetAmount($discountedNetAmount);
    }

    /**
     * Recalculates sell prices for single product attribute
     *
     * @param VariantInterface $variant
     */
    protected function refreshProductVariantSellPrice(VariantInterface $variant)
    {
        $product               = $variant->getProduct();
        $sellPrice             = $product->getSellPrice();
        $grossAmount           = $this->calculateAttributePrice($variant, $sellPrice->getGrossAmount());
        $discountedGrossAmount = $this->calculateAttributePrice($variant, $sellPrice->getDiscountedGrossAmount());
        $taxRate               = $product->getSellPriceTax()->getValue();
        $netAmount             = TaxHelper::calculateNetPrice($grossAmount, $taxRate);
        $discountedNetAmount   = TaxHelper::calculateNetPrice($discountedGrossAmount, $taxRate);

        $productAttributeSellPrice = $variant->getSellPrice();
        $productAttributeSellPrice->setTaxRate($taxRate);
        $productAttributeSellPrice->setTaxAmount($grossAmount - $netAmount);
        $productAttributeSellPrice->setGrossAmount($grossAmount);
        $productAttributeSellPrice->setNetAmount($netAmount);
        $productAttributeSellPrice->setDiscountedGrossAmount($discountedGrossAmount);
        $productAttributeSellPrice->setDiscountedTaxAmount($discountedGrossAmount - $discountedNetAmount);
        $productAttributeSellPrice->setDiscountedNetAmount($discountedNetAmount);
        $productAttributeSellPrice->setValidFrom($sellPrice->getValidFrom());
        $productAttributeSellPrice->setValidTo($sellPrice->getValidTo());
        $productAttributeSellPrice->setCurrency($sellPrice->getCurrency());
    }

    /**
     * Calculates new amount for attribute
     *
     * @param VariantInterface          $variant
     * @param                           $amount
     *
     * @return float
     */
    protected function calculateAttributePrice(VariantInterface $variant, $amount)
    {
        $modifierType  = $variant->getModifierType();
        $modifierValue = $variant->getModifierValue();

        switch ($modifierType) {
            case '+':
                $amount = $amount + $modifierValue;
                break;
            case '-':
                $amount = $amount - $modifierValue;
                break;
            case '%':
                $amount = $amount * ($modifierValue / 100);
                break;
        }

        return round($amount, 2);
    }

    /**
     * Recalculates buy prices for product
     *
     * @param ProductInterface $product
     */
    protected function refreshProductBuyPrices(ProductInterface $product)
    {
        $buyPrice    = $product->getBuyPrice();
        $grossAmount = $buyPrice->getGrossAmount();
        $taxRate     = $product->getBuyPriceTax()->getValue();
        $netAmount   = TaxHelper::calculateNetPrice($grossAmount, $taxRate);

        $buyPrice->setTaxRate($taxRate);
        $buyPrice->setTaxAmount($grossAmount - $netAmount);
        $buyPrice->setNetAmount($netAmount);
    }

    protected function syncProductStock(ProductInterface $product)
    {
        $trackStock       = $product->getTrackStock();
        $stock            = $this->getProductStock($product);
        $grossPrice       = $product->getSellPrice()->getFinalGrossAmount();
        $isStockAvailable = (true === $trackStock) ? $stock > 0 : 1;
        $isPriceNonZero   = $grossPrice > 0;

        if (false === $product->isEnabled() && true === $trackStock) {
            $product->setEnabled($isStockAvailable);
        }

        $product->setStock($stock);

        if (false === $isPriceNonZero) {
            $product->setEnabled(false);
        }

        if (0 === $product->getCategories()->count()) {
            $product->setEnabled(false);
        }
    }

    protected function syncVariantStock(VariantInterface $variant)
    {
        $product          = $variant->getProduct();
        $trackStock       = $product->getTrackStock();
        $stock            = $variant->getStock();
        $isStockAvailable = (true === $trackStock) ? $stock > 0 : 1;
        $variant->setEnabled($isStockAvailable);

        if (false === $product->isEnabled()) {
            $variant->setEnabled(false);
        }
    }

    protected function getProductStock(ProductInterface $product) : int
    {
        if (0 === $product->getVariants()->count()) {
            return $product->getStock();
        }

        $stock = 0;
        $product->getVariants()->map(function (VariantInterface $variant) use (&$stock) {
            $stock = $stock + $variant->getStock();
        });

        return $stock;
    }
}


<?php

namespace Pluralize;

class Pluralize
{
	/**
	 * @var \Pluralize\RuleSet
	 */
	protected $ruleset;

	public function __construct($options = array())
	{
		$this->ruleset(new RuleSet());
	}

	/**
	 * @param string|\Pluralize\RuleSet $rulesetClass
	 * @return \Pluralize\RuleSet
	 */
	public function ruleset($rulesetClass = null)
	{
		if (!is_null($rulesetClass)) {
			if ($rulesetClass instanceof RuleSet) {
				$this->ruleset = $rulesetClass;
			} else {
				$this->ruleset = new $rulesetClass();
			}
		}

		return $this->ruleset;
	}

	public function fix($word, $count = 0, $includeCount = false)
	{
		return ($includeCount ? $count . ' ' : '') . ($count === 1 ? $this->singular($word) : $this->plural($word));
	}

	public function singular($word)
	{
		$restoreCase = $this->restoreWordCase($word);
		$word = strtolower($word);

		if ($irregular = $this->ruleset()->irregular($word)) {
			return $restoreCase($word);
		}

		// There is no reverse look up, for plural to singular, so loop through them.
		foreach ($this->ruleset()->irregularRules as $rule => $replacement) {
			if ($replacement === $word) {
				return $restoreCase($rule);
			}
		}

		$found = $this->ruleset()->uncountable($word);
		if ($found) {
			return $restoreCase($word);
		}

		return $restoreCase($this->sanitize($word, $this->ruleset()->singularRules));
	}

	/**
	 * @param $word
	 * @return bool|mixed
	 */
	public function plural($word)
	{
		$restoreCase = $this->restoreWordCase($word);
		$word = strtolower($word);

		if ($irregular = $this->ruleset()->irregular($word)) {
			return $restoreCase($irregular);
		}

		$found = $this->ruleset()->uncountable($word);
		if ($found) {
			return $restoreCase($word);
		}

		return $restoreCase($this->sanitize($word, $this->ruleset()->pluralRules));
	}

	/**
	 * @param $word
	 * @param $rules
	 * @return string The word, or fixed word.
	 */
	protected function sanitize($word, $rules)
	{
		foreach ($rules as $rule => $replacement) {
			$found = preg_replace($rule, $replacement, $word);
			if ($found != $word) {
				return $found;
			}
		}
		return $word;
	}

	/**
	 * Detect current casing, and restore automagicaly later through a callable;
	 *
	 * @param $token string
	 *
	 * @return \Callable
	 */
	protected function restoreWordCase($token)
	{
		if ($token === strtoupper($token)) {
			return function ($word) {
				return strtoupper($word);
			};
		}

		if ($token === ucfirst($token)) {
			return function ($word) {
				return ucfirst($word);
			};
		}

		return function ($word) {
			return $word;
		};
	}
}


<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\web;

use Yii;
use yii\base\Component;
use yii\base\Exception;

/**
 * AssetConverter supports conversion of several popular script formats into JS or CSS scripts.
 *
 * It is used by [[AssetManager]] to convert files after they have been published.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class AssetConverter extends Component implements AssetConverterInterface
{
    /**
     * @var array the commands that are used to perform the asset conversion.
     * The keys are the asset file extension names, and the values are the corresponding
     * target script types (either "css" or "js") and the commands used for the conversion.
     *
     * You may also use a path alias to specify the location of the command:
     *
     * ```php
     * [
     *     'styl' => ['css', '@app/node_modules/bin/stylus < {from} > {to}'],
     * ]
     * ```
     */
    public $commands = [
        'less' => ['css', 'lessc {from} {to} --no-color --source-map'],
        'scss' => ['css', 'sass {from} {to} --sourcemap'],
        'sass' => ['css', 'sass {from} {to} --sourcemap'],
        'styl' => ['css', 'stylus < {from} > {to}'],
        'coffee' => ['js', 'coffee -p {from} > {to}'],
        'ts' => ['js', 'tsc --out {to} {from}'],
    ];
    /**
     * @var boolean whether the source asset file should be converted even if its result already exists.
     * You may want to set this to be `true` during the development stage to make sure the converted
     * assets are always up-to-date. Do not set this to true on production servers as it will
     * significantly degrade the performance.
     */
    public $forceConvert = false;

    /**
     * Converts a given asset file into a CSS or JS file.
     * @param string $asset the asset file path, relative to $basePath
     * @param string $basePath the directory the $asset is relative to.
     * @return string the converted asset file path, relative to $basePath.
     */
    public function convert($asset, $basePath)
    {
        $pos = strrpos($asset, '.');
        if ($pos !== false) {
            $ext = substr($asset, $pos + 1);
            if (isset($this->commands[$ext])) {
                list ($ext, $command) = $this->commands[$ext];
                $result = substr($asset, 0, $pos + 1) . $ext;
                if ($this->forceConvert || @filemtime("$basePath/$result") < @filemtime("$basePath/$asset")) {
                    $this->runCommand($command, $basePath, $asset, $result);
                }

                return $result;
            }
        }

        return $asset;
    }

    /**
     * Runs a command to convert asset files.
     * @param string $command the command to run. If prefixed with an `@` it will be treated as a path alias.
     * @param string $basePath asset base path and command working directory
     * @param string $asset the name of the asset file
     * @param string $result the name of the file to be generated by the converter command
     * @return boolean true on success, false on failure. Failures will be logged.
     * @throws \yii\base\Exception when the command fails and YII_DEBUG is true.
     * In production mode the error will be logged.
     */
    protected function runCommand($command, $basePath, $asset, $result)
    {
        $command = Yii::getAlias($command);

        $command = strtr($command, [
            '{from}' => escapeshellarg("$basePath/$asset"),
            '{to}' => escapeshellarg("$basePath/$result"),
        ]);
        $descriptor = [
            1 => ['pipe', 'w'],
            2 => ['pipe', 'w'],
        ];
        $pipes = [];
        $proc = proc_open($command, $descriptor, $pipes, $basePath);
        $stdout = stream_get_contents($pipes[1]);
        $stderr = stream_get_contents($pipes[2]);
        foreach ($pipes as $pipe) {
            fclose($pipe);
        }
        $status = proc_close($proc);

        if ($status === 0) {
            Yii::trace("Converted $asset into $result:\nSTDOUT:\n$stdout\nSTDERR:\n$stderr", __METHOD__);
        } elseif (YII_DEBUG) {
            throw new Exception("AssetConverter command '$command' failed with exit code $status:\nSTDOUT:\n$stdout\nSTDERR:\n$stderr");
        } else {
            Yii::error("AssetConverter command '$command' failed with exit code $status:\nSTDOUT:\n$stdout\nSTDERR:\n$stderr", __METHOD__);
        }

        return $status === 0;
    }
}


<?php
/*
 * Copyright (c) 2015 @trashtoy
 * https://github.com/trashtoy/
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
 * Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
/**
 * PHP class file.
 * @auhtor trashtoy
 * @since  2.1.0
 */
namespace Peach\DF;

/**
 * 複数の Codec のエンコード・デコード処理を連結させるための Codec です.
 *
 * このクラスはコンストラクタに 2 種類の Codec を指定してインスタンスを初期化します.
 * エンコードは, コンストラクタに指定した 1 番目, 2 番目の Codec の encode() を順に呼び出すことで実行されます.
 * デコードは, エンコードとは逆に 2 番目, 1 番目の順番で実行されます.
 */
class CodecChain implements Codec
{
    /**
     * 1 番目の Codec です. エンコードの際に先に処理されます.
     *
     * @var Codec
     */
    private $first;

    /**
     * 2 番目の Codec です. デコードの際に先に処理されます.
     *
     * @var Codec
     */
    private $second;

    /**
     * 指定された Codec を使用して変換を行う CodecChain インスタンスを生成します.
     *
     * もしも第 1 Codec が CodecChain インスタンスだった場合は以下のアルゴリズムに従ってチェーンの再構成を行います.
     *
     * - 引数の CodecChain の第 1 Codec を新しいインスタンスの第 1 Codec として適用します
     * - 引数の CodecChain の第 2 Codec とコンストラクタ引数の第 2 Codec で新しい CodecChain を生成し, それを新しいインスタンスの第 2 Codec として適用します
     *
     * @param Codec $first  1 番目の Codec
     * @param Codec $second 2 番目の Codec
     */
    public function __construct(Codec $first, Codec $second)
    {
        if ($first instanceof CodecChain) {
            $this->first  = $first->first;
            $this->second = new self($first->second, $second);
        } else {
            $this->first  = $first;
            $this->second = $second;
        }
    }

    /**
     * チェーンの末尾に新しい Codec を連結させた, 新しい CodecChain インスタンスを返します.
     *
     * @param  Codec $c
     * @return CodecChain
     */
    public function append(Codec $c)
    {
        return new CodecChain($this->first, new CodecChain($this->second, $c));
    }

    /**
     * チェーンの先頭に新しい Codec を連結させた, 新しい CodecChain インスタンスを返します.
     *
     * @param  Codec $c
     * @return CodecChain
     */
    public function prepend(Codec $c)
    {
        return new CodecChain($c, $this);
    }

    /**
     * このオブジェクトに指定された Codec を使って指定された値をデコードします.
     *
     * @param  mixed $text デコード対象の値
     * @return mixed       変換結果
     */
    public function decode($text)
    {
        return $this->first->decode($this->second->decode($text));
    }

    /**
     * このオブジェクトに指定された Codec を使って指定された値をエンコードします.
     *
     * @param  mixed $var エンコード対象の値
     * @return mixed      変換結果
     */
    public function encode($var)
    {
        return $this->second->encode($this->first->encode($var));
    }
}


<?php
/**
 * Phossa Project
 *
 * PHP version 5.4
 *
 * @category  Library
 * @package   Phossa\Query
 * @author    Hong Zhang <phossa@126.com>
 * @copyright 2015 phossa.com
 * @license   http://mit-license.org/ MIT License
 * @link      http://www.phossa.com/
 */
/*# declare(strict_types=1); */

namespace Phossa\Query\Clause;

use Phossa\Query\Dialect\Common\SelectStatementInterface;

/**
 * FromTrait
 *
 * @trait
 * @package Phossa\Query
 * @author  Hong Zhang <phossa@126.com>
 * @see     FromInterface
 * @version 1.0.0
 * @since   1.0.0 added
 */
trait FromTrait
{
    /**
     * TABLES
     *
     * @var    array
     * @access protected
     */
    protected $clause_table = [];

    /**
     * {@inheritDoc}
     */
    public function from(
        $table,
        /*# string */ $tableAlias = ''
    )/* : FromInterface */ {
        if (is_array($table)) {
            foreach ($table as $key => $val) {
                if (is_int($key)) {
                    $key = $val;
                    $val = '';
                }
                $this->from($key, $val);
            }
        } else {
            // overwrite exisiting same table
            $key = array_search($table, $this->clause_table, true);
            if (false !== $key) {
                unset($this->clause_table[$key]);
            }

            if (empty($tableAlias)) {
                $this->clause_table[] = $table;
            } else {
                $this->clause_table[(string) $tableAlias] = $table;
            }
        }
        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function table(
        $table,
        /*# string */ $tableAlias = ''
    )/* : FromInterface */ {
        return $this->from($table, $tableAlias);
    }

    /**
     * Build FROM
     *
     * @return array
     * @access protected
     */
    protected function buildFrom()/*# : array */
    {
        $result = [];
        foreach ($this->clause_table as $as => $tbl) {
            // table alias
            $alias = is_int($as) ? '' : (' AS ' . $this->quoteSpace($as));

            // subselect
            if (is_object($tbl) && $tbl instanceof SelectStatementInterface) {
                $tbl = '(' . $tbl->getStatement([], false) . ')';

            // normal table
            } else {
                $tbl = $this->quote($tbl);
            }
            $result[] = $tbl . $alias;
        }
        return $result;
    }

    /**
     * Get current table name
     *
     * @param  bool $returnAlias return alias is ok
     * @return string
     * @access protected
     */
    protected function getTableName($returnAlias = false)/*# : string */
    {
        $result = '';
        foreach ($this->clause_table as $k => $v) {
            if (!is_int($k) && $returnAlias) {
                return $k;
            } else {
                return $v;
            }
        }
        return $result;
    }

    /**
     * Split "users u" into "users" and alias "u"
     *
     * @param  string $string
     * @return array
     * @access protected
     */
    protected function splitAlias(/*# string */ $string)/*# : array */
    {
        return preg_split('/\s+/', $string, 2, PREG_SPLIT_NO_EMPTY);
    }

    /* utilities from UtilityTrait */
    abstract protected function quote(/*# string */ $str)/*# : string */;
    abstract protected function quoteSpace(/*# string */ $str)/*# : string */;
}


<?php
/*
 * Copyright (c) 2015 @trashtoy
 * https://github.com/trashtoy/
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
 * Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
/**
 * PHP class file.
 * @auhtor trashtoy
 * @since  2.1.0
 * @ignore
 */
namespace Peach\DF\JsonCodec;

/**
 * 空白文字をあらわす Expression です. 以下の BNF ルールを解釈します.
 *
 * <pre>
 * ws = *(
 *         %x20 /              ; Space
 *         %x09 /              ; Horizontal tab
 *         %x0A /              ; Line feed or New line
 *         %x0D )              ; Carriage return
 * </pre>
 *
 * @ignore
 */
class WS implements Expression
{
    /**
     * このクラスはシングルトンです.
     */
    private function __construct() {}

    /**
     * このクラスの唯一のインスタンスを返します.
     *
     * @return WS
     * @codeCoverageIgnore
     */
    public static function getInstance()
    {
        static $instance = null;
        if ($instance === null) {
            $instance = new self();
        }
        return $instance;
    }

    /**
     * 文字 %x20, %x09, %x0A, %x0D を読み飛ばします.
     *
     * @param Context $context
     */
    public function handle(Context $context)
    {
        static $wsList = array("\r", "\n", "\r\n", "\t", " ");
        while ($context->hasNext()) {
            $current = $context->current();
            if (!in_array($current, $wsList)) {
                break;
            }
            $context->next();
        }
    }
}


<?php

/*
 * Copyright (c) 2015 @trashtoy
 * https://github.com/trashtoy/
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
 * Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
/**
 * PHP class file.
 * @auhtor trashtoy
 * @since  2.1.0
 * @ignore
 */
namespace Peach\DF\JsonCodec;

use stdClass;
use Peach\DF\JsonCodec;

/**
 * JSON の BNF ルール object をあらわす Expression です.
 * RFC 7159 で定義されている以下のフォーマットを解釈します.
 *
 * <pre>
 * object = begin-object [ member *( value-separator member ) ] end-object
 * </pre>
 *
 * @ignore
 */
class ObjectExpr implements Expression
{
    /**
     * handle() の解析結果です.
     *
     * @var mixed
     */
    private $result;

    /**
     * 新しい ObjectExpr オブジェクトを構築します.
     */
    public function __construct()
    {
        $this->result = null;
    }

    /**
     * 現在の Context から object 部分を読み込みます.
     *
     * @param Context $context
     */
    public function handle(Context $context)
    {
        $beginObject = new StructuralChar(array("{"));
        $beginObject->handle($context);

        $container = $this->getContainer($context);
        if ($context->current() === "}") {
            $endObject = new StructuralChar(array("}"));
            $endObject->handle($context);
            $this->result = $container->getResult();
            return;
        }

        while (true) {
            if ($context->current() === "}") {
                throw $context->createException("Closing bracket after comma is not permitted");
            }
            $member = new Member();
            $member->handle($context);
            $container->setMember($member);

            $struct = new StructuralChar(array(",", "}"));
            $struct->handle($context);
            if ($struct->getResult() === "}") {
                $this->result = $container->getResult();
                break;
            }
        }
    }

    /**
     * handle() の結果を配列または stdClass として返します.
     *
     * @return mixed OBJECT_AS_ARRAY オプションが ON の場合は配列, OFF の場合は stdClass オブジェクト
     */
    public function getResult()
    {
        return $this->result;
    }

    /**
     * 引数の Context に指定されているオプションに応じた ArrayContainer オブジェクトを返します.
     *
     * @param  Context $context
     * @return ObjectExpr_Container
     */
    private function getContainer(Context $context)
    {
        $asArray = $context->getOption(JsonCodec::OBJECT_AS_ARRAY);
        return $asArray ? new ObjectExpr_ArrayContainer() : new ObjectExpr_StdClassContainer();
    }
}

/**
 * decode 後の object の型 (配列または stdClass) を制御するためのインタフェースです
 *
 * @ignore
 */
interface ObjectExpr_Container
{
    /**
     * 解析結果を返します
     *
     * @return mixed 解析結果
     */
    public function getResult();

    /**
     * 指定された member をこの object に追加します.
     *
     * @param Member $member
     */
    public function setMember(Member $member);
}

/**
 * object を配列として表現する ObjectExpr_Container です.
 *
 * @ignore
 */
class ObjectExpr_ArrayContainer implements ObjectExpr_Container
{
    /**
     * 解析結果をあらわす配列です.
     *
     * @var array
     */
    private $result;

    /**
     * 新しいインスタンスを生成します.
     */
    public function __construct()
    {
        $this->result = array();
    }

    /**
     * 解析結果を配列として返します.
     *
     * @return array
     */
    public function getResult()
    {
        return $this->result;
    }

    /**
     * 指定された member をこの object に追加します.
     *
     * @param Member $member
     */
    public function setMember(Member $member)
    {
        $key = $member->getKey();
        $this->result[$key] = $member->getValue();
    }
}

/**
 * object を stdClass として表現する ObjectExpr_Container です.
 *
 * @ignore
 */
class ObjectExpr_StdClassContainer implements ObjectExpr_Container
{
    /**
     * 解析結果をあらわす stdClass です.
     *
     * @var stdClass
     */
    private $result;

    /**
     * 新しいインスタンスを生成します.
     */
    public function __construct()
    {
        $this->result = new stdClass();
    }

    /**
     * 解析結果を stdClass オブジェクトとして返します.
     *
     * @return stdClass
     */
    public function getResult()
    {
        return $this->result;
    }

    /**
     * 指定された member をこの object に追加します.
     *
     * @param Member $member
     */
    public function setMember(Member $member)
    {
        $key = $member->getKey();
        $this->result->$key = $member->getValue();
    }
}


<?php

namespace Feedify;

class Writer
{

    /* CONSTANTS
     *************************************************************************/
    const RSS_FORMAT = 'rss';
    const SITEMAP_FORMAT = 'sitemap';

    /* ATTRIBUTES
     *************************************************************************/
    public $title;
    public $description;
    public $feedURL;
    public $siteURL;
    public $items = array();

    protected $formatters = array();
    protected $attributeTypes = array(
        'title' => 'string',
        'url' => 'string',
        'date' => 'date',
        'intro' => 'string',
        'author' => 'string'
    );

    /* PUBLIC METHODS
     *************************************************************************/
    public function output($format=self::RSS_FORMAT) {
        $view = $this->getTwigView($format);
        $parameters = array();
        $parameters['feed'] = $this;
        $parameters['items'] = $this->getFormattedItems();
        echo $view->render($parameters);
    }

    public function addItems($items) {
        if (!is_array($items)) {
            $items = array($items);
        }
        $this->items = array_merge($this->items, $items);
    }

    public function addAttribute($attributeName) {
        $this->addAttributeFormatter($attributeName);
    }

    public function addAttributeMap($attributeName, $mapAttribute) {
        $this->addAttributeFormatter($attributeName, $mapAttribute);
    }

    public function addAttributeFormatter($attributeName, $formatter=NULL) {
        if (in_array($attributeName, array_keys($this->attributeTypes))) {
            if (!$formatter) {
                $formatter = $attributeName;
            }
            if (is_string($formatter)) {
                $formatter = $this->getDefaultFormatter($formatter);
            }
            $this->formatters[$attributeName] = $formatter;
        } else {
            throw new \Exception('Unknown feed attribute: '.$attributeName);
        }
    }

    /* PRIVATE METHODS
     *************************************************************************/
    protected function getFormattedItems() {
        $formattedItems = array();
        foreach ($this->items as $item) {
            $formattedItem = array();
            foreach ($this->formatters as $attributeName => $formatter) {
                $formattedItem[$attributeName] = $this->checkAttributeFormat($attributeName, $formatter($item));
            }
            $formattedItems[] = $formattedItem;
        }
        return $formattedItems;
    }

    protected function checkAttributeFormat($attributeName, $attributeValue) {
        if ($this->attributeTypes[$attributeName] == 'date') {
            // Handle standard string date
            if (is_string($attributeValue)) {
                $attributeValue = strtotime($attributeValue);
            }
            // Handle timestamp
            if (is_int($attributeValue)) {
                $attributeValue = new \DateTime($attributeValue);
            }
            if (!is_a($attributeValue, 'DateTime')) {
                return NULL;
            }
        } else {
            if (!is_string($attributeValue)) {
                return NULL;
            }
        }
        return $attributeValue;
    }

    protected function getDefaultFormatter($attributeName) {
        return function ($object) use ($attributeName) {
            if (isset($object[$attributeName])) {
                return $object[$attributeName];
            }
            if (isset($object->$attributeName)) {
                return $object->$attributeName;
            }
        };
    }

    protected function getTwigView($format) {
        header('Content-Type: application/rss+xml; charset=utf-8');
        $filename = $format.'.twig';
        if (!is_file(__DIR__.'/'.$filename)) {
            throw new \Exception('Unknown feed format: '.$format);
        }
        $loader = new \Twig_Loader_Filesystem(__DIR__);
        $twig = new \Twig_Environment($loader);
        $twig = $this->addTwigFilters($twig);
        return $twig->loadTemplate($filename);
    }

    protected function addTwigFilters($twig) {
        $formatDateFilter = new \Twig_SimpleFilter('formatDate', function(\DateTime $date, $format) {
            return $date->format($format);
        });
        $twig->addFilter($formatDateFilter);
        return $twig;
    }

}


<?php
declare(strict_types=1);

/*
 * This file is part of the Stinger Entity Search package.
 *
 * (c) Oliver Kotte <oliver.kotte@stinger-soft.net>
 * (c) Florian Meyer <florian.meyer@stinger-soft.net>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace StingerSoft\EntitySearchBundle\Services\Mapping;

use StingerSoft\EntitySearchBundle\Model\SearchableEntity;
use Doctrine\Common\Persistence\ObjectManager;
use StingerSoft\EntitySearchBundle\Model\Document;
use Symfony\Component\PropertyAccess\PropertyAccess;
use StingerSoft\EntitySearchBundle\Services\SearchService;

/**
 * Handles the creation of documents out of entities
 */
class EntityToDocumentMapper implements EntityToDocumentMapperInterface {

	/**
	 *
	 * @var SearchService
	 */
	protected $searchService;

	/**
	 *
	 * @var array
	 */
	protected $mapping = array();

	/**
	 *
	 * @var string[string]
	 */
	protected $cachedMapping = array();

	/**
	 * Constructor
	 *
	 * @param SearchService $searchService
	 */
	public function __construct(SearchService $searchService, array $mapping = array()) {
		$this->searchService = $searchService;
		foreach($mapping as $key => $config) {
			if(!isset($config['mappings'])) {
				throw new \InvalidArgumentException($key . ' has no mapping defined!');
			}
			if(!isset($config['persistence'])) {
				throw new \InvalidArgumentException($key . ' has no persistence defined!');
			}
			if(!isset($config['persistence']['model'])) {
				throw new \InvalidArgumentException($key . ' has no model defined!');
			}
			$map = array();
			foreach($config['mappings'] as $fieldKey => $fieldConfig) {
				$map[$fieldKey] = isset($fieldConfig['propertyPath']) && $fieldConfig['propertyPath'] ? $fieldConfig['propertyPath'] : $fieldKey;
			}

			$this->mapping[$config['persistence']['model']] = $map;
		}
	}

	/**
	 *
	 * {@inheritDoc}
	 *
	 * @see \StingerSoft\EntitySearchBundle\Services\Mapping\EntityToDocumentMapperInterface::isIndexable()
	 */
	public function isIndexable(object $object) : bool {
		if($object instanceof SearchableEntity) {
			return true;
		}
		if(count($this->getMapping(get_class($object))) > 0) {
			return true;
		}
		return false;
	}

	/**
	 *
	 * {@inheritDoc}
	 *
	 * @see \StingerSoft\EntitySearchBundle\Services\Mapping\EntityToDocumentMapperInterface::isClassIndexable()
	 * @throws \ReflectionException
	 */
	public function isClassIndexable(string $clazz) : bool {
		$reflectionClass = new \ReflectionClass($clazz);
		if(array_key_exists(SearchableEntity::class, $reflectionClass->getInterfaces())) {
			return true;
		}
		if(count($this->getMapping($clazz)) > 0) {
			return true;
		}
		return false;
	}

	/**
	 * {@inheritDoc}
	 * @see \StingerSoft\EntitySearchBundle\Services\Mapping\EntityToDocumentMapperInterface::createDocument()
	 */
	public function createDocument(ObjectManager $manager, object $object) : ?Document {
		if(!$this->isIndexable($object))
			return null;
		$document = $this->searchService->createEmptyDocumentFromEntity($object);
		$index = $this->fillDocument($document, $object);
		if($index === false)
			return null;

		return $document;
	}

	/**
	 * Fills the given document based on the object
	 *
	 * @param Document $document
	 * @param object $object
	 * @return boolean
	 */
	protected function fillDocument(Document $document, object $object) : bool {
		if($object instanceof SearchableEntity) {
			return $object->indexEntity($document);
		}
		$mapping = $this->getMapping(\get_class($object));
		$accessor = PropertyAccess::createPropertyAccessor();
		foreach($mapping as $fieldName => $propertyPath) {
			$document->addField($fieldName, $accessor->getValue($object, $propertyPath));
		}
		return true;
	}

	/**
	 * Fetches the mapping for the given object including the mapping of superclasses
	 *
	 * @return string[string]
	 * @throws \ReflectionException
	 */
	protected function getMapping(string $clazz) : array {
		if(isset($this->cachedMapping[$clazz])) {
			return $this->cachedMapping[$clazz];
		}
		$ref = new \ReflectionClass($clazz);

		$mapping = array();

		foreach($this->mapping as $className => $config) {
			if($clazz === $className || $ref->isSubclassOf($className)) {
				$mapping = \array_merge($mapping, $config);
			}
		}

		$this->cachedMapping[$clazz] = $mapping;

		return $mapping;
	}
}


<?php
/**
 * Created by PhpStorm.
 * User: claudio
 * Date: 03-04-16
 * Time: 19:36
 */

namespace AscensoDigital\PerfilBundle\DataFixtures\ORM;

use AscensoDigital\PerfilBundle\Entity\Permiso;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager;

class LoadPermisoData extends Fixture
{

    /**
     * Load data fixtures with the passed EntityManager
     *
     * @param ObjectManager $manager
     */
    public function load(ObjectManager $manager)
    {
        $mnCrear=$manager->getRepository('ADPerfilBundle:Permiso')->findOneBy(['nombre' => 'ad_perfil-menu-new']);
        if(!$mnCrear) {
            $mnCrear = new Permiso();
            $mnCrear->setNombre('ad_perfil-menu-new')
                ->setDescripcion('Crear Menu de PerfilBundle');
            $manager->persist($mnCrear);
        }
        $this->addReference('per-menu-new',$mnCrear);

        $mnEdit=$manager->getRepository('ADPerfilBundle:Permiso')->findOneBy(['nombre' => 'ad_perfil-menu-edit']);
        if(!$mnEdit) {
            $mnEdit = new Permiso();
            $mnEdit->setNombre('ad_perfil-menu-edit')
                ->setDescripcion('Editar Menu de PerfilBundle');
            $manager->persist($mnEdit);
        }
        $this->addReference('per-menu-edit',$mnEdit);

        $perCrear=$manager->getRepository('ADPerfilBundle:Permiso')->findOneBy(['nombre' => 'ad_perfil-per-new']);
        if(!$perCrear) {
            $perCrear = new Permiso();
            $perCrear->setNombre('ad_perfil-per-new')
                ->setDescripcion('Crear Permiso de PerfilBundle');
            $manager->persist($perCrear);
        }
        $this->addReference('per-per-new',$perCrear);

        $perEdit=$manager->getRepository('ADPerfilBundle:Permiso')->findOneBy(['nombre' => 'ad_perfil-per-edit']);
        if(!$perEdit) {
            $perEdit = new Permiso();
            $perEdit->setNombre('ad_perfil-per-edit')
                ->setDescripcion('Editar Permiso de PerfilBundle');
            $manager->persist($perEdit);
        }
        $this->addReference('per-per-edit',$perEdit);

        $perList=$manager->getRepository('ADPerfilBundle:Permiso')->findOneBy(['nombre' => 'ad_perfil-per-list']);
        if(!$perList) {
            $perList = new Permiso();
            $perList->setNombre('ad_perfil-per-list')
                ->setDescripcion('Listar Asignación de Permisos de PerfilBundle');
            $manager->persist($perList);
        }
        $this->addReference('per-per-list',$perList);

        $repIndex=$manager->getRepository('ADPerfilBundle:Permiso')->findOneBy(['nombre' => 'ad_perfil-mn-reporte']);
        if(!$repIndex) {
            $repIndex = new Permiso();
            $repIndex->setNombre('ad_perfil-mn-reporte')
                ->setDescripcion('Listado de Reportes de PerfilBundle');
            $manager->persist($repIndex);
        }
        $this->addReference('per-rep-list',$repIndex);

        $repCrear=$manager->getRepository('ADPerfilBundle:Permiso')->findOneBy(['nombre' => 'ad_perfil-rep-new']);
        if(!$repCrear) {
            $repCrear = new Permiso();
            $repCrear->setNombre('ad_perfil-rep-new')
                ->setDescripcion('Crear Reporte de PerfilBundle');
            $manager->persist($repCrear);
        }
        $this->addReference('per-rep-new',$repCrear);

        $repEdit=$manager->getRepository('ADPerfilBundle:Permiso')->findOneBy(['nombre' => 'ad_perfil-rep-edit']);
        if(!$repEdit) {
            $repEdit = new Permiso();
            $repEdit->setNombre('ad_perfil-rep-edit')
                ->setDescripcion('Editar Reporte de PerfilBundle');
            $manager->persist($repEdit);
        }
        $this->addReference('per-rep-edit',$repEdit);

        $repLoad=$manager->getRepository('ADPerfilBundle:Permiso')->findOneBy(['nombre' => 'ad_perfil-rep-load-estatico']);
        if(!$repLoad) {
            $repLoad = new Permiso();
            $repLoad->setNombre('ad_perfil-rep-load-estatico')
                ->setDescripcion('Cargar archivo estatico a reporte de PerfilBundle');
            $manager->persist($repLoad);
        }
        $this->addReference('per-rep-load',$repLoad);

        $repDownloadNombre=$manager->getRepository('ADPerfilBundle:Permiso')->findOneBy(['nombre' => 'ad_perfil-rep-download-nombre']);
        if(!$repDownloadNombre) {
            $repDownloadNombre = new Permiso();
            $repDownloadNombre->setNombre('ad_perfil-rep-download-nombre')
                ->setDescripcion('Descargar reporte con nombre de PerfilBundle');
            $manager->persist($repDownloadNombre);
        }
        $this->addReference('per-rep-download-nombre',$repDownloadNombre);

        $confIndex=$manager->getRepository('ADPerfilBundle:Permiso')->findOneBy(['nombre' => 'ad_perfil-mn-configuracion']);
        if(!$confIndex) {
            $confIndex = new Permiso();
            $confIndex->setNombre('ad_perfil-mn-configuracion')
                ->setDescripcion('Menu Configuración');
            $manager->persist($confIndex);
        }
        $this->addReference('per-config-index',$confIndex);

        $mapIndex=$manager->getRepository('ADPerfilBundle:Permiso')->findOneBy(['nombre' => 'ad_perfil-mn-mapa-sitio']);
        if(!$mapIndex) {
            $mapIndex = new Permiso();
            $mapIndex->setNombre('ad_perfil-mn-mapa-sitio')
                ->setDescripcion('Menu Mapa del Sitio');
            $manager->persist($mapIndex);
        }
        $this->addReference('per-mapa-sitio-index',$mapIndex);
        $manager->flush();
    }
}


<?php

namespace Asoc\Dadatata\Filter\FFmpeg;

use Asoc\Dadatata\Filter\FilterInterface;
use Asoc\Dadatata\Model\ThingInterface;
use Asoc\Dadatata\Model\VideoInterface;
use Symfony\Component\Process\ProcessBuilder;

class Extract implements FilterInterface
{
    /**
     * @var string
     */
    private $bin;

    public function __construct($bin = '/usr/bin/ffmpeg')
    {
        $this->bin = $bin;
    }

    /**
     * @param ThingInterface $thing
     * @param                $sourcePath
     *
     * @return array Paths to generated files
     */
    public function process(ThingInterface $thing, $sourcePath, array $options = null)
    {
        $tmpPath = tempnam(sys_get_temp_dir(), 'Dadatata');

        $pb = new ProcessBuilder([$this->bin]);
        $pb->add('-y');
        $pb->add('-i')->add($sourcePath);
        $pb->add('-f')->add('mjpeg');
        $pb->add('-vf')->add('thumbnail');
        $pb->add('-frames:v')->add(1);
        $pb->add($tmpPath);

        $process = $pb->getProcess();
        $code    = $process->run();

        $x = $process->getOutput();
        $y = $process->getErrorOutput();

        return [$tmpPath];
    }

    /**
     * @param ThingInterface $thing
     *
     * @return boolean
     */
    public function canHandle(ThingInterface $thing)
    {
        return $thing instanceof VideoInterface;
    }
}


<?php
/**
 * WellCommerce Open-Source E-Commerce Platform
 *
 * This file is part of the WellCommerce package.
 *
 * (c) Adam Piotrowski <adam@wellcommerce.org>
 *
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed with this source code.
 */

namespace WellCommerce\Bundle\ProductStatusBundle\Configurator;

use WellCommerce\Bundle\LayoutBundle\Configurator\AbstractLayoutBoxConfigurator;
use WellCommerce\Component\Form\Elements\FormInterface;
use WellCommerce\Component\Form\FormBuilderInterface;

/**
 * Class ProductStatusBoxConfigurator
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
final class ProductStatusBoxConfigurator extends AbstractLayoutBoxConfigurator
{
    /**
     * {@inheritdoc}
     */
    public function addFormFields(FormBuilderInterface $builder, FormInterface $form, $defaults)
    {
        $fieldset = $this->getFieldset($builder, $form);

        $fieldset->addChild($builder->getElement('tip', [
            'tip' => $this->trans('layout_box.product_status.tip'),
        ]));

        $statuses   = $this->get('product_status.dataset.admin')->getResult('select');
        $statusKeys = array_keys($statuses);

        $fieldset->addChild($builder->getElement('select', [
            'name'        => 'status',
            'label'       => $this->trans('product.label.statuses'),
            'options'     => $this->get('product_status.dataset.admin')->getResult('select'),
            'transformer' => $builder->getRepositoryTransformer('collection', $this->get('product_status.repository')),
        ]))->setValue(current($statusKeys));
    }
}


<?php

namespace Spiffy\View\Twig;

use Spiffy\View;

class TwigRenderer implements View\ViewRenderer
{
    /**
     * @var TwigResolver
     */
    protected $resolver;

    /**
     * @var \Twig_Environment
     */
    protected $twig;

    /**
     * @param \Twig_Environment $twig
     * @param TwigResolver $resolver
     */
    public function __construct(\Twig_Environment $twig, TwigResolver $resolver)
    {
        $this->twig = $twig;
        $this->resolver = $resolver;
    }

    /**
     * {@inheritDoc}
     */
    public function getEngine()
    {
        return $this->twig;
    }

    /**
     * {@inheritDoc}
     */
    public function render($nameOrModel, array $variables = [])
    {
        if (!$nameOrModel instanceof View\ViewModel) {
            $model = new View\ViewModel();
            $model->setVariables($variables);
            $model->setTemplate($nameOrModel);

            $nameOrModel = $model;
        }

        return $this
            ->resolver
            ->resolve($nameOrModel)
            ->render($nameOrModel->getVariables());
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: christof
 * Date: 11.11.15
 * Time: 14:32.
 */
namespace MandarinMedien\MMMediaBundle\MediaType;

use MandarinMedien\MMMediaBundle\Entity\Media;
use MandarinMedien\MMMediaBundle\Model\MediaInterface;
use MandarinMedien\MMMediaBundle\Model\MediaTypeInterface;

abstract class BaseMediaType implements MediaTypeInterface
{
    const NAME = 'mm.media.type.base';

    protected $raw;
    protected $media;

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

    public function getName()
    {
        return static::NAME;
    }

    public function getReference()
    {
        return $this->raw;
    }

    public function getEntity()
    {
        if (!$this->media) {
            $this->media = (new Media())
                ->setMediaType($this)
                ->setMediaTypeReference($this->getReference())
                ->setMediaTypeMetadata($this->getMetaData())
                ->setName($this->getMediaName())
                ->setDescription($this->getMediaDescription());
        }

        return $this->media;
    }

    public function getMetaData()
    {
        return array();
    }

    protected function setRaw($raw)
    {
        $this->raw = $raw;

        return $this;
    }

    public function __toString()
    {
        return static::NAME;
    }

    /**
     * parse the raw data and returns an instance on match.
     *
     * @param $data
     *
     * @return MediaTypeInterface|null
     */
    public static function check($data)
    {
        return;
    }

    /**
     * @param MediaInterface $media
     * @param array|null     $options
     *
     * @return string
     */
    public function getPreview(MediaInterface $media, array $options = null)
    {
        $self_options = array('html' => array('class' => array(self::NAME)));

        if (is_array($options)) {
            $options = array_merge_recursive($options, $self_options);
        } else {
            $options = $self_options;
        }

        $name = $this->getMediaName();

        if (!$name) {
            $name = basename($media->getMediaTypeReference());
        }

        $html = 'getMediaTypeReference().'" target="_blank" class="'.implode(' ', $options['html']['class']).'" >'.$name.'';

        return $html;
    }

    /**
     * get the media name.
     *
     * @return string
     */
    public function getMediaName()
    {
        return '';
    }

    /**
     * get the media description.
     *
     * @return string
     */
    public function getMediaDescription()
    {
        return '';
    }
}


<?php

namespace Peyote;

/**
 * The LIMIT # clause builder.
 *
 * @package    Peyote
 * @author     Dave Widmer <dave@davewidmer.net>
 */
class Limit implements \Peyote\Builder, \Peyote\Mixin
{
	/**
	 * @var int  The limit number
	 */
	private $limit = null;

	/**
	 * @var int  The offset amount
	 */
	private $offset = 0;

	/**
	 * Sets the limit.
	 *
	 * @param int $num    The number to limit the queries to
	 * @param int $offset The offset of which row to start the results with
	 */
	public function setLimit($num, $offset = 0)
	{
		$this->limit = (int) $num;
		$this->offset = (int) $offset;
	}

	/**
	 * Compiles the query into raw SQL
	 *
	 * @return  string
	 */
	public function compile()
	{
		if ($this->limit === null)
		{
			return "";
		}

		if ($this->offset < 1)
		{
			return "LIMIT {$this->limit}";
		}

		return "LIMIT {$this->offset}, {$this->limit}";
	}

	/**
	 * Gets all of the methods that should be passed as "mixin" methods.
	 *
	 * @return array
	 */
	public function getMethods()
	{
		return array();
	}

}


<?php
/*
 * Copyright (c) 2014 @trashtoy
 * https://github.com/trashtoy/
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
 * Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
/**
 * PHP class file.
 * @auhtor trashtoy
 * @since  2.0.0
 */
namespace Peach\Markup;

/**
 * 開始タグの名前をもとに, 改行するかどうかを判定する BreakControl です.
 */
class NameBreakControl extends BreakControlWrapper
{
    /**
     * 常に改行する要素名の一覧
     * @var array
     */
    private $breakNames;

    /**
     * 常に改行しない要素名の一覧
     * @var array
     */
    private $noBreakNames;

    /**
     * 指定された要素の改行ルールを強制する NameBreakControl インスタンスを生成します。
     *
     * @param array $breakNames   強制的に改行する要素名
     * @param array $noBreakNames 強制的に改行しない要素名
     * @param BreakControl $original オリジナルの BreakControl
     */
    public function __construct(array $breakNames, array $noBreakNames, BreakControl $original = null)
    {
        parent::__construct($original);
        $this->breakNames   = $breakNames;
        $this->noBreakNames = $noBreakNames;
    }

    /**
     * 強制的に改行する (または強制的に改行しない) 要素名のリストをもとに,
     * 指定された要素を改行するかどうかを決定します.
     * 改行リスト・非改行リストの両方に含まれている要素名の場合は,
     * 改行リストのほうが優先されます. (つまり常に改行されます)
     *
     * 改行リスト・非改行リストのいずれにも含まれない場合は,
     * オリジナルの BreakControl の結果を返します.
     *
     * @param  ContainerElement $node
     * @return bool
     */
    public function breaks(ContainerElement $node)
    {
        $name = $node->getName();
        if (in_array($name, $this->breakNames)) {
            return true;
        }
        if (in_array($name, $this->noBreakNames)) {
            return false;
        }

        return parent::breaks($node);
    }
}


<?php
/**
 * Phossa Project
 *
 * PHP version 5.4
 *
 * @category  Library
 * @package   Phossa\Query
 * @author    Hong Zhang <phossa@126.com>
 * @copyright 2015 phossa.com
 * @license   http://mit-license.org/ MIT License
 * @link      http://www.phossa.com/
 */
/*# declare(strict_types=1); */

namespace Phossa\Query\Clause;

/**
 * PartitionTrait
 *
 * @package Phossa\Query
 * @author  Hong Zhang <phossa@126.com>
 * @see     PartitionInterface
 * @version 1.0.0
 * @since   1.0.0 added
 */
trait PartitionTrait
{
    /**
     * Partition
     *
     * @var    array
     * @access protected
     */
    protected $clause_partition = [];

    /**
     * {@inheritDoc}
     */
    public function partition($partitionName)
    {
        if (is_array($partitionName)) {
            $this->clause_partition = array_merge(
                $this->clause_partition, $partitionName
            );
        } else {
            $this->clause_partition[] = $partitionName;
        }
        return $this;
    }

    /**
     * Build PARTITION
     *
     * @return array
     * @access protected
     */
    protected function buildPartition()/*# : array */
    {
        $result = [];
        if (!empty($this->clause_partition)) {
            $result[] = 'PARTITION (' . join(', ', $this->clause_partition) . ')';
        }
        return $result;
    }
}


<?php
/**
 * Phossa Project
 *
 * PHP version 5.4
 *
 * @category  Library
 * @package   Phossa\Query
 * @author    Hong Zhang <phossa@126.com>
 * @copyright 2015 phossa.com
 * @license   http://mit-license.org/ MIT License
 * @link      http://www.phossa.com/
 */
/*# declare(strict_types=1); */

namespace Phossa\Query\Clause;

/**
 * ColDefinitionTrait
 *
 * @package Phossa\Query
 * @author  Hong Zhang <phossa@126.com>
 * @see     ColDefinitionInterface
 * @version 1.0.0
 * @since   1.0.0 added
 */
trait ColDefinitionTrait
{
    use ValueTrait;

    /**
     * column
     *
     * @var    array
     * @access protected
     */
    protected $col_defs = [];

    /**
     * {@inheritDoc}
     */
    public function addCol(
        /*# string */ $colName,
        /*# string */ $colType
    ) {
        $def = [
            'name' => $colName,
            'type' => $colType
        ];
        $this->col_defs[] = $def;
        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function notNull(/*# string */ $conflictClause = '')
    {
        $col = &$this->col_defs[count($this->col_defs) - 1];
        $col['notNull'] = $conflictClause;
        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function defaultValue($value, /*# bool */ $raw = false)
    {
        $col = &$this->col_defs[count($this->col_defs) - 1];
        $col['default'] = [$value, $raw];
        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function autoIncrement()
    {
        $col = &$this->col_defs[count($this->col_defs) - 1];
        $col['autoincrement'] = true;
        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function primary(/*# string */ $conflictClause = '')
    {
        $col = &$this->col_defs[count($this->col_defs) - 1];
        $col['primary'] = $conflictClause;
        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function unique(/*# string */ $conflictClause = '')
    {
        $col = &$this->col_defs[count($this->col_defs) - 1];
        $col['unique'] = $conflictClause;
        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function colConstraint(/*# string */ $string)
    {
        $col = &$this->col_defs[count($this->col_defs) - 1];
        if (!isset($col['constraint'])) {
            $col['constraint'] = [];
        }
        $con = &$col['constraint'];
        $con[] = $string;
        return $this;
    }

    /**
     * Build column definitions
     *
     * @return array
     * @access protected
     */
    protected function buildCol()/*# : array */
    {
        $result = [];

        foreach ($this->col_defs as $col) {
            $res = [];
            // name
            $res[] = $this->quote($col['name']);

            // type
            $res[] = $col['type'];

            // not null ?
            if (isset($col['notNull'])) {
                $res[] = 'NOT NULL' .
                    ($col['notNull'] ? (' '.$col['notNull']) : '');
            }

            // default ?
            if (isset($col['default'])) {
                $res[] = 'DEFAULT ' . ($col['default'][1] ? $col['default'][0] :
                    $this->processValue($col['default'][0]));
            }

            // auto
            if (isset($col['autoincrement'])) {
                $res[] = 'AUTO_INCREMENT';
            }

            // unique
            if (isset($col['unique'])) {
                $res[] = 'UNIQUE' .
                    ($col['unique'] ? (' ' . $col['unique']) : '');
            }

            // primary
            if (isset($col['primary'])) {
                $res[] = 'PRIMARY KEY' .
                    ($col['primary'] ? (' ' . $col['primary']) : '');
            }

            // other constraints
            if (isset($col['constraint'])) {
                $res[] = join(' ', $col['constraint']);
            }

            array_walk($res, function($m) { return trim($m); });
            $result[] = join(' ', $res);
        }
        return $result;
    }

    /* utilities from UtilityTrait */
    abstract protected function quote(/*# string */ $str)/*# : string */;
}


<?php
/*
 * Copyright (c) 2015 @trashtoy
 * https://github.com/trashtoy/
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
 * Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
/**
 * PHP class file.
 * @auhtor trashtoy
 * @since  2.1.0
 * @ignore
 */
namespace Peach\DF\JsonCodec;

/**
 * JSON の BNF ルール value をあらわす Expression です.
 * RFC 7159 で定義されている以下のフォーマットを解釈します.
 *
 *

 * value = false / null / true / object / array / number / string
 *

 *
 * @ignore
 */
class Value implements Expression
{
    /**
     * デコードした結果の値です.
     *
     * @var mixed
     */
    private $result;

    /**
     * 新しい Value インスタンスを構築します.
     */
    public function __construct()
    {
        $this->result = null;
    }

    /**
     * value の内容を解釈してその結果を $result に格納します.
     *
     *

     * value = false / null / true / object / array / number / string
     *

     *
     * @param  Context $context
     */
    public function handle(Context $context)
    {
        $current = $context->current();
        if ($current === "-" || Number::checkDigit($context)) {
            $number = new Number();
            $number->handle($context);
            $this->result = $number->getResult();
            return;
        }
        switch ($current) {
            case "f":
                $this->decodeLiteral($context, "false", false);
                break;
            case "n":
                $this->decodeLiteral($context, "null", null);
                break;
            case "t":
                $this->decodeLiteral($context, "true", true);
                break;
            case "[":
                $array  = new ArrayExpr();
                $array->handle($context);
                $this->result = $array->getResult();
                break;
            case "{":
                $object = new ObjectExpr();
                $object->handle($context);
                $this->result = $object->getResult();
                break;
            case '"':
                $string = new StringExpr();
                $string->handle($context);
                $this->result = $string->getResult();
                break;
            default:
                throw $context->createException("Invalid value format");
        }
    }

    /**
     * 解析結果を返します.
     *
     * @return mixed
     */
    public function getResult()
    {
        return $this->result;
    }

    /**
     * リテラル null, true, false をデコードします.
     *
     * @param Context $context
     * @param string  $literal
     * @param mixed   $value
     */
    private function decodeLiteral(Context $context, $literal, $value)
    {
        $count = strlen($literal);
        if ($context->getSequence($count) !== $literal) {
            $current = $context->current();
            throw $context->createException("Unexpected character found ('{$current}')");
        }
        $this->result = $value;
        $context->skip($count);
    }
}


<?php
/*
 * Copyright (c) 2015 @trashtoy
 * https://github.com/trashtoy/
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
 * Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
/**
 * PHP class file.
 * @auhtor trashtoy
 * @since  2.2.0
 */
namespace Peach\Http;

use Peach\Http\Header\Raw;
use Peach\Http\Header\Status;
use Peach\Util\Strings;

/**
 * 一般的な WEB アプリケーションで使用されることを想定した Endpoint です.
 *
 * このクラスは $_GET, $_POST, $_SERVER などの情報を基にして Request を構築します.
 * send() メソッドでは Response の内容を
 * {@link http://php.net/manual/function.header.php header()} および
 * {@link http://php.net/manual/function.echo.php echo()} を利用してクライアントに送信します.
 */
class DefaultEndpoint implements Endpoint
{
    /**
     * クライアントから受信した HTTP リクエストです.
     * createRequest() の返り値をキャッシュするために利用されます.
     *
     * @var Request
     */
    private $request;

    /**
     * 新しい DefaultEndpoint インスタンスを構築します.
     */
    public function __construct()
    {
    }

    /**
     * グローバル変数 $_GET, $_POST, $_SERVER などを基にして
     * Request オブジェクトを作成します.
     *
     * @return Request
     */
    private function createRequest()
    {
        $keys    = array_keys($_SERVER);
        $request = new Request();
        foreach ($keys as $key) {
            if (!Strings::startsWith($key, "HTTP_")) {
                continue;
            }
            $name  = str_replace("_", "-", substr($key, 5));
            $value = $_SERVER[$key];
            $request->setHeader(Util::parseHeader($name, $value));
        }

        $method  = strtolower($_SERVER["REQUEST_METHOD"]);
        $rawPath = $_SERVER["REQUEST_URI"];
        $scheme  = isset($_SERVER["HTTPS"]) ? "https" : "http";
        $request->setQuery($_GET);
        $request->setPost($_POST);
        $request->setHeader(new Raw(":path", $rawPath));
        $request->setHeader(new Raw(":scheme", $scheme));
        $request->setHeader(new Raw(":method", $method));
        $request->setPath($this->getRequestPath($rawPath));
        return $request;
    }

    /**
     * URL からクエリ部分を除いたパスを返します.
     * 無効なパスが指定された場合は代替値として "/" を返します.
     *
     * @param  string $rawPath
     * @return string クエリ部分を除いたパス文字列
     */
    private function getRequestPath($rawPath)
    {
        $path     = "([^?#]+)";
        $query    = "(\\?[^#]*)?";
        $fragment = "(\\#.*)?";
        $matched  = array();
        return (preg_match("/\\A{$path}{$query}{$fragment}\\z/", $rawPath, $matched)) ? $matched[1] : "/";
    }

    /**
     * 受信した HTTP リクエストを $_GET, $_POST, $_SERVER などのグローバル変数を参照して
     * Request オブジェクトに変換し, その結果を返します.
     *
     * @return Request
     */
    public function getRequest()
    {
        if ($this->request === null) {
            $this->request = $this->createRequest();
        }
        return $this->request;
    }

    /**
     * 指定された Response オブジェクトを header() や echo()
     * などを使ってクライアントに送信します.
     *
     * @param Response $response 送信対象の Response オブジェクト
     */
    public function send(Response $response)
    {
        $body = $response->getBody();
        if ($body instanceof Body) {
            $renderer = $body->getRenderer();
            $value    = $body->getValue();
            $result   = $renderer->render($value);
            $response->setHeader(new Raw("Content-Length", strlen($result)));
        } else {
            $result   = null;
        }

        foreach ($response->getHeaderList() as $header) {
            if ($header instanceof Status) {
                $code         = $header->getCode();
                $reasonPhrase = $header->getReasonPhrase();
                header("HTTP/1.1 {$code} {$reasonPhrase}");
                continue;
            }
            $name  = $header->getName();
            $value = $header->format();
            $this->printHeader($name, $value);
        }
        if (strlen($result)) {
            echo $result;
        }
    }

    /**
     * 指定されたヘッダー名およびヘッダー値の組み合わせを出力します.
     * もしもヘッダー値が配列の場合 (Set-Cookie など) は,
     * 同じヘッダー名による複数のヘッダー行を出力します.
     *
     * @param string       $name  ヘッダー名
     * @param string|array $value ヘッダー値
     */
    private function printHeader($name, $value)
    {
        if (is_array($value)) {
            foreach ($value as $item) {
                header("{$name}: {$item}", false);
            }
            return;
        }

        header("{$name}: {$value}");
    }
}


<?php

/**
 * @author      José Lorente <jose.lorente.martin@gmail.com>
 * @license     The MIT License (MIT)
 * @copyright   José Lorente
 * @version     1.0
 */

namespace jlorente\location\db;

use Yii;
use jlorente\location\exceptions\SaveException;
use jlorente\location\models\Coordinates;
use jlorente\location\db\LocationInterface;
use yii\db\ActiveRecord as BaseActiveRecord;

/**
 * This is the model class for table "jl_loc_location".
 *
 * @property integer $id
 * @property integer $country_id
 * @property integer $state_id
 * @property integer $region_id
 * @property integer $city_id
 * @property string $address
 * @property double $latitude
 * @property double $longitude
 *
 * @property City $city The city in which this location is located or null if not defined.
 * @property Country $county The country in which this zone is located or null if not defined.
 * @property Region $region The region in which this location is located or null if not defined.
 * @property State $state The state in which this zone is located or null if not defined.
 *
 * @author José Lorente <jose.lorente.martin@gmail.com>
 */
class Location extends BaseActiveRecord implements LocationInterface
{

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'jl_loc_location';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['country_id', 'region_id', 'city_id', 'state_id'], 'integer']
            , [['latitude', 'longitude'], 'number']
            , [['address', 'postal_code'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('jlorente/location', 'ID')
            , 'country_id' => Yii::t('jlorente/location', 'Country')
            , 'region_id' => Yii::t('jlorente/location', 'Region')
            , 'city_id' => Yii::t('jlorente/location', 'City')
            , 'state_id' => Yii::t('jlorente/location', 'State')
            , 'address' => Yii::t('jlorente/location', 'Address')
            , 'postal_code' => Yii::t('jlorente/location', 'Postal Code')
            , 'latitude' => Yii::t('jlorente/location', 'Latitude')
            , 'longitude' => Yii::t('jlorente/location', 'Longitude')
        ];
    }

    /**
     *
     * @return yii\db\ActiveQuery
     */
    public function getCity()
    {
        return $this->hasOne(City::className(), ['id' => 'city_id']);
    }

    /**
     *
     * @return yii\db\ActiveQuery
     */
    public function getCountry()
    {
        return $this->hasOne(Country::className(), ['id' => 'country_id']);
    }

    /**
     *
     * @return yii\db\ActiveQuery
     */
    public function getRegion()
    {
        return $this->hasOne(Region::className(), ['id' => 'region_id']);
    }

    /**
     *
     * @return yii\db\ActiveQuery
     */
    public function getState()
    {
        return $this->hasOne(State::className(), ['id' => 'state_id']);
    }

    /**
     *
     * @throws SaveException
     */
    public function updateCoordinates()
    {
        $address = '';
        if (empty($this->address) === false) {
            $matches = [];
            preg_match('/[^\d]+[\d]*/ui', $this->address, $matches);
            $address = $matches[0];
        }
        $locationString = $this->getLocationString();
        $coordinates = new Coordinates([
            'apiServerKey' => Yii::$app->params['googleApiServerKey']
        ]);
        if ($coordinates->populate($address . ' ' . $locationString, $this->country->code)) {
            $coordinates->populate($locationString, $this->country->code);
        }
        $this->attributes = $coordinates->attributes;
        if ($this->update(true, ['latitude', 'longitude']) === false) {
            throw new SaveException($this);
        }
    }

    /**
     * Gets the string identifying the fixed part of the location.
     *
     * @return string
     */
    public function getLocationString()
    {
        $normalized = '';
        if ($this->city !== null) {
            $normalized .= $this->city->name;
        }
        if ($this->region !== null) {
            $normalized .= ' ' . $this->region->name;
        }
        if ($this->postal_code !== null) {
            $normalized .= ' ' . $this->postal_code;
        }
        return $normalized;
    }

    /**
     * @inheritdoc
     */
    public function fields()
    {
        return array_merge(parent::fields(), [
            'country' => 'country'
            , 'region' => 'region'
            , 'city' => 'city'
            , 'state' => 'state'
        ]);
    }

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

    /**
     * @inheritdoc
     */
    public function getLocation()
    {
        return static::findOne($this->id);
    }

    /**
     * @inheritdoc
     */
    public function getCityPropertyName()
    {
        return 'city_id';
    }

    /**
     * @inheritdoc
     */
    public function getCountryPropertyName()
    {
        return 'country_id';
    }

    /**
     * @inheritdoc
     */
    public function getRegionPropertyName()
    {
        return 'region_id';
    }

    /**
     * @inheritdoc
     */
    public function getStatePropertyName()
    {
        return 'state_id';
    }

}


<?php
/*
 * Copyright (c) 2015 @trashtoy
 * https://github.com/trashtoy/
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
 * Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
/**
 * PHP class file.
 * @auhtor trashtoy
 * @since  2.1.0
 * @ignore
 */
namespace Peach\DF\JsonCodec;

/**
 * JSON の BNF ルール member をあらわす Expression です.
 * RFC 7159 で定義されている以下のフォーマットを解釈します.
 *
 * <pre>
 * member = string name-separator value
 * </pre>
 *
 * @ignore
 */
class Member implements Expression
{
    /**
     * handle() の結果得られた object のキーです.
     *
     * @var string
     */
    private $key;

    /**
     * handle() の結果得られた object の値です.
     *
     * @var mixed
     */
    private $value;

    /**
     * 新しい Member オブジェクトを構築します.
     */
    public function __construct()
    {
        $this->key   = null;
        $this->value = null;
    }

    /**
     * 現在の Context から member 部分を読み込みます.
     *
     * @param Context $context
     */
    public function handle(Context $context)
    {
        $string = new StringExpr();
        $string->handle($context);
        $this->key = $string->getResult();

        $nameSeparator = new StructuralChar(array(":"));
        $nameSeparator->handle($context);

        $value = new Value();
        $value->handle($context);
        $this->value = $value->getResult();
    }

    /**
     * handle() の結果得られた object のキーを返します.
     *
     * @return string
     */
    public function getKey()
    {
        return $this->key;
    }

    /**
     * handle() の結果得られた object の値を返します.
     *
     * @return mixed
     */
    public function getValue()
    {
        return $this->value;
    }
}