<?php

namespace kato\helpers;

use Yii;
use yii\web\BadRequestHttpException;

class KatoHtml extends \yii\base\Object
{
    /**
     * Generates link to page
     * Usage: \kato\helpers\KatoHtml::page('page-slug');
     * @param null $slug
     * @return string
     * @throws \yii\web\BadRequestHttpException
     */
    public static function page($slug = null)
    {
    	if (is_null($slug)) {
    		throw new BadRequestHttpException('Page slug not specified.');
    	}

    	return Yii::$app->urlManager->createAbsoluteUrl(['page/view', 'slug' => $slug]);
    }

    /**
     * Evaluates the value of the specified attribute for the given model.
     * The attribute name can be given in a dot syntax. For example, if the attribute
     * is "author.firstName", this method will return the value of "$model->author->firstName".
     * A default value (passed as the last parameter) will be returned if the attribute does
     * not exist or is broken in the middle (e.g. $model->author is null).
     * The model can be either an object or an array. If the latter, the attribute is treated
     * as a key of the array. For the example of "author.firstName", if would mean the array value
     * "$model['author']['firstName']".
     *
     * @param mixed $model the model. This can be either an object or an array.
     * @param mixed $attribute the attribute name (use dot to concatenate multiple attributes)
     * or anonymous function (PHP 5.3+). Remember that functions created by "create_function"
     * are not supported by this method. Also note that numeric value is meaningless when
     * first parameter is object typed.
     * @param mixed $defaultValue the default value to return when the attribute does not exist.
     * @return mixed the attribute value.
     */
    public static function value($model,$attribute,$defaultValue=null)
    {
        if(is_scalar($attribute) || $attribute===null)
            foreach(explode('.',$attribute) as $name)
            {
                if(is_object($model) && isset($model->$name))
                    $model=$model->$name;
                elseif(is_array($model) && isset($model[$name]))
                    $model=$model[$name];
                else
                    return $defaultValue;
            }
        else
            return call_user_func($attribute,$model);
        return $model;
    }

    /**
     * Generates the data suitable for list-based HTML elements.
     * The generated data can be used in {@link dropDownList}, {@link listBox}, {@link checkBoxList},
     * {@link radioButtonList}, and their active-versions (such as {@link activeDropDownList}).
     * @param $models
     * @param $valueField
     * @param $textField
     * @param string $groupField
     * @return array
     */
    public static function listData($models, $valueField, $textField, $groupField='')
    {
        $listData=array();

        if($groupField==='')
        {
            foreach($models as $model)
            {
                $value=self::value($model,$valueField);
                $text=self::value($model,$textField);
                $listData[$value]=$text;
            }
        }
        else
        {
            foreach($models as $model)
            {
                $group=self::value($model,$groupField);
                $value=self::value($model,$valueField);
                $text=self::value($model,$textField);
                if($group===null)
                    $listData[$value]=$text;
                else
                    $listData[$group][$value]=$text;
            }
        }
        return $listData;
    }
}


<?php

namespace bupy7\bbcode;

/**
 * @inheritdoc
 *
 * @author Belosludcev Vasilij http://github.com/bupy7
 * @version 1.1
 */
class Parser extends \JBBCode\Parser
{

    /**
     * Insert
 tag to new line.
     * @inheritdoc
     */
    public function parse($str)
    {
        $str = preg_replace('/(\r\n|\n\r|\n|\r)/', '
', $str);
        $str = preg_replace('/(
]*>[\s]*){2}/', '
', $str);

        return parent::parse($str);
    }

}


<?php

namespace kato;

use kato\modules\media\models\ContentMedia;
use kato\modules\media\models\Media;
use yii\helpers\Inflector;
use ReflectionClass;
use yii\helpers\Url;

class ActiveRecord extends \yii\db\ActiveRecord
{
    /**
     * Attached Content Media, by type
     * @return static
     */
    public function getContentMedia()
    {
        return $this->hasMany(ContentMedia::className(), ['content_id' => 'id'])
            ->where('content_type = :type', [':type' => $this->className()]);
    }

    /**
     * Relate Media
     * Usage: $model->media();
     * @param null $type
     * @return static
     */
    public function getMedia($type = null)
    {
        $media = $this->hasMany(Media::className(), ['id' => 'media_id']);
        if ($type !== null) {
            $media->where('media_type = :type', [':type' => $type]);
        }
        $media->via('contentMedia');

        return $media;
    }

    /**
     * Actions to be taken before saving the record.
     * @param bool $insert
     * @return bool whether the record can be saved
     */
    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            if (isset(\Yii::$app->user)) {
                $user_id = \Yii::$app->user->id;

                if ($this->isNewRecord) {
                    if ($this->hasAttribute('created_by'))
                        $this->created_by = $user_id;
                } else {
                    if ($this->hasAttribute('updated_by'))
                        $this->updated_by = $user_id;
                }
            }
            return true;
        }
        return false;
    }

    /**
     * This method is invoked before deleting a record.
     * The default implementation raises the [[EVENT_BEFORE_DELETE]] event.
     */
    public function beforeDelete()
    {
        if (parent::beforeDelete()) {
            if ($this->media) {
                foreach ($this->media as $media)  {
                    $media->delete();
                }
            }

            return true;
        }

        return false;
    }

    /**
     * Return basic select options for the record.
     * @param string $key
     * @param string $value
     * @param array $where
     * @return array
     */
    public static function getSelectOptions($key = 'id', $value = 'title', $where = [])
    {
        $parents = self::find();
        if (!empty($where)) {
            $parents->where($where);
        }
        return \yii\helpers\ArrayHelper::map($parents->all(), $key, $value);
    }

    /**
     * Return last row inserted
     * @return mixed
     */
    public function getLastRow()
    {
        return static::find()
            ->orderBy('id DESC')
            ->one();
    }

    /**
     * Returns lists of status available
     * @return array
     */
    public function listStatus()
    {
        $data = [];

        // create a reflection class to get constants
        $refl = new ReflectionClass(get_called_class());
        $constants = $refl->getConstants();

        // check for status constants (e.g., STATUS_ACTIVE)
        foreach ($constants as $constantName => $constantValue) {

            // add prettified name to dropdown
            if (strpos($constantName, "STATUS_") === 0) {
                $prettyName = str_replace("STATUS_", "", $constantName);
                $prettyName = Inflector::humanize(strtolower($prettyName));
                $data[$constantValue] = $prettyName;
            }
        }

        return $data;
    }

    /**
     * Returns status label
     * @return bool
     */
    public function getStatusLabel()
    {
        if ($status =$this->listStatus()) {
            return $status[$this->status];
        }
        return false;
    }

    /**
     * Returns permalink to model
     * @return string
     */
    public function getPermalink() {
        return Url::to(['view', 'id' => $this->id]);
    }

    /**
     * Returns types available
     * @param $type
     * @return array
     */
    public function listTypes($type)
    {
        $data = [];
        // create a reflection class to get constants
        $refl = new ReflectionClass(get_called_class());
        $constants = $refl->getConstants();

        foreach ($constants as $constantName => $constantValue) {

            // add prettified name to dropdown
            if (strpos($constantName, $type) === 0) {
                $prettyName = preg_replace('/' . $type . '/', "", $constantName, 1);
                $prettyName = Inflector::humanize(strtolower($prettyName));
                $data[$constantValue] = trim(ucwords($prettyName));
            }
        }

        return $data;
    }

    /**
     * Returns type label
     * @param $type
     * @param $constId
     * @return bool
     */
    public function getTypeLabel($type, $constId)
    {
        if (!is_null($type)) {
            $array = $this->listTypes($constId);
            if (isset($array[$type])) {
                return $array[$type];
            }
        }

        return false;
    }

    /**
     * return array of listing order
     * @return array
     */
    public function getListingOrderArray()
    {
        $count = static::find()
            ->count();

        $array = [];
        for ($i = 1; $i <= $count; $i++) {
            $array[$i] = $i;
        }

        return $array;
    }

    public function softDelete()
    {
        if ($this->hasAttribute('deleted')) {
            $this->deleted = 1;
            return $this->save(false);
        }

        return false;
    }
}


<?php

namespace kato\behaviors;

use yii\base\Behavior;
use yii\db\ActiveRecord;

class FindReplace extends Behavior
{
    /**
     * @var string attribute
     */
    public $attribute;

    /**
     * Can be strong or array
     * @var string|array findText
     */
    public $findText;

    /**
     * @var string replaceText
     */
    public $replaceText;

    /**
     * @inheritdoc
     */
    public function events()
    {
        return [
            ActiveRecord::EVENT_BEFORE_INSERT => 'findReplaceValue',
            ActiveRecord::EVENT_BEFORE_UPDATE => 'findReplaceValue',
        ];
    }

    /**
     * Find and replace text
     * Accepts find as string or array
     */
    public function findReplaceValue()
    {
        if (is_array($this->findText)) {
            //can be array
            $searchReplaceArray = [];
            foreach ($this->findText as $key => $value) {
                $searchReplaceArray[$value] = $this->replaceText;
            }
        } else {
            $searchReplaceArray = [
                $this->findText => $this->replaceText,
            ];
        }

        $this->owner->{$this->attribute} = str_replace(
            array_keys($searchReplaceArray),
            array_values($searchReplaceArray),
            $this->owner->{$this->attribute}
        );
    }
}


<?php

namespace Nauvalazhar\FacadePlease\Commands;

use Illuminate\Console\Command;
use Artisan;

class FacadePleaseDelete extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'facade:delete {name=null}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Laravel 5 Facade Generator';

    /**
     * Detect os for PATH SEPARATOR Issue
     *
     * @return string
     */

    protected $path;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();

        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
            $this->path = "\\";
        } else {
            $this->path = "/";
        }
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $name = $this->argument('name');
        if($name == 'null') {
            $name = $this->ask('Facade Name (e.g Email, Alert, etc)');
        }

        $path_provider = app_path('Providers' . $this->path . $name . 'FacadeServiceProvider.php');
        $path_facade = app_path(config('facadeplease.namespace') . $this->path);
        $this->info($path_provider);
        if(file_exists($path_provider)) {
            $this->info("\n".$name." is founded! The following files will be deleted:\n");
            $this->info('=> ' . $path_facade . $name . "ClassFacade.php");
            $this->info('=> ' . $path_facade . $name . "Facade.php");
            $this->info('=> ' . $path_provider);
            $confirm = $this->confirm("The command can't be undone and some functions may not work. \nDo you wish to contiune?");
            if($confirm == true) {
                $this->info('Deleting service provider ...');
                unlink($path_provider);
                $this->info('Deleting class facade ...');
                unlink($path_facade . $name . 'ClassFacade.php');
                $this->info('Deleting facade ...');
                unlink($path_facade . $name . 'Facade.php');

                // remote from config
                $this->info('Updating config file ...');
                $config_path = config_path('app.php');
                $app_data = file_get_contents($config_path);
                $remove_config = str_replace("'".$name."' => App" . $this->path . config('facadeplease.namespace') . $this->path . $name . "Facade::class,", "", $app_data);
                $remove_config = str_replace("App" . $this->path . 'Providers' . $this->path . $name . "FacadeServiceProvider::class,", "", $remove_config);
                file_put_contents($config_path, $remove_config);

                $this->info('Dumping the autoloader ...');
                exec('composer dump-autoload -o');
                $this->info('Facade deleted successfully!');
            }
        }else{
            $this->error("\n    Facade doesn't exist!\n");
        }
    }
}


<?php

/**
 * Contao Bootstrap
 *
 * @package    contao-bootstrap
 * @subpackage Tab
 * @author     David Molineus <david.molineus@netzmacht.de>
 * @copyright  2013-2018 netzmacht David Molineus. All rights reserved.
 * @license    LGPL-3.0 https://github.com/contao-bootstrap/tab
 * @filesource
 */

declare(strict_types=1);

namespace ContaoBootstrap\Tab\View\Tab;

use ContaoBootstrap\Tab\View\Tab\Item\Dropdown;
use ContaoBootstrap\Tab\View\Tab\Item\NavItem;

/**
 * Class NavigationIterator
 *
 * @package ContaoBootstrap\Tab\View\Tab
 */
final class NavigationIterator implements \Iterator
{
    /**
     * Tab navigation view.
     *
     * @var Navigation
     */
    private $navigation;

    /**
     * Current items of the tab navigation.
     *
     * @var NavItem[]
     */
    private $items;

    /**
     * Nav items.
     *
     * @var NavItem[]
     */
    private $dropdownItems;

    /**
     * Current nav item.
     *
     * @var NavItem|null
     */
    private $currentItem;

    /**
     * Current dropdown item.
     *
     * @var NavItem|null
     */
    private $currentDropdownItem;

    /**
     * NavigationIterator constructor.
     *
     * @param Navigation $navigation Tab navigation view.
     */
    public function __construct(Navigation $navigation)
    {
        $this->navigation = $navigation;
        $this->items      = $navigation->items();

        $this->rewind();
    }

    /**
     * Get the tab navigation.
     *
     * @return Navigation
     */
    public function navigation(): Navigation
    {
        return $this->navigation;
    }

    /**
     * Get the current item.
     *
     * @return NavItem|null
     */
    public function current(): ?NavItem
    {
        if ($this->currentItem instanceof Dropdown) {
            return $this->currentDropdownItem;
        }

        return $this->currentItem;
    }

    /**
     * Get the nex item.
     *
     * @return void
     */
    public function next(): void
    {
        if ($this->currentItem instanceof Dropdown) {
            $this->currentDropdownItem = next($this->dropdownItems) ?: null;

            if ($this->currentDropdownItem) {
                return;
            }
        }

        $this->currentItem = next($this->items) ?: null;

        if ($this->currentItem instanceof Dropdown) {
            $this->dropdownItems       = $this->currentItem->items();
            $this->currentDropdownItem = current($this->dropdownItems);
        } else {
            $this->dropdownItems       = [];
            $this->currentDropdownItem = null;
        }
    }

    /**
     * Get the key. Not supported.
     *
     * @return mixed|void
     *
     * @throws \RuntimeException Method is not supported.
     */
    public function key()
    {
        throw new \RuntimeException('Method key() not supported.');
    }

    /**
     * {@inheritdoc}
     */
    public function valid(): bool
    {
        if ($this->currentItem instanceof Dropdown) {
            return $this->currentDropdownItem instanceof NavItem;
        }

        return $this->currentItem instanceof NavItem;
    }

    /**
     * {@inheritdoc}
     */
    public function rewind(): void
    {
        $this->items               = $this->navigation->items();
        $this->currentItem         = current($this->items);
        $this->dropdownItems       = [];
        $this->currentDropdownItem = null;

        if ($this->currentItem instanceof Dropdown) {
            $this->dropdownItems       = $this->currentItem->items();
            $this->currentDropdownItem = current($this->dropdownItems);
        }
    }

    /**
     * Get the title of the current item.
     *
     * @return array
     */
    public function currentTitle(): array
    {
        if (!$this->currentItem) {
            return [];
        }

        $title = [$this->currentItem->title()];

        if ($this->currentItem instanceof Dropdown && $this->currentDropdownItem) {
            $title[] = $this->currentDropdownItem->title();
        }

        return $title;
    }
}


<?php

namespace kato\gii\generators\crud;

class Generator extends \yii\gii\generators\crud\Generator
{
    /**
     * Generates code for active field
     * @param  string $attribute
     * @return string
     */
    public function generateActiveField($attribute)
    {
        $tableSchema = $this->getTableSchema();
        if ($tableSchema === false || !isset($tableSchema->columns[$attribute])) {
            if (preg_match('/^(password|pass|passwd|passcode)$/i', $attribute)) {
                return "\$form->field(\$model, '$attribute')->passwordInput()";
            } else {
                return "\$form->field(\$model, '$attribute')";
            }
        }
        $column = $tableSchema->columns[$attribute];

        if ($column->name === 'tags') {
            return "\$form->field(\$model, '$attribute')->widget(Select2::classname(), [
            'language' => 'en',
            'options' => [
                'multiple' => true,
                'placeholder' => 'Select a tag ...'
            ],
            'pluginOptions' => [
                'allowClear' => true,
                'tags' => \$tag->listTags(\$model->className()),
            ],
        ])";
        } elseif ($column->type === 'timestamp') {
            return "\$form->field(\$model, '$attribute')->widget(DatePicker::classname(), [
                'options' => [
                    'placeholder' => 'Select date ...',
                ],
                'pluginOptions' => [
                    'format' => 'yyyy-mm-dd',
                    'todayHighlight' => true
                ],
            ])";
        } elseif ($column->phpType === 'boolean' || $column->name === 'active' || $column->name === 'deleted') {
            return "\$form->field(\$model, '$attribute')->widget(SwitchInput::classname(), [
                'pluginOptions' => [
                    'size' => 'small'
                ],
            ])";
        } elseif ($column->type === 'text') {
            return "\$form->field(\$model, '$attribute')->widget(ImperaviWidget::classname())";
        } else {
            if (preg_match('/^(password|pass|passwd|passcode)$/i', $column->name)) {
                $input = 'passwordInput';
            } else {
                $input = 'textInput';
            }
            if ($column->phpType !== 'string' || $column->size === null) {
                return "\$form->field(\$model, '$attribute')->$input()";
            } else {
                return "\$form->field(\$model, '$attribute')->$input(['maxlength' => $column->size])";
            }
        }
    }
}


<?php

declare(strict_types=1);

namespace Mapado\RestClientSdk\Mapping\Driver;

use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry;
use Doctrine\Common\Annotations\FileCacheReader;
use Doctrine\Common\Annotations\Reader;
use Mapado\RestClientSdk\Exception\MappingException;
use Mapado\RestClientSdk\Mapping\Annotations;
use Mapado\RestClientSdk\Mapping\Attribute;
use Mapado\RestClientSdk\Mapping\ClassMetadata;
use Mapado\RestClientSdk\Mapping\Relation;

/**
 * Class AnnotationDriver
 *
 * @author Julien Deniau <julien.deniau@mapado.com>
 */
class AnnotationDriver
{
    /**
     * @var string
     */
    private $cachePath;

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

    public function __construct(string $cachePath, bool $debug = false)
    {
        $this->cachePath = $cachePath;
        $this->debug = $debug;

        AnnotationRegistry::registerFile(
            __DIR__ . '/../Annotations/AllAnnotations.php'
        );
    }

    /**
     * @return array<ClassMetadata>
     *
     * @throws MappingException
     */
    public function loadDirectory(string $path): array
    {
        if (!is_dir($path)) {
            throw new MappingException($path . ' is not a valid directory');
        }

        $iterator = new \RegexIterator(
            new \RecursiveIteratorIterator(
                new \RecursiveDirectoryIterator(
                    $path,
                    \FilesystemIterator::SKIP_DOTS
                ),
                \RecursiveIteratorIterator::LEAVES_ONLY
            ),
            '/^.+\.php$/i',
            \RecursiveRegexIterator::GET_MATCH
        );

        $classes = [];
        $includedFiles = [];

        foreach ($iterator as $file) {
            $sourceFile = $file[0];
            if (!preg_match('(^phar:)i', $sourceFile)) {
                $sourceFile = realpath($sourceFile);
            }

            require_once $sourceFile;
            $includedFiles[] = $sourceFile;
        }

        $declared = get_declared_classes();
        foreach ($declared as $className) {
            $rc = new \ReflectionClass($className);
            $sourceFile = $rc->getFileName();
            if (in_array($sourceFile, $includedFiles)) {
                $classes[] = $className;
            }
        }

        $mapping = [];
        foreach ($classes as $class) {
            $metadata = $this->getClassMetadataForClassname($class);
            if ($metadata) {
                $mapping[] = $metadata;
            }
        }

        return $mapping;
    }

    /**
     * @return array<ClassMetadata>
     */
    public function loadClassname(string $classname): array
    {
        $metadata = $this->getClassMetadataForClassname($classname);

        return $metadata ? [$metadata] : [];
    }

    private function getClassMetadataForClassname(
        string $classname
    ): ?ClassMetadata {
        $reader = new FileCacheReader(
            new AnnotationReader(),
            $this->cachePath,
            $this->debug
        );

        $reflClass = new \ReflectionClass($classname);
        /** @var Annotations\Entity|null */
        $classAnnotation = $reader->getClassAnnotation(
            $reflClass,
            Annotations\Entity::class
        );

        if (!$classAnnotation) {
            return null;
        }

        $attributeList = [];
        $relationList = [];
        foreach ($reflClass->getProperties() as $property) {
            // manage attributes
            /** @var Annotations\Attribute|null */
            $propertyAnnotation = $this->getPropertyAnnotation(
                $reader,
                $property,
                'Attribute'
            );

            if ($propertyAnnotation) {
                $isId = $this->getPropertyAnnotation($reader, $property, 'Id');

                $attributeList[] = new Attribute(
                    $propertyAnnotation->name,
                    $property->getName(),
                    $propertyAnnotation->type,
                    (bool) $isId
                );
            } else {
                // manage relations
                /** @var Annotations\OneToMany|null */
                $relation = $this->getPropertyAnnotation(
                    $reader,
                    $property,
                    'OneToMany'
                );
                if (!$relation) {
                    /** @var Annotations\ManyToOne|null */
                    $relation = $this->getPropertyAnnotation(
                        $reader,
                        $property,
                        'ManyToOne'
                    );
                }

                if ($relation) {
                    $attributeList[] = new Attribute(
                        $relation->name,
                        $property->getName()
                    );

                    $targetEntity = $relation->targetEntity;
                    if (false === mb_strpos($targetEntity, '/')) {
                        $targetEntity =
                            mb_substr(
                                $classname,
                                0,
                                mb_strrpos($classname, '\\') + 1
                            ) .
                            $targetEntity;
                    }

                    $relationList[] = new Relation(
                        $relation->name,
                        $relation->type,
                        $targetEntity
                    );
                }
            }
        }

        $classMetadata = new ClassMetadata(
            $classAnnotation->key,
            $classname,
            $classAnnotation->repository
        );
        $classMetadata->setAttributeList($attributeList);
        $classMetadata->setRelationList($relationList);

        return $classMetadata;
    }

    private function getPropertyAnnotation(
        Reader $reader,
        \ReflectionProperty $property,
        string $classname
    ): ?object {
        return $reader->getPropertyAnnotation(
            $property,
            'Mapado\\RestClientSdk\\Mapping\\Annotations\\' . $classname
        );
    }
}


<?php

namespace BugBuster\BeUserOnlineBundle\EventListener;

use Contao\FrontendUser;
use Contao\BackendUser;
use Contao\User;

class UserLogoutListener
{
    /**
     * @var ContaoFrameworkInterface
     */
    private $framework;

    /**
     * Authentication hash
     * @var string
     */
    protected $strHash;

    public function __construct()
    {

    }

    /**
     * onSetUserLogin
     *
     * @return array                Add your custom modules to the list and return the array of back end modules.
     */
    public function onSetUserLogout(User $user)
    {
        $intUserId = $user->getData()['id']; // for user id, ugly, but I don't know what's better.

        $strHash = '';

        if ($user instanceof FrontendUser)
        {
            $strCookie = 'FE_USER_AUTH';
        }

        if ($user instanceof BackendUser)
        {
            $strCookie = 'BE_USER_AUTH';
        }
        // Generate the cookie hash
        $token = $_COOKIE["csrf_contao_csrf_token"];
        $strHash = sha1($token.$strCookie);

        // Remove the oldest session for the hash from the database
        \Database::getInstance()->prepare("DELETE FROM tl_beuseronline_session WHERE pid=? AND hash=? ORDER BY tstamp")
                                ->limit(1)
                                ->execute($intUserId, $strHash);

        //use app_dev.php to dump
        //dump from Symfony\Component\VarDumper\VarDumper
        //dump($arrModules['content']['modules']);

    }
}


<?php

/**
 * Contao Bootstrap
 *
 * @package    contao-bootstrap
 * @subpackage Tab
 * @author     David Molineus <david.molineus@netzmacht.de>
 * @copyright  2013-2018 netzmacht David Molineus. All rights reserved.
 * @license    LGPL-3.0 https://github.com/contao-bootstrap/tab
 * @filesource
 */

declare(strict_types=1);

namespace ContaoBootstrap\Tab\ContaoManager;

use Contao\CoreBundle\ContaoCoreBundle;
use Contao\ManagerPlugin\Bundle\BundlePluginInterface;
use Contao\ManagerPlugin\Bundle\Config\BundleConfig;
use Contao\ManagerPlugin\Bundle\Parser\ParserInterface;
use ContaoBootstrap\Core\ContaoBootstrapCoreBundle;
use ContaoBootstrap\Grid\ContaoBootstrapGridBundle;
use ContaoBootstrap\Tab\ContaoBootstrapTabBundle;

/**
 * Class Plugin
 */
final class Plugin implements BundlePluginInterface
{
    /**
     * {@inheritdoc}
     */
    public function getBundles(ParserInterface $parser)
    {
        $loadAfter = [ContaoCoreBundle::class, ContaoBootstrapCoreBundle::class];

        if (class_exists(ContaoBootstrapGridBundle::class)) {
            $loadAfter[] = ContaoBootstrapGridBundle::class;
        }

        return [
            BundleConfig::create(ContaoBootstrapTabBundle::class)
                ->setLoadAfter($loadAfter)
        ];
    }
}


<?php namespace Orchestra\Resources;

use Closure;
use Illuminate\Support\Str;
use InvalidArgumentException;

class Factory
{
    /**
     * Dispatcher instance.
     *
     * @var \Orchestra\Resources\Dispatcher
     */
    protected $dispatcher;

    /**
     * Response instance.
     *
     * @var \Orchestra\Resources\Response
     */
    protected $response;

    /**
     * The array of created "drivers".
     *
     * @var array
     */
    protected $drivers = [];

    /**
     * Construct a new Resources instance.
     *
     * @param  \Orchestra\Resources\Dispatcher  $dispatcher
     * @param  \Orchestra\Resources\Response  $response
     */
    public function __construct(Dispatcher $dispatcher, Response $response)
    {
        $this->dispatcher = $dispatcher;
        $this->response   = $response;
    }

    /**
     * Register a new resource.
     *
     * @param  string  $name
     * @param  mixed  $attributes
     *
     * @return \Orchestra\Resources\Router
     *
     * @throws \InvalidArgumentException
     */
    public function make($name, $attributes)
    {
        if (Str::contains($name, '.') || Str::contains($name, '/')) {
            throw new InvalidArgumentException("Invalid character in resource name [{$name}].");
        }

        return $this->drivers[$name] = new Router($name, $attributes);
    }

    /**
     * Get resource by given name, or create a new one.
     *
     * @param  string  $name
     * @param  mixed  $attributes
     *
     * @return \Orchestra\Resources\Router
     */
    public function of($name, $attributes = null)
    {
        if (! isset($this->drivers[$name])) {
            return $this->make($name, $attributes);
        }

        return $this->drivers[$name];
    }

    /**
     * Call a resource controller and action.
     *
     * @param  string  $name
     * @param  array  $parameters
     *
     * @return mixed
     */
    public function call($name, $parameters = [])
    {
        $child = null;

        // Available drivers does not include childs, we should split the
        // name into two (parent.child) where parent would be the name of
        // the resource.
        if (false !== strpos($name, '.')) {
            list($name, $child) = explode('.', $name, 2);
        }

        // When the resources is not available, or register we should
        // return false to indicate this status. This would allow the callee
        // to return 404 abort status.
        if (! isset($this->drivers[$name])) {
            return false;
        }

        return $this->dispatcher->call($this->drivers[$name], $child, $parameters);
    }

    /**
     * Handle response from resources.
     *
     * @param  mixed  $content
     * @param  \Closure  $callback
     *
     * @return mixed
     */
    public function response($content, Closure $callback = null)
    {
        return $this->response->call($content, $callback);
    }

    /**
     * Get all registered resources.
     *
     * @return array
     */
    public function all()
    {
        return $this->drivers;
    }
}


<?php
/**
 * @author    Matthieu Vion
 * @copyright 2018 Magentix
 * @license   https://opensource.org/licenses/MIT MIT License
 * @link      https://github.com/magentix/pickup-plugin
 */
declare(strict_types=1);

namespace Magentix\SyliusPickupPlugin\Form\Extension;

use Magentix\SyliusPickupPlugin\Shipping\Calculator\CalculatorInterface as PickupCalculatorInterface;
use Sylius\Bundle\CoreBundle\Form\Type\Checkout\ShipmentType;
use Sylius\Component\Core\Repository\ShippingMethodRepositoryInterface;
use Sylius\Component\Registry\ServiceRegistryInterface;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormError;
use Symfony\Component\Translation\TranslatorInterface;

final class CheckoutShipmentTypeExtension extends AbstractTypeExtension
{

    /**
     * @var ServiceRegistryInterface $calculatorRegistry
     */
    private $calculatorRegistry;

    /**
     * @var ShippingMethodRepositoryInterface $shippingMethodRepository
     */
    private $shippingMethodRepository;

    /**
     * @var TranslatorInterface $translator
     */
    private $translator;

    /**
     * @param ServiceRegistryInterface $calculatorRegistry
     * @param ShippingMethodRepositoryInterface $shippingMethodRepository
     * @param TranslatorInterface $translator
     */
    public function __construct(
        ServiceRegistryInterface $calculatorRegistry,
        ShippingMethodRepositoryInterface $shippingMethodRepository,
        TranslatorInterface $translator
    ) {
        $this->calculatorRegistry = $calculatorRegistry;
        $this->shippingMethodRepository = $shippingMethodRepository;
        $this->translator = $translator;
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
                $form = $event->getForm();

                $form->add('pickup_id', TextType::class, [
                    'required' => false,
                    'label' => 'sylius.form.checkout.shipping_method.pickup_id',
                ]);
            })
            ->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
                $data = $event->getData();

                $method = $this->shippingMethodRepository->findOneBy(['code' => $data['method']]);
                if ($method) {
                    $calculator = $this->calculatorRegistry->get($method->getCalculator());

                    if ($calculator instanceof PickupCalculatorInterface) {
                        if (!isset($data['pickup_id'])) {
                            $event->getForm()->addError(
                                new FormError($this->translator->trans('pickup.form.shipment.error.pickup_id'))
                            );
                        }
                    }
                }
            });
    }

    /**
     * {@inheritdoc}
     */
    public function getExtendedType(): string
    {
        return ShipmentType::class;
    }
}


<?php namespace Orchestra\Resources;

use Illuminate\Support\Str;
use Illuminate\Http\Request;
use InvalidArgumentException;
use Orchestra\Resources\Routing\Route;
use Illuminate\Routing\Router as IlluminateRouter;
use Orchestra\Resources\Routing\ControllerDispatcher;
use Illuminate\Contracts\Container\Container as IlluminateContainer;

class Dispatcher
{
    /**
     * Application instance.
     *
     * @var \Illuminate\Contracts\Container\Container
     */
    protected $app;

    /**
     * Router instance.
     *
     * @var \Illuminate\Routing\Router
     */
    protected $router;

    /**
     * Request instance.
     *
     * @var \Illuminate\Http\Request
     */
    protected $request;

    /**
     * Construct a new Resources instance.
     *
     * @param  \Illuminate\Contracts\Container\Container  $app
     * @param  \Illuminate\Routing\Router  $router
     * @param  \Illuminate\Http\Request  $request
     */
    public function __construct(IlluminateContainer $app, IlluminateRouter $router, Request $request)
    {
        $this->app     = $app;
        $this->router  = $router;
        $this->request = $request;
    }

    /**
     * Create a new dispatch.
     *
     * @param  \Orchestra\Resources\Router  $driver
     * @param  string|null  $name
     * @param  array  $parameters
     *
     * @return mixed
     */
    public function call(Router $driver, $name = null, array $parameters = [])
    {
        $resolver = $this->resolveDispatchDependencies($driver, $name, $parameters);

        // This would cater request to valid resource but pointing to an
        // invalid child. We should show a 404 response to the user on this
        // case.
        if (! $resolver->isValid()) {
            return false;
        }

        return $this->dispatch($driver, $name, $resolver);
    }

    /**
     * Resolve dispatcher dependencies.
     *
     * @param  \Orchestra\Resources\Router  $driver
     * @param  string  $name
     * @param  array  $parameters
     *
     * @return \Orchestra\Resources\Resolver
     */
    public function resolveDispatchDependencies(Router $driver, $name, array $parameters)
    {
        $segments = $this->getNestedParameters($name, $parameters);
        $key      = implode('.', array_keys($segments));
        $uses     = $driver->get('uses');

        if (! is_null($name)) {
            if (isset($driver[$key]) && Str::startsWith($driver[$key], 'resource:')) {
                $uses = $driver[$key];
            } else {
                $uses = (isset($driver[$name]) ? $driver[$name] : null);
            }
        }

        return new Resolver($uses, $this->request->getMethod(), $parameters, $segments);
    }

    /**
     * Find nested parameters from route.
     *
     * @param  string  $name
     * @param  array  $parameters
     *
     * @return array
     */
    protected function getNestedParameters($name, array $parameters)
    {
        $reserved = ['create', 'show', 'index', 'delete', 'destroy', 'edit'];
        $nested   = [];

        if (($nestedCount = count($parameters)) > 0) {
            $nested = [$name => $parameters[0]];

            for ($index = 1; $index < $nestedCount; $index += 2) {
                $value = null;

                if (($index + 1) < $nestedCount) {
                    $value = $parameters[($index + 1)];
                }

                $key = $parameters[$index];

                ! in_array($key, $reserved) && $nested[$key] = $value;
            }
        }

        return $nested;
    }

    /**
     * Find route action and parameters content attributes from either
     * restful or resources routing.
     *
     * @param  \Orchestra\Resources\Resolver  $resolver
     *
     * @return array
     *
     * @throws \InvalidArgumentException
     */
    protected function findRoutableAttributes(Resolver $resolver)
    {
        $type = $resolver->getType();

        if (in_array($type, ['restful', 'resource'])) {
            $method = 'find'.Str::studly($type).'Routable';

            list($action, $parameters) = call_user_func([$this, $method], $resolver);
        } else {
            throw new InvalidArgumentException("Type [{$type}] not implemented.");
        }

        return [$action, $parameters];
    }

    /**
     * Resolve action from restful controller.
     *
     * @param  \Orchestra\Resources\Resolver  $resolver
     *
     * @return array
     */
    protected function findRestfulRoutable(Resolver $resolver)
    {
        $parameters = $resolver->getParameters();
        $verb       = $resolver->getVerb();

        $action = (count($parameters) > 0 ? array_shift($parameters) : 'index');
        $action = Str::camel("{$verb}_{$action}");

        return [$action, $parameters];
    }

    /**
     * Resolve action from resource controller.
     *
     * @param  \Orchestra\Resources\Resolver  $resolver
     *
     * @return array
     */
    protected function findResourceRoutable(Resolver $resolver)
    {
        $verb      = $resolver->getVerb();
        $swappable = [
            'post'   => 'store',
            'put'    => 'update',
            'patch'  => 'update',
            'delete' => 'destroy',
        ];

        if (! isset($swappable[$verb])) {
            $action = $this->getAlternativeResourceAction($resolver);
        } else {
            $action = $swappable[$verb];
        }

        $parameters = array_values($resolver->getSegments());

        return [$action, $parameters];
    }

    /**
     * Get action name.
     *
     * @param  \Orchestra\Resources\Resolver  $resolver
     *
     * @return string
     */
    protected function getAlternativeResourceAction(Resolver $resolver)
    {
        $parameters = $resolver->getParameters();
        $segments   = $resolver->getSegments();

        $last       = array_pop($parameters);
        $resources  = array_keys($segments);

        if (in_array($last, ['edit', 'create', 'delete'])) {
            // Handle all possible GET routing.
            return $last;
        } elseif (! in_array($last, $resources) && ! empty($segments)) {
            return 'show';
        }

        return 'index';
    }

    /**
     * Dispatch the resource.
     *
     * @param  \Orchestra\Resources\Router  $driver
     * @param  string  $name
     * @param  \Orchestra\Resources\Resolver  $resolver
     *
     * @return mixed
     */
    protected function dispatch(Router $driver, $name, Resolver $resolver)
    {
        // Next we need to the action and parameters before we can call
        // the destination controller, the resolver would determine both
        // restful and resource controller.
        list($action, $parameters) = $this->findRoutableAttributes($resolver);

        $route = new Route((array) $resolver->getVerb(), "{$driver->get('id')}/{$name}", [
            'uses' => $resolver->getController()."@{$action}",
        ]);

        $route->overrideParameters($parameters);

        // Resolve the controller from container.
        $dispatcher = new ControllerDispatcher($this->router, $this->app);

        return $dispatcher->dispatch($route, $this->request, $resolver->getController(), $action);
    }
}


<?php
/**
 * @author    Matthieu Vion
 * @copyright 2018 Magentix
 * @license   https://opensource.org/licenses/MIT MIT License
 * @link      https://github.com/magentix/pickup-plugin
 */
declare(strict_types=1);

namespace Magentix\SyliusPickupPlugin\Form\Extension;

use Magentix\SyliusPickupPlugin\Shipping\Calculator\CalculatorInterface as PickupCalculatorInterface;
use Sylius\Bundle\ShippingBundle\Form\Type\ShippingMethodChoiceType;
use Sylius\Component\Registry\ServiceRegistryInterface;
use Sylius\Component\Core\Model\ShippingMethod;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\OptionsResolver\OptionsResolver;

final class ShippingMethodChoiceTypeExtension extends AbstractTypeExtension
{

    /**
     * @var ServiceRegistryInterface $calculatorRegistry
     */
    private $calculatorRegistry;

    /**
     * @param ServiceRegistryInterface $calculatorRegistry
     */
    public function __construct(
        ServiceRegistryInterface $calculatorRegistry
    ) {
        $this->calculatorRegistry = $calculatorRegistry;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefault(
            'choice_attr',
            function ($choiceValue, $key, $value) {
                /** @var ShippingMethod $choiceValue */
                $calculatorName = $choiceValue->getCalculator();

                /** @var PickupCalculatorInterface $calculator */
                $calculator = $this->calculatorRegistry->get($calculatorName);

                $attr = [];
                if ($calculator instanceof PickupCalculatorInterface) {
                    $attr['class'] = 'pickup';
                }

                return $attr;
            }
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getExtendedType(): string
    {
        return ShippingMethodChoiceType::class;
    }
}


<?php
/**
 * @author    Matthieu Vion
 * @copyright 2018 Magentix
 * @license   https://opensource.org/licenses/MIT MIT License
 * @link      https://github.com/magentix/pickup-plugin
 */
declare(strict_types=1);

namespace Magentix\SyliusPickupPlugin\Controller;

use Magentix\SyliusPickupPlugin\Shipping\Calculator\CalculatorInterface as PickupCalculatorInterface;
use Sylius\Component\Core\Repository\OrderRepositoryInterface;
use Sylius\Component\Core\Repository\ShippingMethodRepositoryInterface;
use Sylius\Component\Core\Model\ShippingMethod;
use Sylius\Component\Order\Model\OrderInterface;
use Sylius\Component\Order\Context\CartContextInterface;
use Sylius\Component\Shipping\Calculator\CalculatorInterface;
use Sylius\Component\Registry\ServiceRegistryInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Sylius\Component\Addressing\Model\CountryInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Intl\Intl;

final class PickupController extends Controller
{

    /**
     * @var ServiceRegistryInterface $calculatorRegistry
     */
    private $calculatorRegistry;

    /**
     * @var RepositoryInterface
     */
    private $countryRepository;

    /**
     * @param ServiceRegistryInterface $calculatorRegistry
     * @param RepositoryInterface $countryRepository
     */
    public function __construct(
        ServiceRegistryInterface $calculatorRegistry,
        RepositoryInterface $countryRepository
    ) {
        $this->calculatorRegistry = $calculatorRegistry;
        $this->countryRepository  = $countryRepository;
    }

    /**
     * Display Pickup List
     *
     * @param Request $request
     * @param string $method
     * @return Response|string
     */
    public function listAction(Request $request, ?string $method): Response
    {
        $calculator = $this->getCalculator($method);

        $params = $request->request->all();

        $pickupTemplate  = $this->getDefaultTemplate();
        $pickupCurrentId = null;
        $pickupList      = [];
        $currentAddress  = null;

        /** @var PickupCalculatorInterface $calculator */
        if ($calculator instanceof PickupCalculatorInterface) {
            if (!empty($calculator->getPickupTemplate())) {
                $pickupTemplate = $calculator->getPickupTemplate();
            }

            $cart = $this->getCurrentCart();
            if (null !== $cart->getId()) {
                $cart    = $this->getOrderRepository()->findCartForSummary($cart->getId());
                $address = $cart->getShippingAddress();

                $shipment = $cart->getShipments()->current();
                $pickupCurrentId = $shipment->getPickupId();

                foreach ($params as $field => $value) {
                    $setter = 'set' . preg_replace('/_/', '', ucwords($field, '_'));
                    if (method_exists($address, $setter)) {
                        $address->$setter($value);
                    }
                }
                $currentAddress = $address;

                $pickupList = $calculator->getPickupList($address, $cart, $this->getMethod($method));
            }
        }

        $pickup = [
            'pickup' => [
                'current_id' => $pickupCurrentId,
                'list'       => $pickupList,
            ],
            'address'   => $currentAddress,
            'countries' => $this->getAvailableCountries(),
            'index'     => $request->get('index', 0),
            'code'      => $method,
        ];

        return $this->render($pickupTemplate, ['method' => $pickup]);
    }

    /**
     * Retrieve Shipping Method Calculator
     *
     * @param string $shippingMethod
     * @return CalculatorInterface|bool
     */
    protected function getCalculator(string $shippingMethod): CalculatorInterface
    {
        $method = $this->getMethod($shippingMethod);

        if ($method === null) {
            return false;
        }

        /** @var CalculatorInterface $calculator */
        $calculator = $this->calculatorRegistry->get($method->getCalculator());

        return $calculator;
    }

    /**
     * Retrieve Shipping Method
     *
     * @param string $shippingMethod
     * @return ShippingMethod|bool
     */
    protected function getMethod(?string $shippingMethod): ShippingMethod
    {
        /** @var ShippingMethod|null $method */
        $method = $this->getShippingMethodRepository()->findOneBy(['code' => $shippingMethod]);

        if ($method === null) {
            return false;
        }

        return $method;
    }

    /**
     * Retrieve Current Cart
     *
     * @return OrderInterface
     */
    protected function getCurrentCart(): OrderInterface
    {
        return $this->getContext()->getCart();
    }

    /**
     * Retrieve Cart Context
     *
     * @return CartContextInterface
     */
    protected function getContext(): CartContextInterface
    {
        /** @var CartContextInterface $context */
        $context = $this->get('sylius.context.cart');

        return $context;
    }

    /**
     * Retrieve Order Repository
     *
     * @return OrderRepositoryInterface
     */
    protected function getOrderRepository(): OrderRepositoryInterface
    {
        /** @var OrderRepositoryInterface $orderRepository */
        $orderRepository = $this->get('sylius.repository.order');

        return $orderRepository;
    }

    /**
     * Retrieve Shipping Mzthod Repository
     *
     * @return ShippingMethodRepositoryInterface
     */
    protected function getShippingMethodRepository(): ShippingMethodRepositoryInterface
    {
        /** @var ShippingMethodRepositoryInterface $shippingMethodRepository */
        $shippingMethodRepository = $this->get('sylius.repository.shipping_method');

        return $shippingMethodRepository;
    }

    /**
     * @return array|CountryInterface[]
     */
    private function getAvailableCountries(): array
    {
        $countries = Intl::getRegionBundle()->getCountryNames();

        /** @var CountryInterface[] $definedCountries */
        $definedCountries = $this->countryRepository->findAll();

        $availableCountries = [];

        foreach ($definedCountries as $country) {
            $availableCountries[$country->getCode()] = $countries[$country->getCode()];
        }

        return $availableCountries;
    }

    /**
     * Retrieve default template for pickup list
     *
     * @return string
     */
    protected function getDefaultTemplate(): string
    {
        return '@MagentixSyliusPickupPlugin/checkout/SelectShipping/pickup/list.html.twig';
    }
}


<?php namespace Orchestra\Resources;

use ArrayAccess;
use Illuminate\Support\Str;
use Illuminate\Support\Arr;
use InvalidArgumentException;

class Router implements ArrayAccess
{
    /**
     * Resource attributes.
     *
     * @var array
     */
    protected $attributes = [];

    /**
     * Reserved keywords.
     *
     * @var array
     */
    protected $reserved = ['index', 'visible'];

    /**
     * Construct a new Resouce container.
     *
     * @param  string  $name
     * @param  mixed  $attributes
     *
     * @throws \InvalidArgumentException
     */
    public function __construct($name, $attributes)
    {
        $attributes = $this->buildResourceSchema($name, $attributes);

        if (empty($attributes['name']) || empty($attributes['uses'])) {
            throw new InvalidArgumentException('Required `name` and `uses` are missing.');
        }

        $this->attributes = $attributes;
    }

    /**
     * Map a child resource attributes.
     *
     * @param  string  $name
     * @param  string  $uses
     *
     * @return $this
     *
     * @throws \InvalidArgumentException
     */
    public function route($name, $uses)
    {
        if (in_array($name, $this->reserved)) {
            throw new InvalidArgumentException("Unable to use reserved keyword [{$name}].");
        } elseif (Str::contains($name, '/')) {
            throw new InvalidArgumentException("Invalid character in resource name [{$name}].");
        }

        $this->attributes['routes'][$name] = $uses;

        return $this;
    }

    /**
     * Set visibility state based on parameter.
     *
     * @param  bool  $value
     *
     * @return $this
     *
     * @throws \InvalidArgumentException
     */
    public function visibility($value)
    {
        if (! is_bool($value)) {
            throw new InvalidArgumentException("Inpecting a boolean, [{$value}] given.");
        }

        $this->set('visible', $value);

        return $this;
    }

    /**
     * Set visibility state to show.
     *
     * @return $this
     */
    public function show()
    {
        return $this->visibility(true);
    }

    /**
     * Set visibility state to hidden.
     *
     * @return $this
     */
    public function hide()
    {
        return $this->visibility(false);
    }

    /**
     * Get attribute.
     *
     * @param  string  $key
     * @param  mixed  $default
     *
     * @return mixed
     */
    public function get($key, $default = null)
    {
        return Arr::get($this->attributes, $key, $default);
    }

    /**
     * Set attribute.
     *
     * @param  string  $key
     * @param  mixed  $value
     *
     * @return void
     */
    public function set($key, $value)
    {
        Arr::set($this->attributes, $key, $value);
    }

    /**
     * Forget attribute.
     *
     * @param  string  $key
     *
     * @return void
     */
    public function forget($key)
    {
        Arr::forget($this->attributes, $key);
    }

    /**
     * Build resource schema.
     *
     * @param  string  $name
     * @param  mixed  $attributes
     *
     * @return array
     */
    protected function buildResourceSchema($name, $attributes)
    {
        $schema = [
            'name'    => '',
            'uses'    => '',
            'routes'  => [],
            'visible' => true,
        ];

        if (! is_array($attributes)) {
            $uses       = $attributes;
            $attributes = [
                'name' => Str::title($name),
                'uses' => $uses,
            ];
        }

        $attributes['id'] = $name;

        return array_merge($schema, $attributes);
    }

    /**
     * Dynamically retrieve the value of an attributes.
     *
     * @param  string  $key
     *
     * @return mixed
     */
    public function __get($key)
    {
        return $this->get($key);
    }

    /**
     * Dynamically set the value of an attributes.
     *
     * @param  string  $key
     * @param  mixed  $value
     *
     * @return void
     */
    public function __set($key, $value)
    {
        $this->route($key, $value);
    }

    /**
     * Handle dynamic calls to the container to set attributes.
     *
     * @param  string  $method
     * @param  array  $parameters
     *
     * @return mixed
     *
     * @throws \InvalidArgumentException
     */
    public function __call($method, $parameters)
    {
        if (! empty($parameters)) {
            throw new InvalidArgumentException('Parameters is not available.');
        }

        return $this->attributes[$method] ?: null;
    }

    /**
     * Determine if a given offset exists.
     *
     * @param  string  $key
     *
     * @return bool
     */
    public function offsetExists($key)
    {
        return isset($this->attributes['routes'][$key]);
    }

    /**
     * Get the value at a given offset.
     *
     * @param  string  $key
     *
     * @return mixed
     */
    public function offsetGet($key)
    {
        return $this->attributes['routes'][$key];
    }

    /**
     * Set the value at a given offset.
     *
     * @param  string  $key
     * @param  mixed  $value
     *
     * @return void
     */
    public function offsetSet($key, $value)
    {
        $this->route($key, $value);
    }

    /**
     * Unset the value at a given offset.
     *
     * @param  string  $key
     *
     * @return void
     */
    public function offsetUnset($key)
    {
        unset($this->attributes['routes'][$key]);
    }
}


<?php
/**
 * @author    Matthieu Vion
 * @copyright 2018 Magentix
 * @license   https://opensource.org/licenses/MIT MIT License
 * @link      https://github.com/magentix/pickup-plugin
 */
declare(strict_types=1);

namespace Magentix\SyliusPickupPlugin\EventListener;

use Sylius\Bundle\ResourceBundle\Event\ResourceControllerEvent;
use Sylius\Component\Core\Model\Order;

final class OrderInitializeCompleteListener extends PickupListener
{

    /**
     * Update Shipping Address on cart summary
     *
     * @param ResourceControllerEvent $event
     * @return void
     */
    public function updateShippingAddress(ResourceControllerEvent $event): void
    {
        /** @var Order $order */
        $order = $event->getSubject();

        $pickup = $this->getPickupAddress($order);

        if (!empty($pickup)) {
            $shipping = clone $order->getShippingAddress();
            $shipping->setCompany($pickup['company']);
            $shipping->setStreet($pickup['street_1']);
            $shipping->setCity($pickup['city']);
            $shipping->setPostcode($pickup['postcode']);
            $shipping->setCountryCode($pickup['country']);

            $order->setShippingAddress($shipping);
        }
    }
}


<?php namespace Orchestra\Resources\Routing;

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class ControllerDispatcher extends \Illuminate\Routing\ControllerDispatcher
{
    /**
     * Call the given controller instance method.
     *
     * @param  \Orchestra\Routing\Controller    $instance
     * @param  \Illuminate\Routing\Route        $route
     * @param  string                           $method
     *
     * @return mixed
     */
    protected function call($instance, $route, $method)
    {
        $controller = get_class($instance);

        if (! method_exists($instance, $method)) {
            throw new NotFoundHttpException("Unable to call [{$controller}@{$method}].");
        }

        return parent::call($instance, $route, $method);
    }
}


<?php namespace Orchestra\Resources;

use Closure;
use Illuminate\Support\Str;
use Orchestra\Facile\Facile;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Response as IlluminateResponse;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class Response
{
    /**
     * Handle response from resources.
     *
     * @param  mixed  $content
     * @param  \Closure|null  $callback
     *
     * @return mixed
     */
    public function call($content, Closure $callback = null)
    {
        if ($content instanceof RedirectResponse || $content instanceof JsonResponse) {
            return $content;
        } elseif ($content instanceof Facile) {
            return $content->render();
        } elseif ($content instanceof IlluminateResponse) {
            return $this->handleIlluminateResponse($content, $callback);
        }

        return $this->handleResponseCallback($content, $callback);
    }

    /**
     * Handle Illuminate\Http\Response content.
     *
     * @param  \Illuminate\Http\Response  $content
     * @param  \Closure  $callback
     *
     * @return mixed
     *
     * @throws \Symfony\Component\HttpKernel\Exception\HttpException
     * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
     */
    protected function handleIlluminateResponse(IlluminateResponse $content, Closure $callback = null)
    {
        $code     = $content->getStatusCode();
        $response = $content->getContent();

        if ($this->isRenderableResponse($response)) {
            return $response->render();
        } elseif ($this->isNoneHtmlResponse($content)) {
            return $content;
        } elseif ($content->isSuccessful()) {
            return $this->handleResponseCallback($response, $callback);
        }

        return $this->abort($code);
    }

    /**
     * Handle response callback.
     *
     * @param  mixed  $content
     * @param  \Closure|null  $callback
     *
     * @return mixed
     */
    protected function handleResponseCallback($content, Closure $callback = null)
    {
        if ($callback instanceof Closure) {
            $content = call_user_func($callback, $content);
        }

        if (false === $content) {
            return $this->abort(404);
        } elseif (is_null($content)) {
            return new IlluminateResponse($content, 200);
        }

        return $content;
    }

    /**
     * Handle abort response.
     *
     * @param  int  $code
     * @param  string  $message
     * @param  array  $headers
     *
     * @return void
     *
     * @throws \Symfony\Component\HttpKernel\Exception\HttpException
     * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
     */
    protected function abort($code, $message = '', array $headers = [])
    {
        if ($code == 404) {
            throw new NotFoundHttpException($message);
        }

        throw new HttpException($code, $message, null, $headers);
    }

    /**
     * Is response renderable.
     *
     * @param  object|string  $response
     *
     * @return bool
     */
    protected function isRenderableResponse($response)
    {
        return $response instanceof Facile && $response->getFormat() !== 'html';
    }

    /**
     * Is response none html.
     *
     * @param  \Illuminate\Http\Response  $content
     *
     * @return bool
     */
    protected function isNoneHtmlResponse(IlluminateResponse $content)
    {
        $contentType = $content->headers->get('Content-Type');
        $isHtml      = Str::startsWith($contentType, 'text/html');

        return ! is_null($content) && ! $isHtml;
    }
}


<?php

namespace ostark\Yii2ArtisanBridge\base;

use ostark\Yii2ArtisanBridge\ErrorHandler;
use Yii;
use yii\base\ActionEvent;
use yii\console\Controller as BaseConsoleController;
use yii\helpers\Inflector;

/**
 * Copy Craft effortlessly
 */
class Commands extends BaseConsoleController
{

    public $actions = [];

    public $defaultAction;

    public $options = [];

    public $optionAliases = [];

    public $helpSummary;

    /**
     * Commands constructor.
     *
     * @param string           $id
     * @param \yii\base\Module $module
     * @param array            $config
     */
    public function __construct(string $id, \yii\base\Module $module, array $config = [])
    {
        parent::__construct($id, $module, $config);

        // EVENT_BEFORE_ACTION
        $this->on(self::EVENT_BEFORE_ACTION, function (ActionEvent $event) {

            // Forward options to Action
            foreach (array_values($this->optionAliases) as $name) {
                if (in_array($name, array_values($this->optionAliases))) {
                    if (isset($event->action->controller->options[$name])) {
                        $event->action->$name = $event->action->controller->options[$name];
                    }
                }
            }

            // Forward $interactive always
            $event->action->interactive = $event->action->controller->interactive;

        });
    }

    /**
     * Setup for actions and options
     *
     * @deprecated 1.2.0 No longer recommended, use Bridge::registerGroup() instead
     *
     * @param string $prefix
     * @param array  $actions
     * @param array  $options
     */
    public static function register(string $prefix, array $actions = [], array $options = [])
    {
        $handler = new ErrorHandler();
        $handler->register();

        Yii::$app->set('errorHandler', $handler);

        Yii::$app->controllerMap[$prefix] = [
            'class'         => get_called_class(),
            'actions'       => $actions,
            'optionAliases' => $options
        ];
    }

    /**
     * @deprecated 1.2.0 No longer recommended, use ActionGroup::setDefaultAction() instead
     *
     * @param string $prefix
     * @param string $name
     */
    public static function setDefaultAction(string $prefix, string $name)
    {
        Yii::$app->controllerMap[$prefix]['defaultAction'] = $name;
    }

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

    public function optionAliases()
    {
        $defaultOptions = ['h' => 'help', 'i' => 'interactive'];

        return array_merge($defaultOptions, $this->optionAliases);
    }

    /**
     * Get options from public Action properties
     */
    public function options($actionID)
    {
        $actionClass   = $this->actions()[$actionID] ?? null;
        $action        = new \ReflectionClass($actionClass);
        $actionOptions = [];

        foreach ($action->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
            if (in_array($property->getName(), array_values($this->optionAliases()))) {
                $actionOptions[] = $property->getName();
            }
        }

        return $actionOptions;

    }

    /**
     * Options getter
     *
     * @param string $name
     *
     * @return bool|mixed
     */
    public function __get($name)
    {
        return null;
    }

    /**
     * Options setter
     *
     * @param string $name
     * @param mixed  $value
     */
    public function __set($name, $value)
    {
        $this->options[$name] = $value;
    }

    public function getHelpSummary()
    {
        return $this->helpSummary;
    }

    /**
     * Returns the help information for the options for the action.
     *
     * The returned value should be an array. The keys are the option names, and the values are
     * the corresponding help information. Each value must be an array of the following structure:
     *
     * - type: string, the PHP type of this argument.
     * - default: string, the default value of this argument
     * - comment: string, the comment of this argument
     *
     * The default implementation will return the help information extracted from the doc-comment of
     * the properties corresponding to the action options.
     *
     * @param Action $action
     *
     * @return array the help information of the action options
     * @throws \ReflectionException
     */
    public function getActionOptionsHelp($action)
    {
        $optionNames = $this->options($action->id);
        if (empty($optionNames)) {
            return [];
        }

        $class   = new \ReflectionClass($action);
        $options = [];

        foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
            $name = $property->getName();
            if (!in_array($name, $optionNames, true)) {
                continue;
            }
            $defaultValue = $property->getValue($action);
            $tags         = $this->parseDocCommentTags($property);

            // Display camelCase options in kebab-case
            $name = Inflector::camel2id($name, '-', true);

            if (isset($tags['var']) || isset($tags['property'])) {
                $doc = isset($tags['var']) ? $tags['var'] : $tags['property'];
                if (is_array($doc)) {
                    $doc = reset($doc);
                }
                if (preg_match('/^(\S+)(.*)/s', $doc, $matches)) {
                    $type    = $matches[1];
                    $comment = $matches[2];
                } else {
                    $type    = null;
                    $comment = $doc;
                }
                $options[$name] = [
                    'type'    => $type,
                    'default' => $defaultValue,
                    'comment' => $comment,
                ];
            } else {
                $options[$name] = [
                    'type'    => null,
                    'default' => $defaultValue,
                    'comment' => '',
                ];
            }
        }

        return $options;
    }

}


<?php

namespace HtSession\Session;

use Zend\Session\Container as SessionContainer;
use Zend\Session\SessionManager;

class BootstrapSession
{
    /**
     * @var SessionManager
     */
    protected $sessionManager;

    /**
     * Constructor
     *
     * @param  SessionManager $sessionManager
     * @return void
     */
    public function __construct(SessionManager $sessionManager)
    {
        $this->sessionManager = $sessionManager;
    }

    /**
     * gets SessionManager instance
     *
     * @return SessionManager
     */
    public function getSessionManager()
    {
        return $this->sessionManager;
    }

    /**
     * Initializes sesssion
     *
     * @return void
     */
    public function bootstrap()
    {
        $this->getSessionManager()->start();
        $container = new SessionContainer('initialized');
        if (!isset($container->init)) {
             $this->getSessionManager()->regenerateId(true);
             $container->init = 1;
        }

    }
}


<?php

/**
 * @copyright   Copyright (c) 2015 ublaboo <ublaboo@paveljanda.com>
 * @author      Pavel Janda <me@paveljanda.com>
 * @package     Ublaboo
 */

namespace Ublaboo\Controls\Controls;

use Nette,
	Nette\Forms\Controls\BaseControl;

class NotTranslatableSelectBox extends Nette\Forms\Controls\SelectBox
{

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

	/**
	 * We have to repeat that method in our class due to parent::$options property accesibility
	 *  Otherwise we would be working with BaseControl::$options
	 * @param array   $items   [description]
	 * @param boolean $useKeys [description]
	 */
	public function setItems(array $items, $useKeys = TRUE)
	{
		if (!$useKeys) {
			$res = array();
			foreach ($items as $key => $value) {
				unset($items[$key]);
				if (is_array($value)) {
					foreach ($value as $val) {
						$res[$key][(string) $val] = $val;
					}
				} else {
					$res[(string) $value] = $value;
				}
			}
			$items = $res;
		}
		$this->options = $items;
		return parent::setItems(Nette\Utils\Arrays::flatten($items, TRUE));
	}

	/**
	 * Just remove translations from each option
	 * @return Nette\Forms\Helpers
	 */
	public function getControl()
	{
		$items = $this->getPrompt() === FALSE ? array() : array('' => $this->translate($this->getPrompt()));
		foreach ($this->options as $key => $value) {
			$items[is_array($value) ? $key : $key] = $value;
		}

		return Nette\Forms\Helpers::createSelectBox(
			$items,
			array(
				'selected?' => $this->value,
				'disabled:' => is_array($this->disabled) ? $this->disabled : NULL
			)
		)->addAttributes(BaseControl::getControl()->attrs);
	}

	/**
	 * Register NotTranslatableSelectBox
	 * @param  string $control_name string
	 * @return void
	 */
	public static function register($control_name = 'addNotTranslatableSelect') {
		Nette\Object::extensionMethod(
			'Nette\Forms\Container::' . $control_name,
			function ($form, $name, $label = NULL, array $items = NULL, $size = NULL) {
				$control = new self($label, $items);

				if ($size > 1) {
					$control->setAttribute('size', (int) $size);
				}

				return $form[$name] = $control;
			}
		);
	}

}


<?php

namespace WildWolf;

class Psr6MemoryCache implements \Psr\Cache\CacheItemPoolInterface
{
    private $cache = [];

    /**
     * @deprecated
     */
    public static function instance()
    {
        static $self = null;

        if (!$self) {
            $self = new self();
        }

        return $self;
    }

    public function __construct()
    {
    }

    private function createItem($key, $data, $expires) : \WildWolf\Cache\CacheItem
    {
        $item = new \WildWolf\Cache\CacheItem($key);
        $item->setIsHit(true);
        $item->set(is_object($data) ? clone $data : $data);
        $item->expiresAt($expires);
        return $item;
    }

    /**
     * Returns a Cache Item representing the specified key.
     *
     * This method must always return a CacheItemInterface object, even in case of
     * a cache miss. It MUST NOT return null.
     *
     * @param string $key
     *   The key for which to return the corresponding Cache Item.
     *
     * @throws \Psr\Cache\InvalidArgumentException
     *   If the $key string is not a legal value a \Psr\Cache\InvalidArgumentException
     *   MUST be thrown.
     *
     * @return \Psr\Cache\CacheItemInterface
     *   The corresponding Cache Item.
     */
    public function getItem($key)
    {
        \WildWolf\Cache\Validator::validateKey($key);

        if (isset($this->cache[$key])) {
            list($data, $expires) = $this->cache[$key];

            if (null === $expires || (new \DateTime()) < $expires) {
                return $this->createItem($key, $data, $expires);
            }

            unset($this->cache[$key]);
        }

        return new \WildWolf\Cache\CacheItem($key);
    }

    /**
     * Returns a traversable set of cache items.
     *
     * @param string[] $keys
     *   An indexed array of keys of items to retrieve.
     *
     * @throws \Psr\Cache\InvalidArgumentException
     *   If any of the keys in $keys are not a legal value a \Psr\Cache\InvalidArgumentException
     *   MUST be thrown.
     *
     * @return array|\Traversable
     *   A traversable collection of Cache Items keyed by the cache keys of
     *   each item. A Cache item will be returned for each key, even if that
     *   key is not found. However, if no keys are specified then an empty
     *   traversable MUST be returned instead.
     */
    public function getItems(array $keys = array())
    {
        $result = [];

        foreach ($keys as $key) {
            $result[$key] = $this->getItem($key);
        }

        return $result;
    }

    /**
     * Confirms if the cache contains specified cache item.
     *
     * Note: This method MAY avoid retrieving the cached value for performance reasons.
     * This could result in a race condition with CacheItemInterface::get(). To avoid
     * such situation use CacheItemInterface::isHit() instead.
     *
     * @param string $key
     *   The key for which to check existence.
     *
     * @throws \Psr\Cache\InvalidArgumentException
     *   If the $key string is not a legal value a \Psr\Cache\InvalidArgumentException
     *   MUST be thrown.
     *
     * @return bool
     *   True if item exists in the cache, false otherwise.
     */
    public function hasItem($key)
    {
        $item = $this->getItem($key);
        return $item->isHit();
    }

    /**
     * Deletes all items in the pool.
     *
     * @return bool
     *   True if the pool was successfully cleared. False if there was an error.
     */
    public function clear()
    {
        $this->cache = [];
        return true;
    }

    /**
     * Removes the item from the pool.
     *
     * @param string $key
     *   The key to delete.
     *
     * @throws InvalidArgumentException
     *   If the $key string is not a legal value a \Psr\Cache\InvalidArgumentException
     *   MUST be thrown.
     *
     * @return bool
     *   True if the item was successfully removed. False if there was an error.
     */
    public function deleteItem($key)
    {
        \WildWolf\Cache\Validator::validateKey($key);
        unset($this->cache[$key]);
        return true;
    }

    /**
     * Removes multiple items from the pool.
     *
     * @param string[] $keys
     *   An array of keys that should be removed from the pool.
     *
     * @throws \Psr\Cache\InvalidArgumentException
     *   If any of the keys in $keys are not a legal value a \Psr\Cache\InvalidArgumentException
     *   MUST be thrown.
     *
     * @return bool
     *   True if the items were successfully removed. False if there was an error.
     */
    public function deleteItems(array $keys)
    {
        foreach ($keys as $key) {
            $this->deleteItem($key);
        }

        return true;
    }

    /**
     * Persists a cache item immediately.
     *
     * @param \Psr\Cache\CacheItemInterface $item
     *   The cache item to save.
     *
     * @return bool
     *   True if the item was successfully persisted. False if there was an error.
     */
    public function save(\Psr\Cache\CacheItemInterface $item)
    {
        $key = $item->getKey();
        $val = $item->get();
        if (is_object($val)) {
            $val = clone $val;
        }

        if (!($item instanceof \WildWolf\Cache\CacheItem)) {
            $expires = null;
        } else {
            $expires = $item->expires();
        }

        $this->cache[$key] = [$val, $expires];
        return true;
    }

    /**
     * Sets a cache item to be persisted later.
     *
     * @param \Psr\Cache\CacheItemInterface $item
     *   The cache item to save.
     *
     * @return bool
     *   False if the item could not be queued or if a commit was attempted and failed. True otherwise.
     */
    public function saveDeferred(\Psr\Cache\CacheItemInterface $item)
    {
        return $this->save($item);
    }

    /**
     * Persists any deferred cache items.
     *
     * @return bool
     *   True if all not-yet-saved items were successfully saved or there were none. False otherwise.
     */
    public function commit()
    {
        return true;
    }
}


<?php

namespace ostark\Yii2ArtisanBridge;

use Symfony\Component\Console\Input\ArgvInput;
use yii\console\UnknownCommandException;

/**
 * Symfony console I/O
 *
 * @package ostark\Yii2ArtisanBridge
 */
class ErrorHandler extends \yii\console\ErrorHandler
{

    /**
     * @param \Exception $exception
     */
    protected function renderException($exception)
    {
        if ($exception instanceof UnknownCommandException) {
            parent::renderException($exception);
        }

        if (!YII_DEBUG) {
            return $this->render($exception->getMessage(), [get_class($exception)]);
        }

        // Debug mode
        $messages = [
            get_class($exception),
            "in " . dirname($exception->getFile()) . DIRECTORY_SEPARATOR .
            basename($exception->getFile()) . ": " . $exception->getLine()
        ];

        if ($exception instanceof \yii\db\Exception && !empty($exception->errorInfo)) {
            $messages[] = print_r($exception->errorInfo, true);
        }

        return $this->render($exception->getMessage(), $messages, $exception->getTraceAsString());

    }

    /**
     * @param string      $title
     * @param array       $messages
     * @param string|null $trace
     *
     * @return string|void
     */
    protected function render(string $title, array $messages, string $trace = null)
    {
        $output   = new OutputStyle(new ArgvInput(), new ConsoleOutput());
        $messages = array_merge(["<fg=white;bg=red;options=bold>$title</>"], $messages);

        $output->block($messages, 'ERROR', 'fg=white;bg=red', ' ', true, false);

        if ($trace) {
            $trace = str_replace(\Yii::getAlias('@root'), '', $trace);
            $trace = "<fg=red;options=bold>Stack trace:</>" . PHP_EOL . PHP_EOL . $trace;
            $output->block($trace, null, 'fg=white', '<fg=red>▓ </> ', true, false);
        }
    }
}


<?php

namespace VergilLai\NodeCategories;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;

/**
 * Artisan Migration Command
 * @package VergilLai\NodeCategories
 * @autohr Vergil <vergil@vip.163.com>
 */
class MigrationCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'node-categories:migration {--table=categories : Tablename} {--softDelete=false}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a categories migration';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $table = $this->option('table');
        $softDelete = $this->option('softDelete') == 'true';

        if ($this->tableExists($table)) {
            $this->error('table is exists!');
        } else {
            if ($this->createMigration($table, $softDelete)) {
                $this->info('Migration created successfully.');
                Artisan::call('migrate');
            } else {
                $this->error(
                    "Couldn't create migration.\n Check the write permissions".
                    " within the database/migrations directory."
                );
            }
        }

        $this->line('');
    }

    private function tableExists($table)
    {
        $dbname = DB::getDatabaseName();

        $field = 'Tables_in_' . $dbname;

        $tables = [];
        foreach(DB::select('SHOW TABLES') as $data) {
            $tables[] = $data->$field;
        }
        return in_array($table, $tables);
    }

    private function createMigration($table, $softDelete = false)
    {
        $this->laravel->view->addNamespace(__NAMESPACE__, __DIR__ . '/views');
        $migrationFile = base_path("/database/migrations")."/".date('Y_m_d_His')."_create_{$table}_table.php";

        $className = 'Create'.studly_case($table).'Table';

        $data = compact('table', 'className', 'softDelete');
        $output = $this->laravel->view->make(__NAMESPACE__ . '::migration')->with($data)->render();

        if (!is_file($migrationFile) && is_writable(dirname($migrationFile))) {
            file_put_contents($migrationFile, $output);
            return true;
        }
        return false;
    }

}


<?php

namespace ostark\Yii2ArtisanBridge\base;

/**
 * Trait BlockOutputTrait
 *
 * @property \ostark\Yii2ArtisanBridge\ConsoleOutput $input
 * @property \ostark\Yii2ArtisanBridge\OutputStyle  $output
 */
trait BlockOutputTrait
{

    /**
     * Formats a message as a block of text.
     *
     * @param string|array $messages The message to write in the block
     * @param string|null  $type     The block type (added in [] on first line)
     * @param string|null  $style    The style to apply to the whole block
     * @param string       $prefix   The prefix for the block
     * @param bool         $padding  Whether to add vertical padding
     * @param bool         $escape   Whether to escape the message
     */
    public function block($messages, $type = null, $style = null, $prefix = ' ', $padding = true, $escape = true)
    {
        $this->output->block($messages, $type, $style, $prefix, $padding, $escape);
    }

    /**
     * @param $message
     */
    public function title($message) {
        $this->output->title($message);
    }

    /**
     * @param $message
     */
    public function section($message)
    {
        $this->output->section($message);
    }

    /**
     * @param array $elements
     */
    public function listing(array $elements) {
        $this->output->listing($elements);
    }

    /**
     * Formats a command comment.
     *
     * @param string|array $message
     */
    public function commentBlock($message)
    {
        $this->block($message, null, null, '<fg=default;bg=default> // </>', false, false);
    }

    /**
     * {@inheritdoc}
     */
    public function successBlock($message)
    {
        $this->block($message, 'OK', 'fg=black;bg=green', ' ', true);
    }

    /**
     * {@inheritdoc}
     */
    public function errorBlock($message)
    {
        $this->block($message, 'ERROR', 'fg=white;bg=red', ' ', true);
    }

    /**
     * {@inheritdoc}
     */
    public function warningBlock($message)
    {
        $this->block($message, 'WARNING', 'fg=white;bg=red', ' ', true);
    }

    /**
     * {@inheritdoc}
     */
    public function noteBlock($message)
    {
        $this->block($message, 'NOTE', 'fg=yellow', ' ░ ');
    }

    /**
     * {@inheritdoc}
     */
    public function cautionBlock($message)
    {
        $this->block($message, 'CAUTION', 'fg=white;bg=red', '» ', true);
    }
}


<?php

namespace HtSession\Session\SaveHandler;

use Doctrine\DBAL\Connection;

/**
 * DB Table Gateway session save handler
 */
class DoctrineDbal extends \Zend\Session\SaveHandler\DbTableGateway
{
    /**
     * @var Connection
     */
    protected $connection;

    /**
     * Constructor
     *
     * @param  EntityManagerInterface          $connection
     * @param  DoctrineDbalOptions $options
     * @return void
     */
    public function __construct(Connection $connection, DoctrineDbalOptions $options)
    {
        $this->connection = $connection;
        $this->options      = $options;
    }

    /**
     * gets connection
     *
     * @return EntityManagerInterface
     */
    public function getConnection()
    {
        return $this->connection;
    }

    /**
     * gets DoctrineDbalOptions
     *
     * @return DoctrineDbalOptions
     */
    public function getOptions()
    {
        return $this->options;
    }

    protected function find($id)
    {
        $queryBuilder = $this->getConnection()->createQueryBuilder();

        return $queryBuilder
            ->select('*')
            ->from($this->getOptions()->getTableName(), 's')
            ->where(
                $queryBuilder->expr()->andX(
                    $queryBuilder->expr()->eq($this->getOptions()->getIdColumn(), '?'),
                    $queryBuilder->expr()->eq($this->getOptions()->getNameColumn(), '?')
                )
            )
            ->setParameter(0, $id)
            ->setParameter(1, $this->sessionName)
            ->execute()
            ->fetch(\PDO::FETCH_ASSOC);
    }

    /**
     * {@inheritDoc}
     */
    public function read($id)
    {
        if ($row = $this->find($id)) {
            if ($row[$this->getOptions()->getModifiedColumn()] + $row[$this->getOptions()->getLifetimeColumn()] > time()) {
                return $row[$this->getOptions()->getDataColumn()];
            }
            $this->destroy($id);
        }

        return '';
    }

    /**
     * {@inheritDoc}
     */
    public function write($id, $data)
    {
        $data = array(
            $this->getOptions()->getModifiedColumn() => time(),
            $this->getOptions()->getDataColumn()     => (string) $data,
        );

        if ($this->find($id)) {
            return $this->getConnection()->update(
                $this->getOptions()->getTableName(),
                $data,
                array(
                    $this->getOptions()->getIdColumn()   => $id,
                    $this->getOptions()->getNameColumn() => $this->sessionName,
                )
            );

        }

        $data[$this->getOptions()->getLifetimeColumn()] = $this->lifetime;
        $data[$this->getOptions()->getIdColumn()]       = $id;
        $data[$this->getOptions()->getNameColumn()]     = $this->sessionName;
        $this->getConnection()->insert($this->getOptions()->getTableName(), $data);

        return true;
    }

    /**
     * {@inheritDoc}
     */
    public function destroy($id)
    {
        return (bool) $this->getConnection()->delete($this->getOptions()->getTableName(), array(
            $this->getOptions()->getIdColumn()   => $id,
            $this->getOptions()->getNameColumn() => $this->sessionName,
        ));
    }

    /**
     * {@inheritDoc}
     */
    public function gc($maxlifetime)
    {
        $queryBuilder = $this->getConnection()->createQueryBuilder();
        $queryBuilder->delete($this->getOptions()->getTableName())
            ->where(sprintf(
                    '%s + %s < %s',
                    $this->getConnection()->quoteIdentifier($this->options->getModifiedColumn()),
                    $this->getConnection()->quoteIdentifier($this->options->getLifetimeColumn()),
                    time()
            ));

        return $queryBuilder->execute();
    }

}


<?php

namespace WildWolf;

class Psr16MemoryCache implements \Psr\SimpleCache\CacheInterface
{
    private $cache = [];

    /**
     * @deprecated
     */
    public static function instance()
    {
        static $self = null;

        if (!$self) {
            $self = new self();
        }

        return $self;
    }

    public function __construct()
    {
    }

    /**
     * Fetches a value from the cache.
     *
     * @param string $key     The unique key of this item in the cache.
     * @param mixed  $default Default value to return if the key does not exist.
     *
     * @return mixed The value of the item from the cache, or $default in case of cache miss.
     *
     * @throws \Psr\SimpleCache\InvalidArgumentException
     *   MUST be thrown if the $key string is not a legal value.
     */
    public function get($key, $default = null)
    {
        \WildWolf\Cache\Validator::validateKey($key);

        if (isset($this->cache[$key])) {
            list($data, $expires) = $this->cache[$key];

            if (null === $expires || (new \DateTime()) < $expires) {
                return $data;
            }

            unset($this->cache[$key]);
        }

        return $default;
    }

    /**
     * Persists data in the cache, uniquely referenced by a key with an optional expiration TTL time.
     *
     * @param string                $key   The key of the item to store.
     * @param mixed                 $value The value of the item to store, must be serializable.
     * @param null|int|\DateInterval $ttl  Optional. The TTL value of this item. If no value is sent and
     *                                     the driver supports TTL then the library may set a default value
     *                                     for it or let the driver take care of that.
     *
     * @return bool True on success and false on failure.
     *
     * @throws \Psr\SimpleCache\InvalidArgumentException
     *   MUST be thrown if the $key string is not a legal value.
     */
    public function set($key, $value, $ttl = null)
    {
        \WildWolf\Cache\Validator::validateKey($key);
        \WildWolf\Cache\Validator::validateTtl($ttl);

        if ($ttl instanceof \DateInterval) {
            $expires = new \DateTime();
            $expires->add($ttl);
        } elseif (is_numeric($ttl)) {
            $expires = new \DateTime('now +' . $ttl . ' seconds');
        } else {
            $expires = null;
        }

        if (is_object($value)) {
            $value = clone $value;
        }

        $this->cache[$key] = [$value, $expires];
        return true;
    }

    /**
     * Delete an item from the cache by its unique key.
     *
     * @param string $key The unique cache key of the item to delete.
     *
     * @return bool True if the item was successfully removed. False if there was an error.
     *
     * @throws \Psr\SimpleCache\InvalidArgumentException
     *   MUST be thrown if the $key string is not a legal value.
     */
    public function delete($key)
    {
        \WildWolf\Cache\Validator::validateKey($key);
        unset($this->cache[$key]);
        return true;
    }

    /**
     * Wipes clean the entire cache's keys.
     *
     * @return bool True on success and false on failure.
     */
    public function clear()
    {
        $this->cache = [];
        return true;
    }

    /**
     * Obtains multiple cache items by their unique keys.
     *
     * @param iterable $keys    A list of keys that can obtained in a single operation.
     * @param mixed    $default Default value to return for keys that do not exist.
     *
     * @return array|iterable   A list of key => value pairs. Cache keys that do not exist or are stale will have $default as value.
     *
     * @throws \Psr\SimpleCache\InvalidArgumentException
     *   MUST be thrown if $keys is neither an array nor a Traversable,
     *   or if any of the $keys are not a legal value.
     */
    public function getMultiple($keys, $default = null)
    {
        \WildWolf\Cache\Validator::validateIterable($keys);

        $result = [];
        foreach ($keys as $key) {
            $result[$key] = $this->get($key, $default);
        }

        return $result;
    }

    /**
     * Persists a set of key => value pairs in the cache, with an optional TTL.
     *
     * @param iterable              $values A list of key => value pairs for a multiple-set operation.
     * @param null|int|\DateInterval $ttl   Optional. The TTL value of this item. If no value is sent and
     *                                      the driver supports TTL then the library may set a default value
     *                                      for it or let the driver take care of that.
     *
     * @return bool True on success and false on failure.
     *
     * @throws \Psr\SimpleCache\InvalidArgumentException
     *   MUST be thrown if $values is neither an array nor a Traversable,
     *   or if any of the $values are not a legal value.
     */
    public function setMultiple($values, $ttl = null)
    {
        \WildWolf\Cache\Validator::validateIterable($values);
        \WildWolf\Cache\Validator::validateTtl($ttl);

        $result = true;
        foreach ($values as $key => $value) {
            if (is_int($key)) {
                $key = (string)$key;
            }

            $result = $this->set($key, $value, $ttl) && $result;
        }

        return $result;
    }

    /**
     * Deletes multiple cache items in a single operation.
     *
     * @param iterable $keys A list of string-based keys to be deleted.
     *
     * @return bool True if the items were successfully removed. False if there was an error.
     *
     * @throws \Psr\SimpleCache\InvalidArgumentException
     *   MUST be thrown if $keys is neither an array nor a Traversable,
     *   or if any of the $keys are not a legal value.
     */
    public function deleteMultiple($keys)
    {
        \WildWolf\Cache\Validator::validateIterable($keys);

        $result = true;
        foreach ($keys as $key) {
            $result = $this->delete($key) && $result;
        }

        return $result;
    }

    /**
     * Determines whether an item is present in the cache.
     *
     * NOTE: It is recommended that has() is only to be used for cache warming type purposes
     * and not to be used within your live applications operations for get/set, as this method
     * is subject to a race condition where your has() will return true and immediately after,
     * another script can remove it making the state of your app out of date.
     *
     * @param string $key The cache item key.
     *
     * @return bool
     *
     * @throws \Psr\SimpleCache\InvalidArgumentException
     *   MUST be thrown if the $key string is not a legal value.
     */
    public function has($key)
    {
        \WildWolf\Cache\Validator::validateKey($key);

        if (isset($this->cache[$key])) {
            list(, $expires) = $this->cache[$key];

            if (null === $expires || (new \DateTime()) < $expires) {
                return true;
            }

            unset($this->cache[$key]);
        }

        return false;
    }
}


<?php

/**
 * @copyright   Copyright (c) 2015 ublaboo <ublaboo@paveljanda.com>
 * @author      Pavel Janda <me@paveljanda.com>
 * @package     Ublaboo
 */

namespace Ublaboo\Controls\Controls;

use Nette,
	Nette\Forms\Controls\ChoiceControl;

class NotTranslatableRadioList extends Nette\Forms\Controls\RadioList
{

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

	/**
	 * @var mixed
	 */
	private $prompt = FALSE;

	/**
	 * Just remove translations from each option
	 * @return Nette\Forms\Helpers
	 */
	public function getControl()
	{
		$input = ChoiceControl::getControl();
		$items = $this->getItems();
		$ids = array();
		if ($this->generateId) {
			foreach ($items as $value => $label) {
				$ids[$value] = $input->id . '-' . $value;
			}
		}

		return $this->container->setHtml(
			Nette\Forms\Helpers::createInputList(
				$items,
				array_merge($input->attrs, array(
					'id:' => $ids,
					'checked?' => $this->value,
					'disabled:' => $this->disabled,
					'data-nette-rules:' => array(key($items) => $input->attrs['data-nette-rules']),
				)),
				array('for:' => $ids) + $this->itemLabel->attrs,
				$this->separator
			)
		);
	}

	/**
	 * Register NotTranslatableRadioList
	 * @param  string $control_name string
	 * @return void
	 */
	public static function register($control_name = 'addNotTranslatableRadioList') {
		Nette\Object::extensionMethod(
			'Nette\Forms\Container::' . $control_name,
			function ($form, $name, $label = NULL, array $items = NULL) {
				$control = new self($label, $items);

				return $form[$name] = $control;
			}
		);
	}

}