<?php

/*
 * This file is part of the Dektrium project.
 *
 * (c) Dektrium project <http://github.com/dektrium>
 *
 * For the full copyright and license information, please view the LICENSE.md
 * file that was distributed with this source code.
 */

namespace jarrus90\User\controllers;

use yii\base\Model;
use yii\base\InvalidConfigException;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\widgets\ActiveForm;
use jarrus90\User\models\Search;
use jarrus90\Core\Web\Controllers\AdminController as Controller;

/**
 * @author Dmitry Erofeev <dmeroff@gmail.com>
 */
abstract class ItemControllerAbstract extends Controller {

    /**
     * @param  string $name
     * @return \jarrus90\User\models\Role|\jarrus90\User\models\Permission
     */
    abstract protected function getItem($name);

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

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

    /**
     * @throws InvalidConfigException
     */
    public function init() {
        parent::init();
        if ($this->modelClass === null) {
            throw new InvalidConfigException('Model class should be set');
        }
        if ($this->type === null) {
            throw new InvalidConfigException('Auth item type should be set');
        }
    }

    /**
     * Lists all created items.
     * @return string
     */
    public function actionIndex() {
        $filterModel = new Search($this->type);
        return $this->render('index', [
                    'filterModel' => $filterModel,
                    'dataProvider' => $filterModel->search(\Yii::$app->request->get()),
        ]);
    }

    /**
     * Shows create form.
     * @return string|Response
     * @throws \yii\base\InvalidConfigException
     */
    public function actionCreate() {
        /** @var \jarrus90\User\models\Role|\jarrus90\User\models\Permission $model */
        $model = \Yii::createObject([
                    'class' => $this->modelClass,
                    'scenario' => 'create',
        ]);

        $this->performAjaxValidation($model);

        if ($model->load(\Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['index']);
        }

        return $this->render('create', [
                    'model' => $model,
        ]);
    }

    /**
     * Shows update form.
     * @param  string $name
     * @return string|Response
     * @throws NotFoundHttpException
     * @throws \yii\base\InvalidConfigException
     */
    public function actionUpdate($name) {
        /** @var \jarrus90\User\models\Role|\jarrus90\User\models\Permission $model */
        $item = $this->getItem($name);
        $model = \Yii::createObject([
                    'class' => $this->modelClass,
                    'scenario' => 'update',
                    'item' => $item,
        ]);

        $this->performAjaxValidation($model);

        if ($model->load(\Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['index']);
        }

        return $this->render('update', [
                    'model' => $model,
        ]);
    }

    /**
     * Deletes item.
     * @param  string $name
     * @return Response
     * @throws NotFoundHttpException
     */
    public function actionDelete($name) {
        $item = $this->getItem($name);
        \Yii::$app->authManager->remove($item);
        return $this->redirect(['index']);
    }

    /**
     * Performs ajax validation.
     * @param Model $model
     * @throws \yii\base\ExitException
     */
    protected function performAjaxValidation(Model $model) {
        if (\Yii::$app->request->isAjax && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            echo json_encode(ActiveForm::validate($model));
            \Yii::$app->end();
        }
    }

}


<?php
namespace Core\Toolbox\IO;

/**
 * Classfile.php
 *
 * @author Michael "Tekkla" Zorn <tekkla@tekkla.de>
 * @copyright 2016
 * @license MIT
 */
class Classfile
{

    use ReplaceDirectorySeperatorTrait;

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

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

    public function __construct(string $classname)
    {
        $this->setClassname($classname);
    }

    /**
     *
     * @param string $classname
     *            The classname as single name or with namespace
     */
    public function setClassname(string $classname)
    {
        $this->classname = $classname;
    }

    /**
     * Returns the classname
     *
     * @return string
     */
    public function getClassname(): string
    {
        return $this->classname;
    }

    /**
     * Sets the basedir to be prepended to classname.php
     *
     * @param string $basedir
     */
    public function setBasedir(string $basedir)
    {
        $this->basedir = $basedir;
    }

    /**
     * Returns the basedir
     *
     * @return string
     */
    public function getBasedir(): string
    {
        return $this->basedir;
    }

    /**
     * Checks for existing class file of a given classname
     *
     * Takes care of namespaces.
     *
     * @return boolean
     */
    public function exists(): bool
    {
        // convert namespace into path
        $class = str_replace('\\', '/', $this->classname);

        // append .php?
        if (strpos($class, '.php') === false) {
            $class .= '.php';
        }

        $class = $this->replaceDirectorySeperator($class);

        if (!empty($this->basedir)) {
            $class = $this->basedir .= DIRECTORY_SEPARATOR;
        }

        return file_exists($class);
    }
}


<?php namespace Ordercloud\Services;

use Ordercloud\Entities\Products\ProductTag;
use Ordercloud\Entities\Products\ProductTagCollection;
use Ordercloud\Entities\Products\ProductTagType;
use Ordercloud\Requests\Exceptions\ConflictRequestException;
use Ordercloud\Requests\Exceptions\NotFoundRequestException;
use Ordercloud\Requests\Exceptions\OrdercloudRequestException;
use Ordercloud\Requests\Products\CreateProductTagRequest;
use Ordercloud\Requests\Products\Criteria\TagCriteria;
use Ordercloud\Requests\Products\DeleteProductTagRequest;
use Ordercloud\Requests\Products\DisableProductTagRequest;
use Ordercloud\Requests\Products\EnableProductTagRequest;
use Ordercloud\Requests\Products\GetProductTagRequest;
use Ordercloud\Requests\Products\GetProductTagsRequest;
use Ordercloud\Requests\Products\GetProductTagTypesRequest;
use Ordercloud\Requests\Products\UpdateProductTagRequest;

class ProductTagService extends OrdercloudService
{
    /**
     * @param $tagId
     *
     * @return ProductTag
     *
     * @throws OrdercloudRequestException
     * @throws NotFoundRequestException
     */
    public function getTag($tagId)
    {
        return $this->request(new GetProductTagRequest($tagId));
    }

    /**
     * @param TagCriteria $criteria
     *
     * @return ProductTagCollection|ProductTag[]
     *
     * @throws OrdercloudRequestException
     * @throws NotFoundRequestException
     */
    public function getTags(TagCriteria $criteria = null)
    {
        $criteria = $criteria ?: TagCriteria::create();

        return $this->request(new GetProductTagsRequest($criteria));
    }

    /**
     * @return ProductTagType[]
     *
     * @throws OrdercloudRequestException
     */
    public function getTagTypes()
    {
        return $this->request(new GetProductTagTypesRequest());
    }

    /**
     * @param int         $organisationId
     * @param int         $tagTypeId
     * @param string      $name
     * @param string|null $shortDescription
     * @param string|null $description
     *
     * @return int The new product tag ID
     *
     * @throws OrdercloudRequestException
     * @throws ConflictRequestException
     * @throws NotFoundRequestException
     */
    public function createTag($organisationId, $tagTypeId, $name, $shortDescription = null, $description = null)
    {
        return $this->request(
            new CreateProductTagRequest($organisationId, $tagTypeId, $name, $shortDescription, $description)
        );
    }

    /**
     * @param int         $tagId
     * @param string      $name
     * @param string|null $shortDescription
     * @param string|null $description
     *
     * @throws OrdercloudRequestException
     * @throws ConflictRequestException
     * @throws NotFoundRequestException
     */
    public function updateTag($tagId, $name, $shortDescription = null, $description = null)
    {
        $this->request(new UpdateProductTagRequest($tagId, $name, $shortDescription, $description));
    }

    /**
     * @param int $tagId
     *
     * @throws OrdercloudRequestException
     * @throws NotFoundRequestException
     */
    public function enableTag($tagId)
    {
        $this->request(new EnableProductTagRequest($tagId));
    }

    /**
     * @param int $tagId
     *
     * @throws OrdercloudRequestException
     * @throws NotFoundRequestException
     */
    public function disableTag($tagId)
    {
        $this->request(new DisableProductTagRequest($tagId));
    }

    /**
     * @param int $tagId
     *
     * @throws OrdercloudRequestException
     * @throws NotFoundRequestException
     */
    public function deleteTag($tagId)
    {
        $this->request(new DeleteProductTagRequest($tagId));
    }
}


<?php
namespace wiggum\services\db;

use \PDO;
use \PDOException;

class DB {

	private $pdo;
	private $transactionError = false;

	/**
	 *
	 * @param array $config
	 */
	public function __construct($config) {
		$port = isset($config['port']) ? $config['port'] : '3306';
		$characterSet = isset($config['characterSet']) ? $config['characterSet'] : 'utf8';

		$this->connect($config['protocol'], $config['username'], $config['password'], $config['url'], $config['name'], $port, $characterSet);
	}

	/**
	 *
	 * @return Ambigous <NULL, \PDO>
	 */
	public function getPDO() {
		return $this->pdo;
	}

	/**
	 *
	 * @param string $table
	 * @return \wiggum\services\db\Builder
	 */
	public function table($table) {
		$query = new Builder($this, new Grammar());

		return $query->from($table);
	}

	/**
	 *
	 * @param string $protocol
	 * @param string $user
	 * @param string $password
	 * @param string $url
	 * @param string $name
	 * @param string $port [3306]
	 * @param string $characterSet ['utf8']
	 *
	 * @return /PDO
	 */
	public function connect($protocol, $user, $password, $url, $name, $port = 3306, $characterSet = 'utf8') {
		$pdo = null;
		try {
			$options = array(PDO::ATTR_PERSISTENT => true);
			$pdo = new PDO("{$protocol}:host={$url};port={$port};dbname={$name}", $user, $password, $options);
			$pdo->exec('SET NAMES '.$characterSet);
		} catch (PDOException $e) {
			$pdo = null;

			throw new \wiggum\exceptions\InternalErrorException('Database failed to connect');
		}
		$this->pdo = $pdo;
	}

	/**
	 *
	 * @return boolean
	 */
	public function beginTransaction() {
		try {
			$this->pdo->beginTransaction();
			return true;
		} catch (PDOException $e) {
			error_log($e->getMessage());
		}
		return false;
	}

	/**
	 *
	 * @return boolean
	 */
	public function doRollBack() {
		try {
			$this->pdo->rollBack();
			return true;
		} catch (PDOException $e) {
			error_log($e->getMessage());
		}
		return false;
	}

	/**
	 *
	 * @param boolean $selfRollBack [default=false]
	 * @return boolean
	 */
	public function doCommit($selfRollBack = false) {
		try {
			if ($selfRollBack) {
				if ($this->transactionError) {
					$this->doRollBack();
					return false;
				}
			}

			$this->pdo->commit();
			return true;
		} catch (PDOException $e) {
			error_log($e->getMessage());
		}
		return false;
	}

	/**
	 * Set corresponding fields in an object from result set.
	 *
	 * @param string $query
	 * @param array $values
	 * @param object $instance - the initialized object that the fields should be set in
	 * @param array $callback [default=array()]
	 * @return object
	 */
	public function fetchObject($query, array $values, $instance, $fetchMode = PDO::FETCH_INTO) {
		$obj = null;
		try {
			$statement = $this->pdo->prepare($query);
			$statement->setFetchMode($fetchMode, $instance);
			if ($statement->execute($values)) {
				$obj = $statement->fetch($fetchMode);
				if (!$obj) return null;
			} else {
				$errorInfo = $statement->errorInfo();
				error_log($errorInfo[2]);
			}
		} catch (PDOException $e) {
			error_log($e->getMessage());
		}
		return $obj;
	}

	/**
	 * Set corresponding fields in an object from result set.
	 * 	$instance is the initialized object that the fields should be set in
	 *
	 * @param string $query
	 * @param array $values
	 * @param object $instance - the initialized object that the fields should be set in
	 * @param array $callback [default=array()]
	 * @return array
	 */
	public function fetchObjects($query, array $values, $instance, $fetchMode = PDO::FETCH_INTO) {

		$objects = array();
		try {
			$statement = $this->pdo->prepare($query);
			$statement->setFetchMode($fetchMode, $instance);
			if ($statement->execute($values)) {
				while (($obj = $statement->fetch($fetchMode))) {
					if (isset($obj))
						$objects[] = clone $obj;
				}
			} else {
				$errorInfo = $statement->errorInfo();
				error_log($errorInfo[2]);
			}
		} catch (PDOException $e) {
			error_log($e->getMessage());
		}
		return $objects;

	}

	/**
	 *
	 * @param string $query
	 * @param array $values
	 * @param int $fetchMode [default=PDO::FETCH_ASSOC]
	 * @return array|object
	 */
	public function fetchRow($query, array $values, $fetchMode = PDO::FETCH_ASSOC) {
		$row = null;
		try {
			$statement = $this->pdo->prepare($query);
			if ($statement->execute($values)) {
				$row = $statement->fetch($fetchMode);
				if ($row === false) $row = null;
			} else {
				$errorInfo = $statement->errorInfo();
				error_log($errorInfo[2]);
			}
		} catch (PDOException $e) {
			error_log($e->getMessage());
		}
		return $row;
	}

	/**
	 *
	 * @param string $query
	 * @param array $values
	 * @param int $fetchMode [default=PDO::FETCH_ASSOC]
	 * @return array
	 */
	public function fetchRows($query, array $values, $fetchMode = PDO::FETCH_ASSOC) {
		$rows = array();
		try {
			$statement = $this->pdo->prepare($query);
			if ($statement->execute($values)) {
				$rows = $statement->fetchAll($fetchMode);
			} else {
				$errorInfo = $statement->errorInfo();
				error_log($errorInfo[2]);
			}
		} catch (PDOException $e) {
			error_log($e->getMessage());
		}
		return $rows;
	}

	/**
	 * Retrieve first column in results set
	 *
	 * @param string $query
	 * @param array $values
	 * @return string
	 */
	public function fetchColumn($query, array $values) {
		$col = null;
		try {
			$statement = $this->pdo->prepare($query);
			if ($statement->execute($values)) {
				$col = $statement->fetchColumn();
				if (!$col) return null;
			} else {
				$errorInfo = $statement->errorInfo();
				error_log($errorInfo[2]);
			}
		} catch (PDOException $e) {
			error_log($e->getMessage());
		}
		return $col;
	}

	/**
	 *
	 * @param string $query
	 * @param array $values
	 * @param boolean $lastInsId [default=true]
	 * @return int | boolean
	 */
	public function executeQuery($query, array $values, $lastInsId = true) {
		$result = false;
		try {
			$statement = $this->pdo->prepare($query);
			if ($statement->execute($values)) {
				if ($lastInsId) {
					$result = $this->pdo->lastInsertId();
				} else {
					$result = true;
				}
			} else {
				$this->transactionError = true;
				$errorInfo = $statement->errorInfo();
				error_log($errorInfo[2]);
			}
		} catch (PDOException $e) {
			$this->transactionError = true;
			error_log($e->getMessage());
		}
		return $result;
	}

}
?>


<?php

namespace Oxygen\Data\Repository\Doctrine;

use DateTime;
use Doctrine\ORM\QueryBuilder;

trait SoftDeletes {

    /**
     * Filters out trashed entities.
     *
     * @param QueryBuilder $query
     * @return QueryBuilder
     */

    protected function scopeExcludeTrashed(QueryBuilder $query) {
        $time = new DateTime();

        return $query
            ->andWhere('o.deletedAt is NULL')
            ->orWhere('o.deletedAt > :currentTimestamp')
            ->setParameter('currentTimestamp', $time->format('Y-m-d H:i:s'));
    }

    /**
     * Filters everything except trashed entities.
     *
     * @param QueryBuilder $query
     * @return QueryBuilder
     */

    protected function scopeOnlyTrashed(QueryBuilder $query) {
        $time = new DateTime();

        return $query
            ->andWhere('o.deletedAt is not NULL')
            ->andWhere(':currentTimestamp > o.deletedAt')
            ->setParameter('currentTimestamp', $time->format('Y-m-d H:i:s'));
    }

}


<?php

namespace Reaction;

use Psr\Http\Message\ServerRequestInterface;
use React\Http\Io\ServerRequest;
use React\Promise\PromiseInterface;
use Reaction\Promise\ExtendedPromiseInterface;
use Reaction\Web\Response;
use function Reaction\Promise\resolve;

/**
 * Class StaticApplicationConsole
 * @package Reaction
 */
class StaticApplicationConsole extends StaticApplicationAbstract
{
    /**
     * @inheritdoc
     */
    public function run()
    {
        $this->loop->futureTick([$this, 'runConsoleRequest']);
        parent::run();
    }

    /**
     * Emulates request resolving in console
     */
    public function runConsoleRequest() {
        $promise = resolve(true);
        //Delayed stop
        $loopStop = function() {
            $this->loop->addTimer(0.5, function() {
                $this->loop->stop();
            });
        };
        $promise->then(
            function() {
                return $this->processRequest($this->createRequest());
            }
        )->then(
            function($response = null) {
                if ($response instanceof Response) {
                    $body = $response->getBody();
                    if (is_object($body) && method_exists($body, '__toString')) {
                        $body = (string)$body;
                    }
                    return $body;
                }
                return $response;
            }
        )->done(function($result = null) use ($loopStop) {
            if (is_string($result)) {
                $this->logger->logRaw($result);
            }
            $loopStop();
        }, function($error) use ($loopStop) {
            \Reaction::error($error);
            $loopStop();
        });
    }

    /**
     * @return ServerRequest
     */
    protected function createRequest() {
        //\Reaction::warning($_SERVER);
        $serverParams = $_SERVER;
        $fileName = ltrim($serverParams['SCRIPT_NAME'], './');
        $serverParams['DOCUMENT_ROOT'] = getcwd();
        $serverParams['SCRIPT_NAME'] = $serverParams['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . $fileName;
        $serverParams['REQUEST_METHOD'] = 'GET';
        $request = new ServerRequest('GET', '/', [], null, '1.1', $serverParams);
        return $request;
    }
}


<?php
/**
 * Поле типа «entity»
 *
 * @version ${product.version}
 *
 * @copyright 2013, Михаил Красильников <m.krasilnikov@yandex.ru>
 * @license http://www.gnu.org/licenses/gpl.txt	GPL License 3
 * @author Михаил Красильников <m.krasilnikov@yandex.ru>
 *
 * Данная программа является свободным программным обеспечением. Вы
 * вправе распространять ее и/или модифицировать в соответствии с
 * условиями версии 3 либо (по вашему выбору) с условиями более поздней
 * версии Стандартной Общественной Лицензии GNU, опубликованной Free
 * Software Foundation.
 *
 * Мы распространяем эту программу в надежде на то, что она будет вам
 * полезной, однако НЕ ПРЕДОСТАВЛЯЕМ НА НЕЕ НИКАКИХ ГАРАНТИЙ, в том
 * числе ГАРАНТИИ ТОВАРНОГО СОСТОЯНИЯ ПРИ ПРОДАЖЕ и ПРИГОДНОСТИ ДЛЯ
 * ИСПОЛЬЗОВАНИЯ В КОНКРЕТНЫХ ЦЕЛЯХ. Для получения более подробной
 * информации ознакомьтесь со Стандартной Общественной Лицензией GNU.
 *
 * Вы должны были получить копию Стандартной Общественной Лицензии
 * GNU с этой программой. Если Вы ее не получили, смотрите документ на
 * <http://www.gnu.org/licenses/>
 *
 * @package ORM
 */

/**
 * Поле типа «entity»
 *
 * Транслируется в свойство, содержащее сущность указанного класса, связанную с текущим объектом.
 * Привязка осуществляется по идентификатору привязываемого объекта.
 *
 * Обязательные параметры:
 *
 * - «class» — полное имя класса объекта, привязанного к этому полю
 *
 * @package ORM
 * @since 3.00
 */
class ORM_Field_Entity extends ORM_Field_Abstract
{
    /**
     * Возвращает имя типа
     *
     * @return string
     *
     * @since 3.00
     */
    public function getTypeName()
    {
        return 'entity';
    }

    /**
     * Возвращает соответствующий тип PDO (PDO::PARAM_…) или null
     *
     * @return null|int
     *
     * @since 3.00
     */
    public function getPdoType()
    {
        return PDO::PARAM_INT;
    }

    /**
     * Преобразует значение ORM в значение PDO
     *
     * @param mixed $ormValue
     *
     * @throws InvalidArgumentException
     *
     * @return mixed
     *
     * @since 3.00
     */
    public function orm2pdo($ormValue)
    {
        if (is_null($ormValue))
        {
            return null;
        }
        $validClass = $this->getParam('class');
        if (!($ormValue instanceof $validClass))
        {
            throw new InvalidArgumentException('Argument 1 must be an instance of ' . $validClass);
        }
        if (!($ormValue instanceof ORM_Entity))
        {
            throw new InvalidArgumentException('Argument 1 must be an instance of ORM_Entity');
        }
        /* @var ORM_Entity $ormValue */
        return $ormValue->getPrimaryKey();
    }

    /**
     * Преобразует значение PDO в значение ORM
     *
     * @param mixed $pdoValue
     *
     * @return mixed
     *
     * @since 3.00
     */
    public function pdo2orm($pdoValue)
    {
        $table = $this->table->getDriver()->getManager()
            ->getTableByEntityClass($this->getParam('class'));
        if (is_null($table))
        {
            return null;
        }
        return $table->find($pdoValue);
    }

    /**
     * Возвращает список обязательных параметров
     *
     * @return string[]
     *
     * @since 3.00
     */
    protected function getRequiredParams()
    {
        return array('class');
    }

    /**
     * Возвращает выражение SQL для описания поля при создании таблицы
     *
     * @return string
     */
    public function getSqlFieldDefinition()
    {
        return $this->getName() . ' INTEGER UNSIGNED';
    }
}


<?php

namespace jamesvweston\Utilities;

class ArrayUtil
{

    /**
     * @param       $var
     * @param       null        $default
     * @return      null
     */
    public static function get (&$var, $default = null)
    {
        return isset($var) ? $var : $default;
    }

    /**
     * Get the value and if it's set, unset it
     * @param       array       $arr
     * @param       string      $key
     * @param       null        $default
     * @return      null
     */
    public static function getUnset (&$arr, $key, $default = null)
    {
        $value                  = isset($arr[$key]) ? $arr[$key] : $default;
        if (isset($arr[$key]))
            unset($arr[$key]);
        return $value;
    }

    /**
     * @param       $array
     * @param       $predicate
     * @return      bool
     */
    public static function all($array, $predicate)
    {
        return array_filter($array, $predicate) === $array;
    }

    /**
     * @param       $array
     * @return      bool
     */
    public static function isArrays($array)
    {
        return ArrayUtil::all($array, 'is_array');
    }

}


<?php

namespace ifcanduela\db;

use ifcanduela\db\traits\ConditionBuilder;

class InsertQuery extends Query
{
    /** @var array[] */
    protected $values;

    use ConditionBuilder;

    /**
     * InsertQuery constructor.
     *
     * @param string|NULL $table
     */
    public function __construct(string $table = null)
    {
        if ($table) {
            $this->into($table);
        }
    }

    /**
     * Specify the table to insert into.
     *
     * @param string $table
     * @return self
     */
    public function into(string $table)
    {
        $this->table($table);

        return $this;
    }

    /**
     * @param array[] $values,... Rows to insert
     * @return self
     */
    public function values(array ...$values)
    {
        $this->values = $values;

        return $this;
    }

    /**
     * Build the query,
     */
    public function build()
    {
        if (!$this->table) {
            throw new \RuntimeException("No tables provided for INSERT clause");
        }

        if (!$this->values) {
            throw new \RuntimeException("No values provided for INSERT clause");
        }

        $sql = ['INSERT INTO'];
        $sql[] = $this->table;

        $columns = array_keys($this->values[0]);
        $sql[] = '(' . implode(', ', $columns) . ')';

        $sql[] = 'VALUES';
        $values = [];

        foreach ($this->values as $row) {
            $row_values = [];
            foreach ($row as $value) {
                $row_values[] = $this->addPlaceholder($value);
            }

            $values[] = '(' . implode(', ', $row_values) . ')';
        }

        $sql[] = implode(', ', $values);

        $this->sql = implode(' ', $sql);
        $this->changed = false;
    }
}


<?php declare(strict_types=1); namespace BapCat\Tailor;

use BapCat\Nom\Pipeline;
use BapCat\Persist\Directory;

class Tailor {
  /** @var  Generator  $generator */
  private $generator;

  /** @var  callable[]  $bindings */
  private $bindings = [];

  /**
   * @param  Directory                    $templates
   * @param  Directory                    $cache
   * @param  Pipeline                     $pipeline
   * @param  HashGenerationStrategy|null  $hasher
   */
  public function __construct(Directory $templates, Directory $cache, Pipeline $pipeline, ?HashGenerationStrategy $hasher = null) {
    $this->generator = new Generator($templates, $cache, $pipeline, $hasher);

    spl_autoload_register([$this, 'make']);
  }

  /**
   * May be useful for pre-generating classes (see Remodel)
   *
   * @return  Generator
   */
  public function getGenerator(): Generator {
    return $this->generator;
  }

  /**
   * Bind a class to a template with specified parameters
   *
   * @param  string   $alias
   * @param  string   $template
   * @param  mixed[]  $params    (optional)
   *
   * @return  void
   */
  public function bind(string $alias, string $template, array $params = []): void {
    $this->bindCallback($alias, function(Generator $generator) use($template, $params): void {
      $compiled = $generator->generate($template, $params);
      $generator->includeFile($compiled);
    });
  }

  /**
   * Bind a callback to be executed when the specified class is autoloaded
   *
   * @param  string    $alias
   * @param  callable  $generator
   *
   * @return  void
   */
  public function bindCallback(string $alias, callable $generator): void {
    $this->bindings[$alias] = $generator;
  }

  /**
   * Autoloader
   *
   * @param  string  $alias
   *
   * @return  void
   */
  private function make(string $alias): void {
    if(!array_key_exists($alias, $this->bindings)) {
      return;
    }

    $this->bindings[$alias]($this->generator);
  }
}


<?php

namespace Reaction\Console;

use Reaction;
use Reaction\Exceptions\ErrorException;
use Reaction\Exceptions\UserException;
use Reaction\Helpers\Console;

/**
 * ErrorHandler handles uncaught PHP errors and exceptions.
 *
 * ErrorHandler is configured as an application component in [[\Reaction\RequestApplicationInterface]] by default.
 * You can access that instance via `$app->errorHandler`.
 */
class ErrorHandler extends \Reaction\Base\ErrorHandler
{
    /**
     * Logs the given exception.
     * @param \Exception $exception the exception to be logged
     */
    public function logException($exception)
    {
    }

    /**
     * Renders an exception using ansi format for console output.
     * @param \Exception $exception the exception to be rendered.
     */
    protected function renderException($exception)
    {
        if ($exception instanceof UnknownCommandException) {
            // display message and suggest alternatives in case of unknown command
            $message = $this->formatMessage($exception->getName() . ': ') . $exception->command;
            $alternatives = $exception->getSuggestedAlternatives();
            if (count($alternatives) === 1) {
                $message .= "\n\nDid you mean \"" . reset($alternatives) . '"?';
            } elseif (count($alternatives) > 1) {
                $message .= "\n\nDid you mean one of these?\n    - " . implode("\n    - ", $alternatives);
            }
        } elseif ($exception instanceof Exception && ($exception instanceof UserException || !Reaction::isDebug())) {
            $message = $this->formatMessage($exception->getName() . ': ') . $exception->getMessage();
        } elseif (Reaction::isDebug()) {
            if ($exception instanceof Exception) {
                $message = $this->formatMessage("Exception ({$exception->getName()})");
            } elseif ($exception instanceof ErrorException) {
                $message = $this->formatMessage($exception->getName());
            } else {
                $message = $this->formatMessage('Exception');
            }
            $message .= $this->formatMessage(" '" . get_class($exception) . "'", [Console::BOLD, Console::FG_BLUE])
                . ' with message ' . $this->formatMessage("'{$exception->getMessage()}'", [Console::BOLD]) //. "\n"
                . "\n\nin " . dirname($exception->getFile()) . DIRECTORY_SEPARATOR . $this->formatMessage(basename($exception->getFile()), [Console::BOLD])
                . ':' . $this->formatMessage($exception->getLine(), [Console::BOLD, Console::FG_YELLOW]) . "\n";
            $trace = static::getExceptionTrace($exception, true);
            //$trace = $exception->getTraceAsString();
            $message .= "\n" . $this->formatMessage("Stack trace:\n", [Console::BOLD]) . $trace;
        } else {
            $message = $this->formatMessage('Error: ') . $exception->getMessage();
        }

        if (Reaction::isConsoleApp()) {
            Console::stderr($message . "\n");
        } else {
            echo $message . "\n";
        }
    }

    /**
     * Colorizes a message for console output.
     * @param string $message the message to colorize.
     * @param array $format the message format.
     * @return string the colorized message.
     * @see Console::ansiFormat() for details on how to specify the message format.
     */
    protected function formatMessage($message, $format = [Console::FG_RED, Console::BOLD])
    {
        $stream = Reaction::isConsoleApp() ? \STDERR : \STDOUT;
        // try controller first to allow check for --color switch
        if (Reaction::isConsoleApp() && Console::streamSupportsAnsiColors($stream)) {
            $message = Console::ansiFormat($message, $format);
        }

        return $message;
    }
}


<?php namespace Ordercloud\Entities\Organisations;

use JsonSerializable;
use Ordercloud\Entities\Users\UserShort;

class OrganisationProfile implements JsonSerializable
{
    /** @var integer */
    private $id;
    /** @var UserShort */
    private $contactPerson;
    /** @var string */
    private $contactNumber;
    /** @var boolean */
    private $enabled;
    /** @var OrganisationAddress */
    private $address;

    public function __construct($id, UserShort $contactPerson, $contactNumber, $enabled, OrganisationAddress $address = null)
    {
        $this->id = $id;
        $this->contactPerson = $contactPerson;
        $this->contactNumber = $contactNumber;
        $this->enabled = $enabled;
        $this->address = $address;
    }

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

    /**
     * @return UserShort
     */
    public function getContactPerson()
    {
        return $this->contactPerson;
    }

    /**
     * @return string
     */
    public function getContactNumber()
    {
        return $this->contactNumber;
    }

    /**
     * @return boolean
     */
    public function isEnabled()
    {
        return $this->enabled;
    }

    /**
     * @return OrganisationAddress
     */
    public function getAddress()
    {
        return $this->address;
    }

    /**
     * Specify data which should be serialized to JSON
     */
    public function jsonSerialize()
    {
        return [
            'id' => $this->getId(),
            'contactPerson' => $this->getContactPerson(),
            'contactNumber' => $this->getContactNumber(),
            'enabled' => $this->isEnabled(),
            'address' => $this->getAddress(),
        ];
    }
}


<?php

namespace Reaction\Web;

use Reaction\Base\BaseObject;
use Reaction\Helpers\ArrayHelper;

/**
 * Cookie represents information related with a cookie, such as [[name]], [[value]], [[domain]], etc.
 *
 * For more details and usage information on Cookie, see the [guide article on handling cookies](guide:runtime-sessions-cookies).
 */
class Cookie extends BaseObject
{
    /**
     * @var string name of the cookie
     */
    public $name;
    /**
     * @var string value of the cookie
     */
    public $value = '';
    /**
     * @var string domain of the cookie
     */
    public $domain = '';
    /**
     * @var int the timestamp at which the cookie expires. This is the server timestamp.
     * Defaults to 0, meaning "until the browser is closed".
     */
    public $expire = 0;
    /**
     * @var string the path on the server in which the cookie will be available on. The default is '/'.
     */
    public $path = '/';
    /**
     * @var bool whether cookie should be sent via secure connection
     */
    public $secure = false;
    /**
     * @var bool whether the cookie should be accessible only through the HTTP protocol.
     * By setting this property to true, the cookie will not be accessible by scripting languages,
     * such as JavaScript, which can effectively help to reduce identity theft through XSS attacks.
     */
    public $httpOnly = true;

    /**
     * Magic method to turn a cookie object into a string without having to explicitly access [[value]].
     *
     * ```php
     * if (isset($request->cookies['name'])) {
     *     $value = (string) $request->cookies['name'];
     * }
     * ```
     *
     * @return string The value of the cookie. If the value property is null, an empty string will be returned.
     */
    public function __toString()
    {
        return (string)$this->value;
    }

    /**
     * Get cookie for Set-Cookie header
     * @param string $validationKey Cookie validation key
     * @return string
     * @throws \Reaction\Exceptions\InvalidConfigException
     */
    public function getForHeader($validationKey = null) {
        if ($this->expire != 1 && isset($validationKey)) {
            $value = \Reaction::$app->security->hashData(serialize([$this->name, $this->value]), $validationKey);
        }
        $value = isset($value) && $value !== "" ? urlencode($value) : '';
        $name = urlencode($this->name);
        $data = [
            'Secure' => $this->secure ? null : '',
            'HttpOnly' => $this->httpOnly ? null : '',
            'Domain' => isset($this->domain) ? $this->domain : '',
            'Path' => isset($this->path) ? $this->path : '',
            'Expires' => !empty($this->expire) ? gmdate('D, d M Y H:i:s T', $this->expire) : '',
        ];
        foreach ($data as $key => $val) {
            if ($val === '') {
                unset($data[$key]);
            }
        }
        $data = ArrayHelper::merge([$name => $value], $data);

        return $this->convertArrayToHeaderString($data);
    }

    /**
     * Convert cookie data array to Set-cookie header string
     * @param array $data
     * @return string
     */
    protected function convertArrayToHeaderString(array $data) {
        $strings = [];
        foreach ($data as $key => $val) {
            if (null === $val) {
                $strings[] = $key;
                continue;
            }
            if (is_bool($val)) {
                $val = !empty($val) ? 1 : 0;
            }
            $strings[] = $key . '=' . $val;
        }
        return implode('; ', $strings);
    }
}


<?php
/**
 * This file is a part of CSCFA project.
 *
 * PHP version 5.5
 *
 * @category Object
 * @package  CscfaCacheSystemBundle
 * @author   Matthieu VALLANCE <matthieu.vallance@cscfa.fr>
 * @license  http://opensource.org/licenses/MIT MIT
 * @filesource
 * @link     http://cscfa.fr
 */
namespace Cscfa\Bundle\CacheSystemBundle\Object\Element;

/**
 * CacheElement
 *
 * The CacheElement manage the
 * cache element
 *
 * @category Object
 * @package  CscfaCacheSystemBundle
 * @author   Matthieu VALLANCE <matthieu.vallance@cscfa.fr>
 * @license  http://opensource.org/licenses/MIT MIT
 * @filesource
 * @link     http://cscfa.fr
 */
class CacheElement implements \Serializable
{

    /**
     * Key
     *
     * The element key
     *
     * @var string
     */
    protected $key;

    /**
     * Time over
     *
     * The date time to
     * ensure the cache
     * element
     *
     * @var \DateTime
     */
    protected $timeOver;

    /**
     * Content
     *
     * The cache content
     *
     * @var string
     */
    protected $content;

    /**
     * Constructor
     *
     * Default constructor
     *
     * @param string $key - the element key
     */
    public function __construct($key = null)
    {
        $this->key = $key;
    }

    /**
     * Get key
     *
     * Get the element key
     *
     * @return string
     */
    public function getKey()
    {
        return $this->key;
    }

    /**
     * Get time over
     *
     * Get the element time over
     *
     * @return DateTime
     */
    public function getTimeOver()
    {
        return $this->timeOver;
    }

    /**
     * Set time over
     *
     * Set the element time over
     *
     * @param \DateTime $timeOver - the element time over
     *
     * @return CacheElement
     */
    public function setTimeOver(\DateTime $timeOver)
    {
        $this->timeOver = $timeOver;
        return $this;
    }

    /**
     * Get content
     *
     * Get the element content
     *
     * @return string
     */
    public function getContent()
    {
        return $this->content;
    }

    /**
     * Set content
     *
     * Set the element content
     *
     * @param string $content - the element content
     *
     * @return CacheElement
     */
    public function setContent($content)
    {
        $this->content = $content;
        return $this;
    }

    /**
     * Serialize
     *
     * Serialize the current
     * instance
     *
     * @see Serializable::serialize()
     */
    public function serialize()
    {
        return serialize(
            array(
                "key" => $this->key,
                "timeOver" => $this->timeOver->getTimestamp(),
                "content" => $this->content
            )
        );
    }

    /**
     * Unserialize
     *
     * Unserialize an
     * instance
     *
     * @see Serializable::unserialize()
     */
    public function unserialize($serialized)
    {
        $tmp = unserialize($serialized);

        $dateTime = new \DateTime();
        $dateTime->setTimestamp($tmp['timeOver']);

        $this->key = $tmp['key'];
        $this->timeOver = $dateTime;
        $this->content = $tmp['content'];
    }
}


<?php

/**
 * merry\Config
 *
 * @author Michael Wallner <mike@php.net>
 */
namespace merry;

/**
 * A merry config container
 *
 * @see https://github.com/m6w6/merry
 * @package merry\Config
 */
class Config extends Container
{
	/**
	 * Create a new configuration container
	 * @param array $array the configuration array
	 * @param string $section the section to use (i.e. first level key)
	 * @param string $section_sep a separator for section extension
	 * @param string $key_sep a separator for key traversal
	 */
	public function __construct(array $array = null, $section = null, $section_sep = ":", $key_sep = ".") {
		if (isset($section) && strlen($section_sep)) {
			$array = $this->combine($array, $section_sep)[$section];
		}
		if ($array) {
			$config = array();

			if (strlen($key_sep)) {
				foreach ($array as $key => $val) {
					$this->walk($config, $key, $val, $key_sep);
				}
			}
			parent::__construct($config, false);
		}
	}

	/**
	 * Combine individual sections with their parent section
	 * @param array $array the config array
	 * @param string $section_sep the section extension separator
	 * @return array merged sections
	 */
	protected function combine($array, $section_sep) {
		foreach ($array as $section_spec => $settings) {
			$section_spec = array_map("trim", explode($section_sep, $section_spec));
			if (count($section_spec) > 1) {
				$sections[$section_spec[0]] = array_merge(
					$sections[$section_spec[1]],
					$settings
				);
			} else {
				$sections[$section_spec[0]] = $settings;
			}
		}
		return $sections;
	}

	/**
	 * Walk a key split by the key separator into an array up and set the
	 * respective value on the leaf
	 * @param mixed $ptr current leaf pointer in the array
	 * @param string $key the array key
	 * @param mixed $val the value to set
	 * @param string $key_sep the key separator for traversal
	 */
	protected function walk(&$ptr, $key, $val, $key_sep) {
		foreach (explode($key_sep, $key) as $sub) {
			$ptr = &$ptr[$sub];
		}
		$ptr = $val;
	}
}

/* vim: set noet ts=4 sw=4: */


<?php
namespace Gosyl\CommonBundle\Twig;

use Gosyl\CommonBundle\Twig\Message\MessageOptions;

class Message extends \Twig_Extension {
	/**
	 * Constantes définissant le niveau d'alerte d'un message
	 * @var int
	 */
	const INFO = 1;
	const WARNING = 2;
	const ERROR = 3;
	const ALERT = 4;
	const QUESTION = 5;

	/**
	 * Tableaux qui relie les niveaux d'alerte à leurs noms utilisés dans le helper
	 * @var array
	 */
	public static $aTypeMessage = array(
			self::INFO => 'info',
			self::WARNING => 'warning',
			self::ALERT => 'alert',
			self::ERROR => 'error',
			self::QUESTION => 'question',

	);

	/**
	 * Tableau des messages par défaut
	 * @var array
	 */
	protected $_aMessage = array(
			'inscriptionOk' => array(
					'message' => 'Un email a été envoyé à l\'administrateur afin qu\'il valide l\'inscription.

Un email vous sera envoyé lorsque votre compte sera actif.

Merci de bien vouloir patienter...',
					'type' => self::INFO,
					'dialogOptions' => array(
							'events' => array(
									'close' => array(
											'data' => array(
													'function' => '{
						                                document.location = GLOBAL_basePath;
						                            }',
											),
											'ecrasement' => true
									),
							),
					),
			),
			'suppressionUtilisateur' => array(
					'message' => 'Êtes-vous sûr de vouloir supprimer cet utilisateur ?',
					'type' => self::QUESTION,
					'dialogOptions' => array(
							'options' => array(
									'autoOpen' => array(
											'data' => false,
											'ecrasement' => true,
									),
									'buttons' => array(
											'data' => array(
													0 => array(
															'text' => 'Oui',
															'click' => array(
																	'function' => '{
								                                        suppressionUtilisateur($(this).data(\'dataUtilisateur\'));
								                                    }',
															),
													),
													1 => array(
															'text' => 'Non',
															'click' => array(
																	'function' => '{
								                                        $(this).dialog(\'close\');
								                                    }',
															),
													),
											),
											'ecrasement' => true,
									),
							),
							//'events' => null/*array(

							//)*/
					),
					'idDialog' => 'dmdSupprUtilisateur',
			),
			'restaurationUtilisateur' => array(
					'message' => 'Êtes-vous sûr de vouloir restaurer cet utilisateur ?',
					'type' => self::QUESTION,
					'dialogOptions' => array(
							'options' => array(
									'autoOpen' => array(
											'data' => false,
											'ecrasement' => true,
									),
									'buttons' => array(
											'data' => array(
													0 => array(
															'text' => 'Oui',
															'click' => array(
																	'function' => '{
								                                        restoreUser($(this).data(\'dataUtilisateur\'));
								                                    }',
															),
													),
													1 => array(
															'text' => 'Non',
															'click' => array(
																	'function' => '{
								                                        $(this).dialog(\'close\');
								                                    }',
															),
													),
											),
											'ecrasement' => true,
									),
							),
					),
					'idDialog' => 'dmdRestUtilisateur',
			),
			'activationUtilisateur' => array(
					'message' => 'Êtes-vous sûr de vouloir activer cet utilisateur ?',
					'type' => self::QUESTION,
					'dialogOptions' => array(
							'options' => array(
									'autoOpen' => array(
											'data' => false,
											'ecrasement' => true,
									),
									'buttons' => array(
											'data' => array(
													0 => array(
															'text' => 'Oui',
															'click' => array(
																	'function' => '{
								                                        activeUser($(this).data(\'dataUtilisateur\'));
								                                    }',
															),
													),
													1 => array(
															'text' => 'Non',
															'click' => array(
																	'function' => '{
								                                        $(this).dialog(\'close\');
								                                    }',
															),
													),
											),
											'ecrasement' => true,
									),
							),
					),
					'idDialog' => 'dmdActUtilisateur',
			),
			'desactivationUtilisateur' => array(
					'message' => 'Êtes-vous sûr de vouloir desactiver cet utilisateur ?',
					'type' => self::QUESTION,
					'dialogOptions' => array(
							'options' => array(
									'autoOpen' => array(
											'data' => false,
											'ecrasement' => true,
									),
									'buttons' => array(
											'data' => array(
													0 => array(
															'text' => 'Oui',
															'click' => array(
																	'function' => '{
								                                        desactiveUser($(this).data(\'dataUtilisateur\'));
								                                    }',
															),
													),
													1 => array(
															'text' => 'Non',
															'click' => array(
																	'function' => '{
								                                        $(this).dialog(\'close\');
								                                    }',
															),
													),
											),
											'ecrasement' => true,
									),
							),
					),
					'idDialog' => 'dmdDesactiveUtilisateur',
			),
			'supprDossier' => array(
					'message' => 'Êtes-vous sûr de vouloir supprimer :  ?',
					'type' => self::QUESTION,
					'dialogOptions' => array(
							'options' => array(
									'autoOpen' => array(
											'data' => false,
											'ecrasement' => true,
									),
									'buttons' => array(
											'data' => array(
													0 => array(
															'text' => 'Oui',
															'click' => array(
																	'function' => '{
								                                        Gosyl.Fileserver.GestionFichiers.Ajax.supprDossiersAction();
								                                	}',
															),
													),
													1 => array(
															'text' => 'Non',
															'click' => array(
																	'function' => '{
								                                        $(this).dialog(\'close\');
								                                	}',
															),
													),
											),
											'ecrasement' => true,
									),
							),
					),
					'idDialog' => 'dmdSupprDossier',
			),
			'errorMsg' => array(
					'type' => self::ERROR,
					'dialogOptions' => array(
							'options' => array(
									'autoOpen' => array(
											'data' => false,
											'ecrasement' => true,
									),
									'buttons' => array(
											'data' => array(
													0 => array(
															'text' => 'Ok',
															'click' => array(
																	'function' => '{
								                                        $(this).dialog(\'close\');
								                                    }',
															),
													),
											),
											'ecrasement' => true,
									),
							),
					),
			),
			'inconnu' => array(
					'message' => 'Nom de message inconnu',
					'type' => self::ERROR,
			),
			'aucunMessage' => array(
					'message' => 'Aucun message à afficher',
					'type' => self::WARNING,
			),
			'param' => array(
					'message' => '',
					'type' => self::INFO,
			),
	);

	public function getFunctions() {
		return array(
				new \Twig_SimpleFunction('message', array($this, 'messageFct'), array('is_safe' => array('html')))
		);
	}

	public function messageFct($nomMessage = null, $message = null, $typeMessage = self::INFO, array $messageOptions = null) {
		$contenu = '';

		if(is_null($nomMessage)) {
			// On affiche un message non enregistré
			if(is_null($message)) {
				// Erreur aucun message parametré
				$aMessage = $this->_aMessage['aucunMessage'];
			} else {
				if(is_null($messageOptions)) {
					// On prend les options par défaut
					$aOptions = MessageOptions::$aDefaultOptions;
					$aMessage = array('type' => !is_null($typeMessage) ? $typeMessage : self::INFO, 'message' => $message, $aOptions);
				} else {
					// Options redéfinies
					$aOptions = $messageOptions;
					$aMessage = array_merge(array('type' => !is_null($typeMessage) ? $typeMessage : self::INFO, 'message' => $message), $aOptions);
				}
				// Construction du tableau

			}
		} else {
            $aMessage = $this->_aMessage[$nomMessage];

            if(!is_null($message)) {
                $aMessage['message'] = $message;
                if(isset($messageOptions)) {
                    $aMessage['dialogOptions'] = array_merge($aMessage['dialogOptions'], $messageOptions['dialogOptions']);
                    if(isset($messageOptions['idDialog'])) {
                        $aMessage['idDialog'] = $messageOptions['idDialog'];
                    }
                }
            }
        }

        if(!isset($aMessage['dialogOptions'])) {
        	// Si pas d'option défini
        	$aMessage['dialogOptions'] = MessageOptions::$aDefaultOptions;
        } else {

        	$aMessageDefault = MessageOptions::$aDefaultOptions;

        	// on fusionne les deux tableaux d'options
        	if(isset($aMessage['dialogOptions']['options'])) {
        		$aMessage['dialogOptions']['options'] = $this->_integreOptions('options', $aMessageDefault, $aMessage['dialogOptions']['options']);
        	} else {
        		$aMessage['dialogOptions']['options'] = MessageOptions::$aDefaultOptions['options'];
        	}

        	if(isset($aMessage['dialogOptions']['events']) && !is_null($aMessage['dialogOptions']['events'])) {
        		$aMessage['dialogOptions']['events'] = $this->_integreOptions('events', $aMessageDefault, $aMessage['dialogOptions']['events']);
        	} else {
        		$aMessage['dialogOptions']['events'] = MessageOptions::$aDefaultOptions['events'];
        	}
        }

        $aMessage['dialogOptions'] = $this->_integreIconeTypeAlerte($aMessage['dialogOptions'], $aMessage['type']);

        // Création du message
        $contenu .= $this->_makeDiv($aMessage);

        // Création du js qui gère le message
        $contenu .= $this->_makeJs($aMessage);

		return $contenu;
	}

	public function getName() {
		return 'twig.extension.message';
	}

	protected function _integreIconeTypeAlerte($aOptions, $type) {
		// Permet d'ajouter un titre avec une image définissant le niveau d'alerte
		$aOptions['events']['open']['function'] = substr_replace(
				$aOptions['events']['open']['function'],
				'if($(".ui-dialog .ui-dialog-titlebar .ui-dialog-title img[src=\"/bundles/gosylcommon/images/' . self::$aTypeMessage[$type] . '.png\"]").length == 0) {
                 $(".ui-dialog .ui-dialog-titlebar .ui-dialog-title img").remove();
                 $(".ui-dialog .ui-dialog-titlebar .ui-dialog-title").prepend(" ");
             }',
				-1,
				0
				);

		return $aOptions;
	}

	protected function _integreOptions($typeOption, $aMessageDefaut, $aMessage) {
		$aMessageTemp = array();
		// Si les options du modal sont présentes
		foreach ($aMessage as $key => $aValue) {
			// On éclate le tableau d'option par défaut
			if(!is_null($aValue)) {
				// Si le paramètre est présent
				if(!$aValue['ecrasement']) {
					// on ajoute le nouveau paramètre aux paramètres existant
					if(is_array($aValue['data'])) {
						foreach ($aValue['data'] as $subKey => $subValue) {
							if(is_string($subKey)) {
								// cas des fonctions
								$aMessage[$key]['function'] = array();
								$aMessage[$key]['function'] = substr_replace(
										$aMessageDefaut[$typeOption][$key]['function'],
										substr($aMessage[$key]['data']['function'], 1),
										-1,
										strlen($aMessage[$key]['data']['function']) - 1
										);
								unset($aMessage[$key]['data']);
								unset($aMessage[$key]['ecrasement']);
							} elseif (is_int($subKey)) {
								// cas des boutons penser à mettre les index à partir de 1 !
								$aMessageTemp[$key] = array_merge($aMessage[$key]['data'], $aMessageDefaut[$typeOption][$key]);
							}
						}
					}
				} else {
					// On écrase les paramètres par défaut
					foreach ($aMessageDefaut[$typeOption] as $cle => $valeur) {
						if($cle == $key) {
							if(isset($aMessage[$cle])) {
								if(isset($aMessage[$cle]['data'])) {
									if(!is_null($aMessage[$cle]['data'])) {
										// le paramètre est trouvé on réorganise le tableau
										$param = $aMessage[$cle]['data'];
										//unset($aMessage['dialogOptions'][$typeOption][$cle]);
										$aMessageTemp[$cle] = $param;
									}
								} elseif(is_null($aMessage[$cle]['data'])) {
									$aMessageTemp[$cle] = null;
								}
							}
						}
					}
				}
			}
		}

		$aMessage = array_merge($aMessage, $aMessageTemp);

		// on récupère les options par défaut
		foreach ($aMessageDefaut[$typeOption] as $key => $value) {
			if(!isset($aMessage[$key])) {
				$aMessage[$key] = $value;
			}
		}

		return $aMessage;
	}

	/**
	 * Création du conteneur du message
	 *
	 * @param array $paramMessage paramètres du message
	 * @return string
	 */
	protected function _makeDiv(array $paramMessage) {
		$contenu = '';

		$idDialog = isset($paramMessage['idDialog']) ? $paramMessage['idDialog'] : ('dialog' . ucfirst(self::$aTypeMessage[$paramMessage['type']]));

		$contenu .= '

' . $paramMessage['message'] . '

';

		return $contenu;
	}

	/**
	 * Création du js qui gère le message
	 *
	 * @param array $message options du message
	 */
	protected function _makeJs(array $message) {
		$contenu = '';

		return $contenu;
	}
}


<?php

namespace Reaction\Helpers\Request;

/**
 * Class StringHelper. Proxy To \Reaction\Helpers\StringHelper
 * @package Reaction\Helpers\Request
 */
class StringHelper extends RequestAppHelperProxy
{
    public $helperClass = 'Reaction\Helpers\StringHelper';

    /**
     * Returns the number of bytes in the given string.
     * This method ensures the string is treated as a byte array by using `mb_strlen()`.
     * @param string $string the string being measured for length
     * @return int the number of bytes in the given string.
     * @see \Reaction\Helpers\StringHelper::byteLength()
     */
    public function byteLength($string)
    {
        return $this->proxy(__FUNCTION__, [$string]);
    }

    /**
     * Returns the portion of string specified by the start and length parameters.
     * This method ensures the string is treated as a byte array by using `mb_substr()`.
     * @param string $string the input string. Must be one character or longer.
     * @param int $start the starting position
     * @param int $length the desired portion length. If not specified or `null`, there will be
     * no limit on length i.e. the output will be until the end of the string.
     * @return string the extracted part of string, or FALSE on failure or an empty string.
     * @see http://www.php.net/manual/en/function.substr.php
     * @see \Reaction\Helpers\StringHelper::byteSubstr()
     */
    public function byteSubstr($string, $start, $length = null)
    {
        return $this->proxy(__FUNCTION__, [$string, $start, $length]);
    }

    /**
     * Returns the trailing name component of a path.
     * This method is similar to the php function `basename()` except that it will
     * treat both \ and / as directory separators, independent of the operating system.
     * This method was mainly created to work on php namespaces. When working with real
     * file paths, php's `basename()` should work fine for you.
     * Note: this method is not aware of the actual filesystem, or path components such as "..".
     *
     * @param string $path A path string.
     * @param string $suffix If the name component ends in suffix this will also be cut off.
     * @return string the trailing name component of the given path.
     * @see http://www.php.net/manual/en/function.basename.php
     * @see \Reaction\Helpers\StringHelper::basename()
     */
    public function basename($path, $suffix = '')
    {
        return $this->proxy(__FUNCTION__, [$path, $suffix]);
    }

    /**
     * Returns parent directory's path.
     * This method is similar to `dirname()` except that it will treat
     * both \ and / as directory separators, independent of the operating system.
     *
     * @param string $path A path string.
     * @return string the parent directory's path.
     * @see http://www.php.net/manual/en/function.basename.php
     * @see \Reaction\Helpers\StringHelper::dirname()
     */
    public function dirname($path)
    {
        return $this->proxy(__FUNCTION__, [$path]);
    }

    /**
     * Truncates a string to the number of characters specified.
     *
     * @param string $string The string to truncate.
     * @param int $length How many characters from original string to include into truncated string.
     * @param string $suffix String to append to the end of truncated string.
     * @param string $encoding The charset to use, defaults to charset currently used by application.
     * @param bool $asHtml Whether to treat the string being truncated as HTML and preserve proper HTML tags.
     * @return string the truncated string.
     * @see \Reaction\Helpers\StringHelper::truncate()
     */
    public function truncate($string, $length, $suffix = '...', $encoding = null, $asHtml = false)
    {
        return $this->proxyWithCharset(__FUNCTION__, [$string, $length, $suffix, $encoding, $asHtml], -2);
    }

    /**
     * Truncates a string to the number of words specified.
     *
     * @param string $string The string to truncate.
     * @param int $count How many words from original string to include into truncated string.
     * @param string $suffix String to append to the end of truncated string.
     * @param bool $asHtml Whether to treat the string being truncated as HTML and preserve proper HTML tags.
     * @return string the truncated string.
     * @see \Reaction\Helpers\StringHelper::truncateWords()
     */
    public function truncateWords($string, $count, $suffix = '...', $asHtml = false)
    {
        return $this->proxy(__FUNCTION__, [$string, $count, $suffix, $asHtml]);
    }

    /**
     * Truncate a string while preserving the HTML.
     *
     * @param string $string The string to truncate
     * @param int $count
     * @param string $suffix String to append to the end of the truncated string.
     * @param string|bool $encoding
     * @return string
     */
    protected function truncateHtml($string, $count, $suffix, $encoding = false)
    {
        return $this->proxyWithCharset(__FUNCTION__, [$string, $count, $suffix, $encoding]);
    }

    /**
     * Check if given string starts with specified substring.
     * Binary and multibyte safe.
     *
     * @param string $string Input string
     * @param string $with Part to search inside the $string
     * @param bool   $caseSensitive Case sensitive search. Default is true. When case sensitive is enabled, $with must exactly match the starting of the string in order to get a true value.
     * @param string $encoding String encoding
     * @return bool Returns true if first input starts with second input, false otherwise
     * @see \Reaction\Helpers\StringHelper::startsWith()
     */
    public function startsWith($string, $with, $caseSensitive = true, $encoding = null)
    {
        return $this->proxyWithCharset(__FUNCTION__, [$string, $with, $caseSensitive, $encoding]);
    }

    /**
     * Check if given string ends with specified substring.
     * Binary and multibyte safe.
     *
     * @param string $string Input string to check
     * @param string $with Part to search inside of the $string.
     * @param bool $caseSensitive Case sensitive search. Default is true. When case sensitive is enabled, $with must exactly match the ending of the string in order to get a true value.
     * @param string $encoding String encoding
     * @return bool Returns true if first input ends with second input, false otherwise
     * @see \Reaction\Helpers\StringHelper::endsWith()
     */
    public function endsWith($string, $with, $caseSensitive = true, $encoding = null)
    {
        return $this->proxyWithCharset(__FUNCTION__, [$string, $with, $caseSensitive, $encoding]);
    }

    /**
     * Explodes string into array, optionally trims values and skips empty ones.
     *
     * @param string $string String to be exploded.
     * @param string $delimiter Delimiter. Default is ','.
     * @param mixed $trim Whether to trim each element. Can be:
     *   - boolean - to trim normally;
     *   - string - custom characters to trim. Will be passed as a second argument to `trim()` function.
     *   - callable - will be called for each value instead of trim. Takes the only argument - value.
     * @param bool $skipEmpty Whether to skip empty strings between delimiters. Default is false.
     * @return array
     * @see \Reaction\Helpers\StringHelper::explode()
     */
    public function explode($string, $delimiter = ',', $trim = true, $skipEmpty = false)
    {
        return $this->proxy(__FUNCTION__, [$string, $delimiter, $trim, $skipEmpty]);
    }

    /**
     * Counts words in a string.
     *
     * @param string $string
     * @return int
     * @see \Reaction\Helpers\StringHelper::countWords()
     */
    public function countWords($string)
    {
        return $this->proxy(__FUNCTION__, [$string]);
    }

    /**
     * Returns string representation of number value with replaced commas to dots, if decimal point
     * of current locale is comma.
     * @param int|float|string $value
     * @return string
     * @see \Reaction\Helpers\StringHelper::normalizeNumber()
     */
    public function normalizeNumber($value)
    {
        return $this->proxy(__FUNCTION__, [$value]);
    }

    /**
     * Encodes string into "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648).
     *
     * > Note: Base 64 padding `=` may be at the end of the returned string.
     * > `=` is not transparent to URL encoding.
     *
     * @see https://tools.ietf.org/html/rfc4648#page-7
     * @param string $input the string to encode.
     * @return string encoded string.
     * @see \Reaction\Helpers\StringHelper::base64UrlEncode()
     */
    public function base64UrlEncode($input)
    {
        return $this->proxy(__FUNCTION__, [$input]);
    }

    /**
     * Decodes "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648).
     *
     * @see https://tools.ietf.org/html/rfc4648#page-7
     * @param string $input encoded string.
     * @return string decoded string.
     * @see \Reaction\Helpers\StringHelper::base64UrlDecode()
     */
    public function base64UrlDecode($input)
    {
        return $this->proxy(__FUNCTION__, [$input]);
    }

    /**
     * Safely casts a float to string independent of the current locale.
     *
     * The decimal separator will always be `.`.
     * @param float|int $number a floating point number or integer.
     * @return string the string representation of the number.
     * @see \Reaction\Helpers\StringHelper::floatToString()
     */
    public function floatToString($number)
    {
        return $this->proxy(__FUNCTION__, [$number]);
    }

    /**
     * Checks if the passed string would match the given shell wildcard pattern.
     * This function emulates [[fnmatch()]], which may be unavailable at certain environment, using PCRE.
     * @param string $pattern the shell wildcard pattern.
     * @param string $string the tested string.
     * @param array $options options for matching. Valid options are:
     *
     * - caseSensitive: bool, whether pattern should be case sensitive. Defaults to `true`.
     * - escape: bool, whether backslash escaping is enabled. Defaults to `true`.
     * - filePath: bool, whether slashes in string only matches slashes in the given pattern. Defaults to `false`.
     *
     * @return bool whether the string matches pattern or not.
     * @see \Reaction\Helpers\StringHelper::matchWildcard()
     */
    public function matchWildcard($pattern, $string, $options = [])
    {
        return $this->proxy(__FUNCTION__, [$pattern, $string, $options]);
    }
}


<?php
/**
 * This file is part of the CarteBlanche PHP framework.
 *
 * (c) Pierre Cassat <me@e-piwi.fr> and contributors
 *
 * License Apache-2.0 <http://github.com/php-carteblanche/carteblanche/blob/master/LICENSE>
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CarteBlanche\Controller;

use \CarteBlanche\CarteBlanche;
use \CarteBlanche\Abstracts\AbstractController;

/**
 * Errors controller extending the abstract \CarteBlanche\Abstracts\AbstractController class
 *
 * @author  Piero Wbmstr <me@e-piwi.fr>
 */
class ErrorController
    extends AbstractController
{

    /**
     * The directory where to search the views files
     */
    static $views_dir = 'error/';

    /**
     * @see self::back_home()
     */
    public function indexAction($id = null)
    {
        return self::back_home();
    }

    /**
     * @see self::back_home()
     */
    public function emptyAction($altdb = null)
    {
        return self::back_home();
    }

    /**
     * Back to the homepage of the application
     */
    public function back_home()
    {
        $this->getContainer()->get('router')->redirect();
    }

    /**
     * Send a mail report to the website contact
     */
    public function reportAction($code = null)
    {
        $referer = $this->getContainer()->get('router')->getReferer();
        $txt_message = $this->view(
            'error_mail_content',
            array(
                'url'=>$referer,
                'code'=>$code
            )
        );

        $webmaster_email = CarteBlanche::getConfig('app.webmaster_email', null);
        $webmaster_name = CarteBlanche::getConfig('app.webmaster_name', null);
        $mail = new \MimeEmail\Lib\MimeEmail();
        $mail
            ->setTo($webmaster_email, $webmaster_name)
            ->setSubject($this->trans('Error report'))
            ->setText($txt_message);
        $ok = $mail->send(true);
        if ($ok) {
            $this->getContainer()->get('session')
                ->setFlash("info:".$this->trans('OK - A report has been sent concerning your error. Thank you.'));
        } else {
            $this->getContainer()->get('session')
                ->setFlash("error:".$this->trans('ERROR - An error occurred while trying to send email ...'));
        }
        $this->getContainer()->get('router')->redirect($_SERVER['HTTP_REFERER']);
    }

    /**
     * The "not found" error page
     *
     * @return string The 403 forbidden error page view content
     */
    public function error403Action()
    {
        $this->getContainer()->get('router')->setReferer();
        $_args=array(
            'offset'=>null,'limit'=>null,'table'=>null,'altdb'=>null,
            'orderby'=>null, 'orderway'=>null
        );
        $url_args = CarteBlanche::getConfig('routing.arguments_mapping');
        foreach ($_args as $_arg_var=>$_arg_val) {
            if (!empty($_arg_val)) {
                if (in_array($_arg_var, $url_args))
                    $args[ array_search($_arg_var, $url_args) ] = $_arg_val;
                else
                    $args[ $_arg_var ] = $_arg_val;
            }
        }
        $searchbox = new \Tool\SearchBox(array(
            'hiddens'=>$_args, 'advanced_search'=>true
        ));
        $ctt = (string) $searchbox;

        $_f = CarteBlanche::getContainer()->get('locator')->locateView(self::$views_dir.'403.md');
        $_txt = new \Tool\Text(array(
//            'original_str'=>file_get_contents(CarteBlanche::getPath('root_path')._CarteBlanche_DIR._VIEWSDIR.self::$views_dir.'404.md'),
            'original_str'=>file_get_contents($_f),
            'markdown'=>true,
        ));
        $ctt .= $_txt;

        $params = array(
            'title'=>$this->trans('OOPS ! You can\'t access this page !!'),
            'content'=>$ctt,
            'sitemap_url'=>CarteBlanche::getContainer()->get('router')->buildUrl(array(
                'controller'=>'cms','action'=>'sitemap'
            )),
            'report_error'=>CarteBlanche::getContainer()->get('router')->buildUrl(array(
                'controller'=>'error','action'=>'report','code'=>'403'
            ))
        );
        $params['output'] = CarteBlanche::getContainer()->get('front_controller')
            ->view(self::$views_dir.'error', $params);
        return CarteBlanche::getContainer()->get('front_controller')->render($params);
    }

    /**
     * The "not found" error page
     *
     * @return string The 404 error page view content
     */
    public function error404Action()
    {
        $this->getContainer()->get('router')->setReferer();
        $_args=array(
            'offset'=>null,'limit'=>null,'table'=>null,'altdb'=>null,
            'orderby'=>null, 'orderway'=>null
        );
        $url_args = CarteBlanche::getConfig('routing.arguments_mapping');
        foreach ($_args as $_arg_var=>$_arg_val) {
            if (!empty($_arg_val)) {
                if (in_array($_arg_var, $url_args))
                    $args[ array_search($_arg_var, $url_args) ] = $_arg_val;
                else
                    $args[ $_arg_var ] = $_arg_val;
            }
        }
        $searchbox = new \Tool\SearchBox(array(
            'hiddens'=>$_args, 'advanced_search'=>true
        ));
        $ctt = (string) $searchbox;

        $_f = CarteBlanche::getContainer()->get('locator')->locateView(self::$views_dir.'404.md');
        $_txt = new \Tool\Text(array(
//            'original_str'=>file_get_contents(CarteBlanche::getPath('root_path')._CarteBlanche_DIR._VIEWSDIR.self::$views_dir.'404.md'),
            'original_str'=>file_get_contents($_f),
            'markdown'=>true,
        ));
        $ctt .= $_txt;

        $params = array(
            'title'=>$this->trans('OOPS ! The page was not found !!'),
            'content'=>$ctt,
            'sitemap_url'=>CarteBlanche::getContainer()->get('router')->buildUrl(array(
                'controller'=>'cms','action'=>'sitemap'
            )),
            'report_error'=>CarteBlanche::getContainer()->get('router')->buildUrl(array(
                'controller'=>'error','action'=>'report','code'=>'404'
            ))
        );
        $params['output'] = CarteBlanche::getContainer()->get('front_controller')
            ->view(self::$views_dir.'error', $params);
        return CarteBlanche::getContainer()->get('front_controller')->render($params);
    }

    /**
     * The "internal server error" page
     *
     * @return string The 500 error page view content
     */
    public function error500Action()
    {
        $this->getContainer()->get('router')->setReferer();
        $_args=array(
            'offset'=>null,'limit'=>null,'table'=>null,'altdb'=>null,
            'orderby'=>null, 'orderway'=>null
        );
        $url_args = CarteBlanche::getConfig('routing.arguments_mapping');
        foreach ($_args as $_arg_var=>$_arg_val) {
            if (!empty($_arg_val)) {
                if (in_array($_arg_var, $url_args))
                    $args[ array_search($_arg_var, $url_args) ] = $_arg_val;
                else
                    $args[ $_arg_var ] = $_arg_val;
            }
        }
        $searchbox = new \Tool\SearchBox(array(
            'hiddens'=>$_args, 'advanced_search'=>true
        ));
        $ctt = (string) $searchbox;

        $_f = CarteBlanche::getContainer()->get('locator')->locateView(self::$views_dir.'500.md');
        $_txt = new \Tool\Text(array(
//            'original_str'=>file_get_contents(CarteBlanche::getPath('root_path')._CarteBlanche_DIR._VIEWSDIR.self::$views_dir.'500.md'),
            'original_str'=>file_get_contents($_f),
            'markdown'=>true,
        ));
        $ctt .= $_txt;

        $params = array(
            'title'=>$this->trans('OOPS ! An error occurred !!'),
            'content'=>$ctt,
            'sitemap_url'=>CarteBlanche::getContainer()->get('router')->buildUrl(array(
                'controller'=>'cms','action'=>'sitemap'
            )),
            'report_error'=>CarteBlanche::getContainer()->get('router')->buildUrl(array(
                'controller'=>'error','action'=>'report','code'=>'500'
            ))
        );
        $params['output'] = CarteBlanche::getContainer()->get('front_controller')
            ->view(self::$views_dir.'error', $params);
        return CarteBlanche::getContainer()->get('front_controller')->render($params);
    }

}

// Endfile


<?php
/**
 * Class KeylistsServiceProvider
 *
 * @author Del
 */
namespace Delatbabel\Keylists;

use Delatbabel\Keylists\Console\Commands\LoadExchangeRates;
use Delatbabel\Keylists\Console\Commands\LoadISO3166Countries;
use Delatbabel\Keylists\Console\Commands\LoadTimezones;
use Delatbabel\Keylists\Console\Commands\LoadAUStates;
use Illuminate\Support\ServiceProvider;

/**
 * Class KeylistsServiceProvider
 *
 * Service providers are the central place of all Laravel application bootstrapping.
 * Your own application, as well as all of Laravel's core services are bootstrapped
 * via service providers.
 *
 * @see  Illuminate\Support\ServiceProvider
 * @link http://laravel.com/docs/5.1/providers
 */
class KeylistsServiceProvider extends ServiceProvider
{
    /** @var array list of commands to be registered in the service provider */
    protected $moreCommands = [
        LoadISO3166Countries::class,
        LoadTimezones::class,
        LoadExchangeRates::class,
        LoadAUStates::class,
    ];

    /**
     * Bootstrap the application events.
     *
     * This method is called after all other service providers have been registered,
     * meaning you have access to all other services that have been registered by
     * the framework.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__ . '/../database/migrations' => database_path() . '/migrations'
        ], 'migrations');
        $this->publishes([
            __DIR__ . '/../database/seeds' => database_path() . '/seeds'
        ], 'seeds');
        $this->publishes([
            __DIR__ . '/../config' => config_path()
        ], 'config');

        $this->commands($this->moreCommands);
    }

    /**
     * Register the service provider.
     *
     * Within the register method, you should only bind things into the service container.
     * You should never attempt to register any event listeners, routes, or any other piece
     * of functionality within the register method. Otherwise, you may accidentally use a
     * service that is provided by a service provider which has not loaded yet.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}


<?php
declare(strict_types=1);

namespace eXtalion\Component\Routing;

use eXtalion\Component\Routing\Exception\ControllerClassNotFound;
use eXtalion\Component\Routing\Exception\RouteNotValid;

/**
 * @author Damian Glinkowski <damianglinkowski@gmail.com>
 */
abstract class Route implements \IteratorAggregate
{
    /**
     * Uri path with parameters (if needed)
     *
     * Example:
     *     /
     *     /some/uri/path
     *     /some/{uri}/pl - uri is a parameter
     *
     * @var string
     */
    private $route;

    /**
     * Full namespace controller class
     *
     * @var string
     */
    private $controllerClass;

    /**
     * Controller class dependencies
     *
     * @var mixed[]
     */
    private $controllerClassDependencies;

    /**
     * @var \Closure[]
     */
    private $routeParametersOptions;

    /**
     * Separate route parts
     *
     * @var string[]
     */
    private $routeArray;

    /**
     * @var string[]
     */
    private $routeParameters;

    /**
     * Route method
     *
     * @var string
     */
    private $method;

    /**
     * @param string $route Uri path with parameters (if needed)
     * @param string $controllerClass
     * @param mixed[] $controllerClassDependencies
     * @param \Closure[] $routeParametersOptions
     */
    public function __construct(
        string $route,
        string $controllerClass,
        array $controllerClassDependencies = [],
        array $routeParametersOptions = []
    ) {
        $this->validRouet($route);
        $this->validControllerClass($controllerClass);

        $this->route = explode('?', $route)[0];
        $this->controllerClass = $controllerClass;
        $this->controllerClassDependencies = $controllerClassDependencies;
        $this->routeParametersOptions = $routeParametersOptions;

        $this->routeArray = explode('/', $this->route);
        array_shift($this->routeArray);
        $this->buildRouteParametersArray();

        $class = get_class($this);
        $this->method = strtolower(substr($class, strrpos($class, '\\') + 1));
    }

    private function validRouet(string $route): void
    {
        if ($route !== '' && $route[0] === '/') {
            $isRouteValid = filter_var(
                'http://example.com' . $route,
                FILTER_VALIDATE_URL,
                FILTER_FLAG_PATH_REQUIRED
            );
            if ($isRouteValid) {
                return;
            }
        }
        throw new RouteNotValid(
            'Route "' . $route . '" is not valid'
        );
    }

    private function validControllerClass(string $controllerClass): void
    {
        if (class_exists($controllerClass) === false) {
            throw new ControllerClassNotFound(
                'Controller class "' . $controllerClass . '" not found'
            );
        }
    }

    private function buildRouteParametersArray(): void
    {
        $this->routeParameters = [];
        foreach ($this->routeArray as $index => $part) {
            if ($part && $part[0] === '{' && $part[-1] === '}') {
                $this->routeParameters[$index] = trim($part, '{}');
            }
        }
    }

    public function __destruct()
    {
        $this->controllerClassDependencies = null;
        $this->routeParametersOptions = null;
    }

    /**
     * Gets route as string
     *
     * @return string
     */
    public function __toString(): string
    {
        return $this->route;
    }

    /**
     * @inheritDoc
     *
     * @return \Iterator of string
     */
    public function getIterator(): \Iterator
    {
        yield from $this->routeArray;
    }

    /**
     * Gets route method
     *
     * @return string
     */
    public function method(): string
    {
        return $this->method;
    }

    /**
     * Gets controller class object
     *
     * @return object New instance of $this->controllerClass
     */
    public function controller()
    {
        return new $this->controllerClass(
            ...$this->controllerClassDependencies
        );
    }

    /**
     * Extract parameters value from path
     *
     * @param string $path Uri path that match to route without query
     *
     * @return mixed[] Map parameter_name => value
     * @throws \Throwable If any route parameter option throw exception
     */
    public function extractParameters(string $path): array
    {
        if ($this->routeParameters === []) {
            return [];
        }
        $parameters = [];
        $pathArray = explode('/', $path);
        array_shift($pathArray);
        foreach ($this->routeParameters as $index => $parameter) {
            $parameterAction = $this->routeParametersOptions[$parameter] ??
                function (string $parameter): string {
                    return $parameter;
                };
            $parameters[$parameter] = $parameterAction($pathArray[$index]);
        }
        return $parameters;
    }
}


<?php

/*
 * This file is part of madewithlove/service-providers
 *
 * (c) madewithlove <heroes@madewithlove.be>
 *
 * For the full copyright and license information, please view the LICENSE
 */

namespace Madewithlove\ServiceProviders\Console;

use Interop\Container\ServiceProviderInterface;
use Madewithlove\ServiceProviders\Utilities\Alias;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;

class SymfonyConsoleServiceProvider implements ServiceProviderInterface
{
    /**
     * @var string
     */
    protected $name;

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

    /**
     * @var Command[]|string[]
     */
    protected $commands;

    /**
     * @param string             $name
     * @param string             $version
     * @param string[]|Command[] $commands
     */
    public function __construct($name = 'NAME', $version = 'VERSION', $commands = [])
    {
        $this->name = $name;
        $this->version = $version;
        $this->commands = $commands;
    }

    /**
     * {@inheritdoc}
     */
    public function getServices()
    {
        return [
            Application::class => [$this, 'getApplication'],
            'console' => new Alias(Application::class),
        ];
    }

    /**
     * @param ContainerInterface $container
     *
     * @return Application
     */
    public function getApplication(ContainerInterface $container)
    {
        $console = new Application();
        $console->setName($this->name);
        $console->setVersion($this->version);

        // Register commands
        foreach ($this->commands as $command) {
            $console->add(is_string($command) ? $container->get($command) : $command);
        }

        return $console;
    }
}


<?php namespace Ordercloud\Entities\Settings;

use JsonSerializable;
use Ordercloud\Support\Collection;

class SettingsCollection extends Collection implements JsonSerializable
{
    /**
     * @param SettingKeyShort $key The setting key
     *
     * @return Setting|null
     */
    public function getByKey(SettingKeyShort $key)
    {
        foreach ($this->all() as $setting) {
            if ($setting->getKey()->getId() == $key->getId() || $setting->getKey()->getName() == $key->getName()) {
                return $setting;
            }
        }

        return null;
    }

    /**
     * @param string $keyName The setting key name
     *
     * @return Setting|null
     */
    public function getByKeyName($keyName)
    {
        return $this->getByKey(new SettingKeyShort(null, $keyName));
    }

    /**
     * @param int $keyID The setting key ID
     *
     * @return Setting|null
     */
    public function getByKeyID($keyID)
    {
        return $this->getByKey(new SettingKeyShort($keyID, null));
    }

    /**
     * @param SettingKeyShort $key
     * @param mixed $default The default value to return if setting not found
     *
     * @return null|string
     */
    public function getValueByKey(SettingKeyShort $key, $default = null)
    {
        $setting = $this->getByKey($key);

        if (is_null($setting)) {
            return $default;
        }

        return $setting->getValue();
    }

    /**
     * @param string $keyName The setting key name
     * @param mixed $default The default value to return if setting not found
     *
     * @return string|null
     */
    public function getValueByKeyName($keyName, $default = null)
    {
        return $this->getValueByKey(new SettingKeyShort(null, $keyName), $default);
    }

    /**
     * @param int $keyID The setting key ID
     * @param mixed $default The default value to return if setting not found
     *
     * @return string|null
     */
    public function getValueByKeyID($keyID, $default = null)
    {
        return $this->getValueByKey(new SettingKeyShort($keyID, null), $default);
    }

    /**
     * @return Setting[]
     */
    public function all()
    {
        return parent::all();
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: Bartosz Gołek
 * Date: 09.11.13
 * Time: 15:30
 *
 * @package    Conpago
 * @subpackage Core
 * @author     Bartosz Gołek <bartosz.golek@gmail.com>
 * @copyright  Copyright (c) 2015, Bartosz Gołek
 */

namespace Conpago\Core;

use Conpago\Config\Contract\IAppConfig;
use Conpago\DI\IFactory;
use Conpago\Exceptions\ControllerNotFoundException;
use Conpago\Helpers\Contract\IRequestDataReader;
use Conpago\Presentation\Contract\IController;
use Conpago\Presentation\Contract\IControllerResolver;

/**
 * Class resolves controller based on request and configuration.
 */
class ControllerResolver implements IControllerResolver
{

    /**
     * Application configuration.
     *
     * @var \Conpago\Config\Contract\IAppConfig
     */
    private $appConfig;

    /**
     * Creates new instance of controller resolver.
     *
     * @param IRequestDataReader $requestDataReader   Request data access provider.
     * @param IAppConfig         $appConfig           Application configuration.
     * @param IFactory[]         $controllerFactories Collection of named controller factories.
     *
     * @inject Factory <\Conpago\Presentation\Contract\IController> $controllerFactories
     */
    public function __construct(
        IRequestDataReader $requestDataReader,
        IAppConfig $appConfig,
        array $controllerFactories
    ) {
        $this->controllerFactories = $controllerFactories;
        $this->requestDataReader   = $requestDataReader;
        $this->appConfig           = $appConfig;
    }

    /**
     * Gets controller instance.
     * Controller instance is produced with factory of name from request or default name from configuration.
     *
     * @return IController Instance of produced controller.
     *
     * @throws ControllerNotFoundException If factory with given name does not exists.
     */
    public function getController()
    {
        $params         = $this->requestDataReader->getRequestData()->getParameters();
        $controllerName = $this->appConfig->getDefaultInteractor();

        if (isset($params['interactor'])) {
            $controllerName = $params['interactor'];
        };

        $controllerArrayKey = $controllerName.'Controller';

        if (!array_key_exists($controllerArrayKey, $this->controllerFactories)) {
            throw new ControllerNotFoundException('Controller \''.$controllerName.'\' not found.');
        }

        return $this->controllerFactories[$controllerArrayKey]->createInstance();
    }

    /**
     *  Collection of named controller factories.
     *
     * @var IFactory[]
     */
    protected $controllerFactories;

    /**
     * Request data access provider.
     *
     * @var IRequestDataReader
     */
    private $requestDataReader;
}


<?php
namespace Li;
// how to use
// $gridview = GridView::init($this, $model,
//     array(
//         'columns'=>array(
//             array(
//                 'name'=>'id',
//                 'alias'=>'id',
//                 'filter'=>true,
//             ),
//             array(
//                 'name'=>'created',
//                 'alias'=>'created',
//                 'filter'=>array(
//                     '1'=>1,
//                     '2'=>2),
//                 'value'=>'date("Y-m-d",$data["created"])'
//             ),
//             array(
//                 'name'=>'updated',
//                 'alias'=>'updated',
//                 'filter'=>true,
//                 'options'=>array(
//                     'class'=>'gridview-datepicker',
//                 ),
//                 'value'=>'date("Y-m-d",$data["updated"])'
//             ),
//             array(
//                 'alias'=>'操作',
//                 'buttons'=>array(
//                     array(
//                         'name'=>'编辑',
//                         'action'=>'update',
//                     ),
//                     array(
//                         'name'=>'删除',
//                         'action'=>'delete',
//                     ),
//                     array(
//                         'name'=>'test',
//                         'action'=>'test',
//                         'options'=>array(
//                             // 'class'=>'btn btn-default btn-xm',
//                             'style'=>'color:red;',
//                         ),
//                     ),
//                 )
//             ),
//         ),
//         'criteria'=>array(
//             'pageSize'=>2,
//             'order'=>'id desc'
//         )
//     )
// );

class GridView {
    public $controller;
    public $model;
    public $columns;
    public $criteria;

    public $pagination;
    // public $order;
    public $reset;
    public $params = [
        'filter'=>true,
        'columns'=>[],
        'criteria'=>[],
    ];

    public $dataProvider;

    // 全局控制筛选
    public $filter=true;

    /**
     * init gridview
     * @param $controller mixed current controller instance
     * @param $model mixed current model instance
     * @param $params mixed gridview params
     *
     * @return mixed the gridview
     */
    static public function init($controller, $dataProvider, $params=array()) {
        return new self($controller, $dataProvider, $params);
    }

    public function __construct($controller, $dataProvider, $params=null) {
        $this->params=array_merge($this->params,$params);

        $this->criteria=$this->params['criteria'];
        $this->reset = $controller->url();
        $this->dataProvider = $dataProvider;
        $this->controller = $controller;
        $this->columns = $this->getColumns();
        $this->data = $this->getData();
        $this->pagination =  $this->dataProvider->getPagination();

    }

    public function getColumns() {
        $columns = [];
        if(empty($this->params['columns'])) {
            $cols = $this->dataProvider->model->alias();
            foreach($cols as $key => $value) {
                $tmp['name'] = $key;
                $tmp['alias'] = $value;
                $tmp['filter'] = true;

                $columns[] = $tmp;
            }

            $columns[] = array(
                'alias'=>'操作',
                'buttons'=>array(
                    array(
                        'name'=>'编辑',
                        'action'=>'update',
                    ),
                    array(
                        'name'=>'删除',
                        'action'=>'delete',
                        'htmlOptions'=>array(
                            'class'=>'gridview-delete',
                        ),
                    ),
                )
            );
        } else {
            foreach($this->params['columns'] as $value) {
                $column = [];
                $column['filter'] = true;
                if(isset($value['value'])) {
                    $column['value'] = $value['value'];
                }
                if (isset($value['buttons'])) {
                    $column['name'] = '';
                    $column['type'] = 'buttons';
                    $column['buttons'] = $value['buttons'];
                    $column['alias'] = $value['alias'];
                }
                if (!is_array($value)) {
                    $column['name'] = $value;
                } else if( isset($value['name']) ) {
                    $column['name'] = $value['name'];
                    if(isset($value['filter'])) {
                        $column['filter'] = $value['filter'];
                    }
                }

                if (!isset($value['alias'])) {
                    // debug($this->dataProvider);die;
                    if($this->dataProvider instanceof DataProvider && isset($this->dataProvider->model->alias()[$column['name']]))
                        $column['alias'] = $this->dataProvider->model->alias()[$column['name']];
                    else
                        $column['alias'] = $column['name'];
                } else {
                    $column['alias'] = '';
                }

                $column['htmlOptions']=$this->_getOptions(isset($value['options'])?$value['options']:null);
                $columns[] = $column;
            }
        }

        return $columns;
    }

    /**
     * 获得criteria并且合并已知条件
     * @param $criteria array
     * @return array
     */
    // private function _getCriteria($criteria=array())
    // {
    //     if(!empty($_GET))
    //     {
    //         if(empty($criteria))
    //         {
    //             foreach($_GET as $key=>$value)
    //             {
    //                 if(!empty($value) && $key != $this->pagination->pageVar)
    //                 {
    //                     $criteria['condition'][$key]=$value;
    //                 }
    //             }
    //         }
    //         else
    //         {
    //             foreach($_GET as $key=>$value)
    //             {
    //                 if(!empty($value) && $key != $this->pagination->pageVar && !isset($criteria['condition'][$key]))
    //                 {
    //                     $criteria['condition'][$key]=$value;
    //                 }
    //             }
    //         }
    //     }

    //     return $criteria;
    // }

    /**
     * get Pagination
     * @return mixed the Pagination instance
     */
    // public function getPagination()
    // {
    //     return new Pagination($this->model,$this->criteria);
    // }

    /**
     * get data
     * @return array the gridview data
     */

    public function getData() {
        $data = $this->dataProvider->getData();
        unset($value);
        foreach($data as &$value) {
            foreach($this->columns as $column) {
                // 自定义value
                if(isset($column['value'])) {
                    $value->$column['name'] = $this->evaluateExpression($column['value'],array('data'=>$value));
                } elseif(isset($column['buttons']) && is_array($column['buttons'])) {
                    $value->{'__BUTTONS_HTML__'} = $this->_getButtons($column['buttons'],$value);
                }
            }
        }
        return $data;
    }

    /**
     * get button html code
     * @param $buttons array the button array
     * @param $row array current row data
     * @return string the html code of button
     */
    private function _getButtons($buttons, $row) {
        $html = '';
        foreach($buttons as $value) {
            if(isset($value['audit']) && $value['audit']($row) == 0) {
                continue;
            }
            $tmp='evaluateExpression($value['url'], array('data'=>$row));
            } elseif(isset($value['action'])) {
                $value['options']['class']='gridview-'.$value['action'];
                $tmp.=url().'/'.$this->controller->id.'/'.$value['action'].'?id='.$row['id'].'&from='.urlencode($_SERVER['REQUEST_URI']);
            }
            $tmp .= '"';
            if (isset($value['options']) && is_array($value['options']) && !empty($value['options'])) {
                $tmp.=$this->_getOptions($value['options']);
            }
            $tmp.='">'.$value['name'].'  ';

            $html.=$tmp;
        }

        return $html;
    }

    /**
     * get item option html code
     * @param $options array html options
     * @return string the html code of options
     */
    private function _getOptions($options) {
        $optionsHtml='';
        if (!empty($options)) {
            if(is_array($options)) {
                foreach($options as $key => $value) {
                    $optionsHtml.=' '.$key.'="'.$value.'"';
                }
            } else {
                $optionsHtml=' class="'.$options.'"';
            }
        }
        return $optionsHtml;
    }

    /**
     * Evaluates a PHP expression.
     *
     * @param mixed $_expression_ a PHP expression or PHP callback to be evaluated.
     * @param array $_data_ additional parameters to be passed to the above expression/callback.
     * @return mixed the expression result
     */
    public function evaluateExpression($_expression_, $_data_) {
        // debug($_data_);
        // debug($_expression_);
        // die;
        if (is_string($_expression_)) {
            extract($_data_);
            return eval('return '.$_expression_.';');
        } else {
            $_data_[]=$this;
            return call_user_func_array($_expression_, $_data_);
        }
    }
}