<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Filter
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Encrypt.php 24593 2012-01-05 20:35:02Z matthew $
 */

/**
 * @see Zend_Filter_Encrypt
 */

/**
 * Encrypts a given file and stores the encrypted file content
 *
 * @category   Zend
 * @package    Zend_Filter
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Filter_File_Encrypt extends Zend_Filter_Encrypt
{
    /**
     * New filename to set
     *
     * @var string
     */
    protected $_filename;

    /**
     * Returns the new filename where the content will be stored
     *
     * @return string
     */
    public function getFilename()
    {
        return $this->_filename;
    }

    /**
     * Sets the new filename where the content will be stored
     *
     * @param  string $filename (Optional) New filename to set
     * @return Zend_Filter_File_Encryt
     */
    public function setFilename($filename = null)
    {
        $this->_filename = $filename;
        return $this;
    }

    /**
     * Defined by Zend_Filter_Interface
     *
     * Encrypts the file $value with the defined settings
     *
     * @param  string $value Full path of file to change
     * @return string The filename which has been set, or false when there were errors
     */
    public function filter($value)
    {
        if (!file_exists($value)) {

            throw new Zend_Filter_Exception("File '$value' not found");
        }

        if (!isset($this->_filename)) {
            $this->_filename = $value;
        }

        if (file_exists($this->_filename) and !is_writable($this->_filename)) {

            throw new Zend_Filter_Exception("File '{$this->_filename}' is not writable");
        }

        $content = file_get_contents($value);
        if (!$content) {

            throw new Zend_Filter_Exception("Problem while reading file '$value'");
        }

        $encrypted = parent::filter($content);
        $result    = file_put_contents($this->_filename, $encrypted);

        if (!$result) {

            throw new Zend_Filter_Exception("Problem while writing file '{$this->_filename}'");
        }

        return $this->_filename;
    }
}


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

use InvalidArgumentException;

use function strlen;

/**
 * Represents a password
 *
 * @property-read  string  $raw
 *
 * @author    Corey Frenette
 * @copyright Copyright (c) 2019, BapCat
 */
class Password extends Value {
  /** @var  string  $raw  The raw password */
  private $raw;

  /**
   * @param  string  $password  The raw password to wrap
   */
  public function __construct($password) {
    $this->validate($password);

    $this->raw = $password;
  }

  /**
   * Ensures the password is valid
   *
   * @throws  InvalidArgumentException  If the password is not valid
   *
   * @param  string  $password  The password to validate
   *
   * @return  void
   */
  private function validate($password): void {
    if(strlen($password) < $this->validationMinLength()) {
      throw new InvalidArgumentException("The password must be at least {$this->validationMinLength()} characters long");
    }

    if(strlen($password) > $this->validationMaxLength()) {
      throw new InvalidArgumentException("The password must be no more than {$this->validationMaxLength()} characters long");
    }
  }

  /**
   * Used for validation, the minimum length a password can be
   *
   * @return  int  The minimum password length
   */
  protected function validationMinLength(): int {
    return 8;
  }

  /**
   * Used for validation, the maximum length a password can be
   *
   * @return  int  The maximum password length
   */
  protected function validationMaxLength(): int {
    return 56; // BCrypt limitation
  }

  /**
   * Converts this object to a string
   *
   * @return  string  A string representation of this object
   */
  public function __toString(): string {
    return $this->raw;
  }

  /**
   * Converts this object to a json encodable-form
   *
   * @return  string  A representation of this object suitable for encoding
   */
  public function jsonSerialize(): string {
    return $this->raw;
  }

  /**
   * Gets the raw value this object wraps
   *
   * @return  string  The raw value this object wraps
   */
  protected function getRaw(): string {
    return $this->raw;
  }
}


<?php

namespace Colorium\Http\Request;

class Accept
{

    /** @var array */
    public $medias = [];

    /** @var array */
    public $languages = [];

    /** @var array */
    public $encodings = [];

    /** @var array */
    public $charsets = [];

    /**
     * Custom HTTP Accept
     *
     * @param array $medias
     * @param array $languages
     * @param array $encodings
     * @param array $charsets
     */
    public function __construct(array $medias = [], array $languages = [], array $encodings = [], array $charsets = [])
    {
        $this->medias = $medias;
        $this->language = $languages;
        $this->encoding = $encodings;
        $this->charset = $charsets;
    }

    /**
     * Negociate media
     *
     * @param string $compare
     * @return string
     */
    public function media($compare = null)
    {
        return $compare
            ? static::compare($compare, $this->medias)
            : reset($this->medias);
    }

    /**
     * Negociate language
     *
     * @param string $compare
     * @return string
     */
    public function language($compare = null)
    {
        return $compare
            ? static::compare($compare, $this->languages)
            : reset($this->languages);
    }

    /**
     * Negociate encoding
     *
     * @param string $compare
     * @return string
     */
    public function encoding($compare = null)
    {
        return $compare
            ? static::compare($compare, $this->encodings)
            : reset($this->encodings);
    }

    /**
     * Negociate charset
     *
     * @param string $compare
     * @return string
     */
    public function charset($compare = null)
    {
        return $compare
            ? static::compare($compare, $this->charsets)
            : reset($this->charsets);
    }

    /**
     * Parse from strings
     *
     * @param string $accept
     * @param string $acceptLanguage
     * @param string $acceptEncoding
     * @param string $acceptCharset
     *
     * @return static
     */
    public static function from($accept = null, $acceptLanguage = null, $acceptEncoding = null, $acceptCharset = null)
    {
        $medias = static::parse($accept, '/');
        $languages = static::parse($acceptLanguage, '-');
        $encodings = static::parse($acceptEncoding);
        $charsets = static::parse($acceptCharset);

        return new static($medias, $languages, $encodings, $charsets);
    }

    /**
     * Accept string parsing
     *
     * @param string $string
     * @param string $separator
     * @return array
     */
    protected static function parse($string, $separator = null)
    {
        $items = [];
        if($string) {
            $string = strtolower(str_replace(' ', '', $string));
            $rows = explode(',', $string);
            foreach($rows as $row) {
                @list($item, $quality) = explode(';q=', $row);
                if(!$quality) {
                    if($separator) {
                        @list($part, $subpart) = explode($separator, $item);
                        $quality = ($part = '*' or $subpart == '*') ? 0 : 1;
                    }
                    else {
                        $quality = ($item == '*') ? 0 : 1;
                    }
                }
                $items[$item] = (float)$quality;
            }
            sort($items);
            $items = array_keys($items);
        }

        return $items;
    }

    /**
     * Compare for negociation
     *
     * @param string $needle
     * @param array $haystack
     * @return bool
     */
    protected static function compare($needle, array $haystack)
    {
        foreach($haystack as $row) {
            if(fnmatch($row, $needle)) {
                return true;
            }
        }
        return false;
    }

}


<?php
/**
 * @file
 * Information about the shape and structure of Earth along with general Earth helper mathods.
 */

namespace Lootils\Geo;

/**
 * Information about the shape of the Earth.
 */
class Earth {

  /**
   * The distance is in meters.
   */
  public function earthRadiusSemimajor() {
    return 6378137.0;
  }

  public function earthEccentricitySq() {
    return 2 * $this->earthFlattening() - pow($this->earthFlattening(), 2);
  }

  public function earthFlattening() {
    return 1 / 298.257223563;
  }

  public function earthRadiusSemiminor() {
    return ($this->earthRadiusSemimajor() * (1 - $this->earthFlattening()));
  }

  /**
   * Get the radius of the Earth at a specific latitude.
   *
   * @param float $latitude
   *   The latitude at which to get the radius of the Earth.
   *
   * @return float
   *   The radius of the Earth at this latitude in meters.
   */
  public function earthRadius($latitude) {
    $radLat = deg2rad($latitude);

    $x = cos($radLat) / $this->earthRadiusSemimajor();
    $y = sin($radLat) / $this->earthRadiusSemiminor();

    return 1 / (sqrt($x * $x + $y * $y));
  }

  /**
   * Convert a coordinate into Degree Minute Second format.
   *
   * @param float $coordinate
   *   The coordinate in decimal format to convert.
   *
   * @return array
   *   An array with the keys degrees, minutes, and seconds
   */
  public function convertDecToDMS($coordinate) {

    $dms = array();
    $parts = explode('.', $coordinate);

    // The degrees portion.
    $dms['degrees'] = $parts[0];

    // Calculate the minutes
    $temp = ("0." . $parts[1]) * 3600;
    $dms['minutes'] = floor($temp / 60);

    // Find the seconds left over
    $dms['seconds'] = $temp - ($dms['minutes'] * 60);

    return $dms;
  }

  /**
   * Convert Degrees Minutes Seconds to Decimal for a coordinate.
   *
   * @param int $degrees
   * @param int $minutes
   * @param float $seconds
   *
   * @return float
   *   The coordinate in decimal format.
   */
  public function convertDMStoDec($degrees, $minutes, $seconds) {
    if ($degrees < 0) {
      return $degrees - ((($minutes * 60) + $seconds) / 3600);
    }

    return $degrees + ((($minutes * 60) + $seconds) / 3600);
  }

  /**
   * Convert meters to nautical miles.
   *
   * @see https://en.wikipedia.org/wiki/Nautical_mile
   *
   * @param float $meters
   *   A distance in meters.
   *
   * @return float
   *   The same distance in nautical miles.
   */
  public function convertMetersToNauticalMiles($meters) {
    return $meters / 1852;
  }

  /**
   * Convert nautical miles to meters.
   *
   * @param float $nm
   *   A distance in nautical miles.
   *
   * @return float
   *   The same distance in meters.
   */
  public function convertNauticalMilesToMeters($nm) {
    return $nm * 1852;
  }

}


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

use \CarteBlanche\CarteBlanche;
use \CarteBlanche\Interfaces\CarteBlancheExceptionInterface;
use \DevDebug\ErrorException as BaseErrorException;

/**
 * Special application error handler
 *
 * To use it, write something like :
 *
 *     trigger_error( 'Error info', E_USER_ERROR|E_USER_WARNING|E_USER_NOTICE );
 *
 * All error exceptions are written in the logs (by default in the "error.log" file)
 * except if `app.modes._APP_MODE.log_errors=false`
 *
 * @author      Piero Wbmstr <me@e-piwi.fr>
 */
class ErrorException
    extends BaseErrorException
    implements CarteBlancheExceptionInterface
{

    /**
     * Construction of the exception - a message is needed (1st argument)
     *
     * @param   string  $message    The exception message
     * @param   int     $code       The exception code
     * @param   int     $severity
     * @param   string  $filename
     * @param   int     $lineno
     * @param   mixed   $previous
     */
    public function __construct(
        $message, $code = 0, $severity = 1, $filename = __FILE__, $lineno = __LINE__, $previous = null
    ) {
        // kernel configuration data
        $mode_data = CarteBlanche::getKernelMode(true);

        // parent constructor
        if (!is_array($mode_data)
            || !isset($mode_data['debug'])
            || false==$mode_data['debug']) {
                parent::__construct($message, $code, $severity, $filename, $lineno, $previous, true);
        } else {
            parent::__construct($message, $code, $severity, $filename, $lineno, $previous, false);
        }

        // log?
        if (is_array($mode_data)
            && isset($mode_data['log_errors'])
            && true==$mode_data['log_errors']) {
                $this->log();
        }
    }

    /**
     * Render the Exception as string
     *
     * @return string
     */
    public function __toString()
    {
        $mode_data = CarteBlanche::getKernelMode(true);
        if (!is_array($mode_data)
            || !isset($mode_data['debug'])
            || false==$mode_data['debug']) {
                return $this->productionRendering();
        } else {
            return $this->debugRendering();
        }
    }

    /**
     * Render of a production error
     *
     * @return string
     */
    public function productionRendering()
    {
        $args   = array('message'=>$this->getAppMessage());
        $ft     = CarteBlanche::getContainer()->get('front_controller');
        return ($ft ? $ft->renderProductionError($args, 500) : parent::__toString());
    }

    /**
     * Render of a debug error
     *
     * @return string
     */
    public function debugRendering()
    {
        $args   = array('message'=>$this->getAppMessage());
        $ft     = CarteBlanche::getContainer()->get('front_controller');
        return ($ft ? $ft->renderError($args, $this) : parent::__toString());
    }

    /**
     * Log the exception in `history.log`
     *
     * @return void
     */
    public function log()
    {
        CarteBlanche::log(
            $this->getAppMessage()."\n".$this->getTraceAsString(),
            \Library\Logger::ERROR
        );
    }

    /**
     * Get the CarteBlanche information string about an Exception
     *
     * @return string
     */
    public function getAppMessage()
    {
        return sprintf('[%s] "%s" (%d)', get_class($this), $this->getMessage(), $this->getCode());
    }

}

// Endfile


<?php namespace Mvalim\PackageUtils\Console;

use Illuminate\Console\Command;
use Mvalim\PackageUtils\Container;
use SebastianBergmann\Exporter\Exception;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class Publish extends Command {

	/**
	 * The console command name.
	 *
	 * @var string
	 */
	protected $name = 'package:publish';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Publish resources from a package.';

	/**
	 * @var Container
	 */
	protected $container;

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

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function fire()
	{
		$packageName = $this->argument('package');

		$this->container = $this->getLaravel()->make('Mvalim\PackageUtils\Container');
		$this->container->setCommand($this);
		$package = $this->container->package($packageName);

		$resource = $this->argument('resource');
		$allPublishers = $resource ? [$package->getPublisher($resource)] : $package->getPublishers();

		foreach($allPublishers as $key => $publisher) {
			$this->line('');
			$this->line('<fg=cyan>Publishing ' . str_plural($resource ?: $key) . ' for package ' . $packageName . '</fg=cyan>');
			try {
				$publisher->publish($this->option('force'));
			} catch(\Exception $e) {
				$this->error("\n" . $e->getMessage());
				return;
			}
		}
		$this->line('');
		$this->line("<info>Done:</info> Resource(s) from <fg=cyan>{$packageName}</fg=cyan> published");
	}

	/**
	 * Get the console command arguments.
	 *
	 * @return array
	 */
	protected function getArguments()
	{
		return [
			['package', InputArgument::REQUIRED, 'The package name.'],
			['resource', InputArgument::OPTIONAL, 'What to to publish? (optional, if none is given will execute all registered publishers)'],
		];
	}

	/**
	 * Get the console command options.
	 *
	 * @return array
	 */
	protected function getOptions()
	{
		return [
			['force', null, InputOption::VALUE_NONE, 'Make a backup of the existing files, and overwrite them.'],
		];
	}

}


<?php

namespace Behavior;

use Think\Behavior;

/**
 * 运行时间信息显示
 */
final class ShowRuntimeBehavior extends Behavior
{

    /**
     * 执行入口
     *
     * @param mixed $content
     */
    public function run(&$content)
    {
        if (C('SHOW_RUN_TIME')) {
            if (false !== strpos($content, '{__NORUNTIME__}')) {
                $content = str_replace('{__NORUNTIME__}', '', $content);
            } else {
                $runtime = $this->showTime();
                if (strpos($content, '{__RUNTIME__}')) {
                    $content = str_replace('{__RUNTIME__}', $runtime, $content);
                } else {
                    $content .= $runtime;
                }
            }
        } else {
            $content = str_replace(['{__NORUNTIME__}', '{__RUNTIME__}'], '', $content);
        }
    }

    /**
     * 显示运行时间、数据库操作、缓存次数、内存使用信息

     * @return string
     */
    private function showTime()
    {
        // 显示运行时间
        G('beginTime', $GLOBALS['_beginTime']);
        G('viewEndTime');
        $showTime = 'Process: '.G('beginTime', 'viewEndTime').'s ';
        if (C('SHOW_ADV_TIME')) {
            // 显示详细运行时间
            $showTime .= '( Load:'.G('beginTime', 'loadTime').'s Init:'.G('loadTime', 'initTime').'s Exec:'.G(
                    'initTime',
                    'viewStartTime'
                ).'s Template:'.G('viewStartTime', 'viewEndTime').'s )';
        }
        if (C('SHOW_DB_TIMES')) {
            // 显示数据库操作次数
//                $showTime .= ' | DB :' . N('db_query') . ' queries ' . N('db_write') . ' writes ';
        }
        if (C('SHOW_CACHE_TIMES')) {
            // 显示缓存读写次数
//                $showTime .= ' | Cache :' . N('cache_read') . ' gets ' . N('cache_write') . ' writes ';
        }
        if (MEMORY_LIMIT_ON && C('SHOW_USE_MEM')) {
            // 显示内存开销
            $showTime .= ' | UseMem:'.number_format((memory_get_usage() - $GLOBALS['_startUseMems']) / 1024).' kb';
        }
        if (C('SHOW_LOAD_FILE')) {
            $showTime .= ' | LoadFile:'.count(get_included_files());
        }
        if (C('SHOW_FUN_TIMES')) {
            $fun = get_defined_functions();
            $showTime .= ' | CallFun:'.count($fun['user']).','.count($fun['internal']);
        }

        return $showTime;
    }
}


<?php
/**
 * Абстрактная сущность
 *
 * @version ${product.version}
 *
 * @copyright 2011, Михаил Красильников <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
 */

/**
 * Абстрактная сущность
 *
 * @package ORM
 * @since 1.00
 */
abstract class ORM_Entity
{
    /**
     * Состояние сущности: новый объект
     * @since 3.00
     */
    const IS_NEW = 1;

    /**
     * Состояние сущности: объект соответствует записи в БД
     * @since 3.00
     */
    const IS_PERSISTENT = 2;

    /**
     * Состояние сущности: в объекте есть изменения, несохранённые в БД
     * @since 3.00
     */
    const IS_DIRTY = 3;

    /**
     * Состояние сущности: объект удалён из БД
     * @since 3.00
     */
    const IS_DELETED = 4;

    /**
     * Таблица, где хранится этот объект
     *
     * @var ORM_Table
     */
    private $table;

    /**
     * Состояние сущности
     * @var int
     *
     * @since 3.00
     */
    private $state = self::IS_NEW;

    /**
     * Необработанные значения свойств (значения PDO)
     *
     * По мере обращения к свойствам сущности, эти значения трансформируются в значения ORM и
     * помещаются в {@link $ormValues}.
     *
     * @var array
     */
    private $pdoValues = array();

    /**
     * Кэш значений свойств, приведённых к типам ORM
     *
     * @var array
     */
    private $ormValues = array();

    /**
     * Конструктор
     *
     * @param array $pdoValues  исходные PDO-значения полей
     *
     * @return ORM_Entity
     *
     * @since 1.00
     */
    public function __construct(array $pdoValues = array())
    {
        $this->table = ORM::getManager()->getTableByEntityClass(get_class($this));
        $columns = $this->getTable()->getColumns();
        foreach ($pdoValues as $name => $value)
        {
            if (!array_key_exists($name, $columns))
            {
                continue;
            }
            if ($columns[$name]->isVirtual())
            {
                continue;
            }
            $this->pdoValues[$name] = $value;
        }
        if ($this->getPrimaryKey() !== null)
        {
            $this->setEntityState(self::IS_PERSISTENT);
        }
    }

    /**
     * "Магический" метод для доступа к свойствам объекта
     *
     * Если есть геттер (метод, имя которого состоит из префикса "get" и имени свойства), вызывает
     * его для получения значения. В противном случае вызывает {@link getPdoValue}.
     *
     * Результат метода кэшируется.
     *
     * @param string $property  имя свойства
     *
     * @return mixed  ORM-значение свойства
     *
     * @uses getPdoValue()
     * @since 1.00
     */
    public function __get($property)
    {
        if (!array_key_exists($property, $this->ormValues))
        /*
         * Если значение PDO запрошенного свойства ещё трансформировано в значение ORM, делаем
         * это сейчас.
         */
        {
            $pdoValue = $this->getPdoValue($property);

            $getter = 'get' . $property;
            if (method_exists($this, $getter))
            {
                $ormValue = $this->$getter($pdoValue);
            }
            else
            {
                $table = $this->getTable();
                $columns = $table->getColumns();
                if (array_key_exists($property, $columns))
                {
                    if (null === $pdoValue && $columns[$property]->isVirtual())
                    {
                        $pdoValue = $columns[$property]->evaluateVirtualValue($this);
                    }
                    $ormValue = $columns[$property]->pdo2orm($pdoValue);
                }
                else
                {
                    $ormValue = $pdoValue;
                }
            }
            $this->ormValues[$property] = $ormValue;
        }
        return $this->ormValues[$property];
    }

    /**
     * "Магический" метод для установки свойств объекта
     *
     * Если есть сеттер (метод, имя которого состоит из префикса "set" и имени свойства), вызывает
     * его для установки значения. В противном случае вызывает {@link setOrmValue()}.
     *
     * @param string $property  имя свойства
     * @param mixed  $value     ORM-значение
     *
     * @return void
     *
     * @uses setPdoValue()
     * @since 1.00
     */
    public function __set($property, $value)
    {
        $setter = 'set' . $property;
        if (method_exists($this, $setter))
        {
            unset($this->ormValues[$property]);
            $this->$setter($value);
        }
        else
        {
            $this->setOrmValue($property, $value);
        }
        if ($this->getEntityState() == self::IS_PERSISTENT)
        {
            $this->setEntityState(self::IS_DIRTY);
        }
    }

    /**
     * Возвращает таблицу этой сущности
     *
     * @return ORM_Table
     *
     * @since 1.00
     */
    public function getTable()
    {
        return $this->table;
    }

    /**
     * Возвращает состояние объекта
     *
     * См. константы ORM_Entity::IS_…
     *
     * @return int
     *
     * @since 3.00
     */
    public function getEntityState()
    {
        return $this->state;
    }

    /**
     * Задаёт состояние объекта
     *
     * @param int $state  новое состояние (см. константы ORM_Entity::IS_…)
     *
     * @since 3.00
     */
    protected function setEntityState($state)
    {
        $this->state = intval($state);
    }

    /**
     * Возвращает значение основного ключа для этого объекта
     *
     * @return mixed
     *
     * @since 3.00
     */
    public function getPrimaryKey()
    {
        return $this->{$this->getTable()->getPrimaryKey()};
    }

    /**
     * Возвращает PDO-значение свойства
     *
     * Сначала метод пытается получить значение из {@link $ormValues}, если там значения нет, то
     * из {@link $pdoValues}.
     *
     * @param string $property  имя свойства
     *
     * @return mixed  PDO-значение свойства
     *
     * @since 3.00
     */
    public function getPdoValue($property)
    {
        if (array_key_exists($property, $this->ormValues))
        {
            $value = $this->getOrmValue($property);
            $columns = $this->getTable()->getColumns();
            if (array_key_exists($property, $columns))
            {
                $value = $columns[$property]->orm2pdo($value);
            }
        }
        else
        {
            $value = array_key_exists($property, $this->pdoValues)
                ? $this->pdoValues[$property]
                : null;
        }
        return $value;
    }

    /**
     * Устанавливает PDO-значение свойства
     *
     * При этом удаляется значение этого свойства из {@link $ormValues}.
     *
     * @param string $property  имя свойства
     * @param mixed  $value     PDO-значение
     *
     * @return void
     *
     * @since 3.00
     */
    public function setPdoValue($property, $value)
    {
        $this->pdoValues[$property] = $value;
        unset($this->ormValues[$property]);
    }

    /**
     * Возвращает ORM-значение свойства
     *
     * @param string $property  имя свойства
     *
     * @return mixed  ORM-значение свойства
     *
     * @since 3.00
     */
    public function getOrmValue($property)
    {
        return array_key_exists($property, $this->ormValues) ? $this->ormValues[$property] : null;
    }

    /**
     * Устанавливает ORM-значение свойства
     *
     * @param string $property  имя свойства
     * @param mixed  $value     ORM-значение
     *
     * @return void
     *
     * @since 3.00
     */
    public function setOrmValue($property, $value)
    {
        $this->ormValues[$property] = $value;
    }

    /**
     * Вызывается перед изменением в БД
     *
     * @param ezcQuery $query  запрос, который будет выполнен для сохранения записи
     *
     * @return ezcQuery
     *
     * @since 1.00
     */
    public function beforeSave(ezcQuery $query)
    {
        return $query;
    }

    /**
     * Вызывается после записи изменений в БД
     *
     * @return void
     *
     * @since 1.00
     */
    public function afterSave()
    {
        foreach ($this->getTable()->getColumns() as $column)
        {
            $column->afterEntitySave($this);
        }
        $this->setEntityState(self::IS_PERSISTENT);
    }

    /**
     * Вызывается перед удалением записи из БД
     *
     * @param ezcQuery $query  запрос, который будет выполнен для удаления записи
     *
     * @return void
     *
     * @since 1.00
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function beforeDelete(ezcQuery $query)
    {
    }

    /**
     * Вызывается после удаления записи из БД
     *
     * @return void
     *
     * @since 1.00
     */
    public function afterDelete()
    {
        foreach ($this->getTable()->getColumns() as $key => $column)
        {
            $column->afterEntityDelete($this, $key);
        }
        $this->setEntityState(self::IS_DELETED);
    }
}


<?php

namespace Reaction\Console\Controllers;

use Reaction;
use Reaction\Console\Exception;
use Reaction\Db\DatabaseInterface;
use Reaction\Helpers\FileHelperAsc;
use Reaction\Promise\ExtendedPromiseInterface;
use Reaction\Db\Query;
use Reaction\DI\Instance;
use Reaction\Helpers\Console;
use Reaction\Helpers\FileHelper;
use Reaction\Helpers\VarDumper;
use Reaction\I18n\GettextPoFile;
use Reaction\Promise\Promise;
use function Reaction\Promise\resolve;
use function Reaction\Promise\reject;
use function Reaction\Promise\all;
use function Reaction\Promise\allInOrder;
use Reaction\RequestApplicationInterface;

/**
 * Extracts messages to be translated from source files.
 *
 * The extracted messages can be saved the following depending on `format`
 * setting in config file:
 *
 * - PHP message source files.
 * - ".po" files.
 * - Database.
 *
 * Usage:
 * 1. Create a configuration file using the 'message/config' command:
 *    console message/config /path/to/myapp/messages/config.php
 * 2. Edit the created config file, adjusting it for your web application needs.
 * 3. Run the 'message/extract' command, using created config:
 *    console message /path/to/myapp/messages/config.php
 */
class MessageController extends Reaction\Console\Routes\Controller
{
    /**
     * @var string controller default action ID.
     */
    public $defaultAction = 'extract';
    /**
     * @var string required, root directory of all source files.
     */
    public $sourcePath = '@reaction';
    /**
     * @var string required, root directory containing message translations.
     */
    public $messagePath = '@reaction/Messages';
    /**
     * @var array required, list of language codes that the extracted messages
     * should be translated to. For example, ['zh-CN', 'de'].
     */
    public $languages = [];
    /**
     * @var string|array the name of the function for translating messages.
     * Defaults to 'Reaction::t'. This is used as a mark to find the messages to be
     * translated. You may use a string for single function name or an array for
     * multiple function names.
     */
    public $translator = ['Reaction::t', 'Reaction::tp', '$this->app->t', '$app->t'];
    /**
     * @var bool whether to sort messages by keys when merging new messages
     * with the existing ones. Defaults to false, which means the new (untranslated)
     * messages will be separated from the old (translated) ones.
     */
    public $sort = false;
    /**
     * @var bool whether the message file should be overwritten with the merged messages
     */
    public $overwrite = true;
    /**
     * @var bool whether to remove messages that no longer appear in the source code.
     * Defaults to false, which means these messages will NOT be removed.
     */
    public $removeUnused = false;
    /**
     * @var bool whether to mark messages that no longer appear in the source code.
     * Defaults to true, which means each of these messages will be enclosed with a pair of '@@' marks.
     */
    public $markUnused = true;
    /**
     * @var array list of patterns that specify which files/directories should NOT be processed.
     * If empty or not set, all files/directories will be processed.
     * See helpers/FileHelper::findFiles() description for pattern matching rules.
     * If a file/directory matches both a pattern in "only" and "except", it will NOT be processed.
     */
    public $except = [
        '.svn',
        '.git',
        '.gitignore',
        '.gitkeep',
        '.hgignore',
        '.hgkeep',
        '/messages',
    ];
    /**
     * @var array list of patterns that specify which files (not directories) should be processed.
     * If empty or not set, all files will be processed.
     * See helpers/FileHelper::findFiles() description for pattern matching rules.
     * If a file/directory matches both a pattern in "only" and "except", it will NOT be processed.
     */
    public $only = ['*.php'];
    /**
     * @var string generated file format. Can be "php", "db", "po" or "pot".
     */
    public $format = 'php';
    /**
     * @var string connection component ID for "db" format.
     */
    public $db = 'db';
    /**
     * @var string custom name for source message table for "db" format.
     */
    public $sourceMessageTable = '{{%source_message}}';
    /**
     * @var string custom name for translation message table for "db" format.
     */
    public $messageTable = '{{%message}}';
    /**
     * @var string name of the file that will be used for translations for "po" format.
     */
    public $catalog = 'messages';
    /**
     * @var array message categories to ignore. For example, 'rct', 'app*', 'widgets.menu', etc.
     * @see isCategoryIgnored
     */
    public $ignoreCategories = [];
    /**
     * @var string File header in generated PHP file with messages. This property is used only if [[$format]] is "php".
     */
    public $phpFileHeader = '';
    /**
     * @var string|null DocBlock used for messages array in generated PHP file. If `null`, default DocBlock will be used.
     * This property is used only if [[$format]] is "php".
     */
    public $phpDocBlock;
    /**
     * @var int Mode used to create directories and files
     */
    public $filesystemMode = 0777;

    /**
     * @var array Config for messages extraction.
     * @see actionExtract()
     * @see initConfig()
     */
    protected $config;

    /**
     * {@inheritdoc}
     */
    public function options($actionID = null)
    {
        return array_merge(parent::options($actionID), [
            'sourcePath',
            'messagePath',
            'languages',
            'translator',
            'sort',
            'overwrite',
            'removeUnused',
            'markUnused',
            'except',
            'only',
            'format',
            'db',
            'sourceMessageTable',
            'messageTable',
            'catalog',
            'ignoreCategories',
            'phpFileHeader',
            'phpDocBlock',
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function optionAliases()
    {
        return array_merge(parent::optionAliases(), [
            'c' => 'catalog',
            'e' => 'except',
            'f' => 'format',
            'i' => 'ignoreCategories',
            'l' => 'languages',
            'u' => 'markUnused',
            'p' => 'messagePath',
            'o' => 'only',
            'w' => 'overwrite',
            'S' => 'sort',
            't' => 'translator',
            'm' => 'sourceMessageTable',
            's' => 'sourcePath',
            'r' => 'removeUnused',
        ]);
    }

    /**
     * Creates a configuration file for the "extract" command using command line options specified.
     *
     * The generated configuration file contains parameters required
     * for source code messages extraction.
     * You may use this configuration file with the "extract" command.
     *
     * @param RequestApplicationInterface $app
     * @param string                      $filePath output file name or alias.
     * @return ExtendedPromiseInterface
     */
    public function actionConfig(RequestApplicationInterface $app, $filePath)
    {
        $filePath = Reaction::getAlias($filePath);
        if (file_exists($filePath)) {
            $confirmPromise = $this->confirm("File '{$filePath}' already exists. Do you wish to overwrite it?");
        } else {
            $confirmPromise = resolve(true);
        }

        return $confirmPromise
            ->then(function() use ($filePath) {
                $array = VarDumper::export($this->getOptionValues($this->getCurrentAction()));
                $content = <<<EOD
<?php
/**
 * Configuration file for 'console {$this->getUniqueId()}/{$this->defaultAction}' command.
 *
 * This file is automatically generated by 'console {$this->getUniqueId()}/{$this->getCurrentAction()}' command.
 * It contains parameters for source code messages extraction.
 * You may modify this file to suit your needs.
 *
 * You can use 'console {$this->getUniqueId()}/{$this->getCurrentAction()}-template' command to create
 * template configuration file with detailed description for each parameter.
 */
return $array;

EOD;
                return FileHelperAsc::exists($filePath)
                    ->then(null, function() use ($filePath) {
                        return FileHelperAsc::create($filePath, $this->filesystemMode);
                    })->then(function() use ($filePath, $content) {
                        return FileHelperAsc::putContents($filePath, $content);
                    })->then(function() use ($filePath) {
                        $this->stdout("Configuration file created: '{$filePath}'.\n\n", Console::FG_GREEN);
                        return true;
                    }, function($error) use ($filePath) {
                        $this->stdout("Configuration file was NOT created: '{$filePath}'.\n\n", Console::FG_RED);
                        return reject($error);
                    });
            });
    }

    /**
     * Creates a configuration file template for the "extract" command.
     *
     * The created configuration file contains detailed instructions on
     * how to customize it to fit for your needs. After customization,
     * you may use this configuration file with the "extract" command.
     *
     * @param RequestApplicationInterface $app
     * @param string                      $filePath output file name or alias.
     * @return ExtendedPromiseInterface
     */
    public function actionConfigTemplate(RequestApplicationInterface $app, $filePath)
    {
        $filePath = Reaction::getAlias($filePath);

        if (file_exists($filePath)) {
            $confirmPromise = $this->confirm("File '{$filePath}' already exists. Do you wish to overwrite it?");
        } else {
            $confirmPromise = resolve(true);
        }

        return $confirmPromise
            ->then(function() use ($filePath) {
                if (!copy(Reaction::getAlias('@reaction/Views/message/config.php'), $filePath)) {
                    return reject(new Exception("Configuration file template was NOT created at '{$filePath}'."));
                }
                $this->stdout("Configuration file template created at '{$filePath}'.\n\n", Console::FG_GREEN);
                return true;
            });
    }

    /**
     * Extracts messages to be translated from source code.
     *
     * This command will search through source code files and extract
     * messages that need to be translated in different languages.
     *
     * @param RequestApplicationInterface $app
     * @param string                      $configFile the path or alias of the configuration file.
     * You may use the "yii message/config" command to generate
     * this file and then customize it for your needs.
     * @return ExtendedPromiseInterface
     * @throws Exception on failure.
     * @throws Reaction\Exceptions\InvalidConfigException
     */
    public function actionExtract(RequestApplicationInterface $app, $configFile = null)
    {
        $this->initConfig($configFile);

        $files = FileHelper::findFiles(realpath($this->config['sourcePath']), $this->config);

        $messages = [];
        foreach ($files as $file) {
            $messages = array_merge_recursive($messages, $this->extractMessages($file, $this->config['translator'], $this->config['ignoreCategories']));
        }

        $catalog = isset($this->config['catalog']) ? $this->config['catalog'] : 'messages';

        if (in_array($this->config['format'], ['php', 'po'])) {
            $promises = [];
            foreach ($this->config['languages'] as $language) {
                $dir = $this->config['messagePath'] . DIRECTORY_SEPARATOR . $language;
                if (!is_dir($dir) && !@mkdir($dir)) {
                    throw new Exception("Directory '{$dir}' can not be created.");
                }
                if ($this->config['format'] === 'po') {
                    $promises[] = $this->saveMessagesToPO($messages, $dir, $this->config['overwrite'], $this->config['removeUnused'], $this->config['sort'], $catalog, $this->config['markUnused']);
                } else {
                    $promises[] = $this->saveMessagesToPHP($messages, $dir, $this->config['overwrite'], $this->config['removeUnused'], $this->config['sort'], $this->config['markUnused']);
                }
            }
            return !empty($promises) ? all($promises) : resolve(true);
        } elseif ($this->config['format'] === 'db') {
            /** @var DatabaseInterface $db */
            $db = Instance::ensure($this->config['db'], DatabaseInterface::class);
            $sourceMessageTable = isset($this->config['sourceMessageTable']) ? $this->config['sourceMessageTable'] : '{{%source_message}}';
            $messageTable = isset($this->config['messageTable']) ? $this->config['messageTable'] : '{{%message}}';
            return $this->saveMessagesToDb(
                $messages,
                $db,
                $sourceMessageTable,
                $messageTable,
                $this->config['removeUnused'],
                $this->config['languages'],
                $this->config['markUnused']
            );
        } elseif ($this->config['format'] === 'pot') {
            return $this->saveMessagesToPOT($messages, $this->config['messagePath'], $catalog);
        }
        return resolve(true);
    }

    /**
     * Saves messages to database.
     *
     * @param array $messages
     * @param DatabaseInterface $db
     * @param string $sourceMessageTable
     * @param string $messageTable
     * @param bool $removeUnused
     * @param array $languages
     * @param bool $markUnused
     * @return ExtendedPromiseInterface
     */
    protected function saveMessagesToDb($messages, $db, $sourceMessageTable, $messageTable, $removeUnused, $languages, $markUnused)
    {
        $currentMessages = [];
        $currentLanguages = [];
        $missingLanguages = [];
        $currentPromises = [
            'messages' => (new Query())->select(['id', 'category', 'message'])->from($sourceMessageTable)->all($db),
            'languages' => (new Query())->select(['language'])->from($messageTable)->groupBy('language')->all($db),
        ];

        $newMessages = [];
        $obsoleteMessages = [];
        $savedFlag = false;

        //Get current messages and languages
        return all($currentPromises)
            ->then(function($results) use (&$currentMessages, &$currentLanguages, &$missingLanguages, $languages) {
                if (!empty($results['messages'])) {
                    foreach ($results['messages'] as $row) {
                        $currentMessages[$row['category']][$row['id']] = $row['message'];
                    }
                }
                if (!empty($results['languages'])) {
                    foreach ($results['languages'] as $row) {
                        $currentLanguages[] = $row['language'];
                    }
                }
                if (!empty($currentLanguages)) {
                    $missingLanguages = array_diff($languages, $currentLanguages);
                }
                return true;
            //Extract from $messages array New and Obsolete messages
            })->then(function() use (&$currentMessages, &$newMessages, &$obsoleteMessages, $messages, $removeUnused) {
                foreach ($messages as $category => $msgs) {
                    $msgs = array_unique($msgs);

                    if (isset($currentMessages[$category])) {
                        $newMessages[$category] = array_diff($msgs, $currentMessages[$category]);
                        $obsoleteMessages += array_diff($currentMessages[$category], $msgs);
                    } else {
                        $newMessages[$category] = $msgs;
                    }
                }

                foreach (array_diff(array_keys($currentMessages), array_keys($messages)) as $category) {
                    $obsoleteMessages += $currentMessages[$category];
                }

                if (!$removeUnused) {
                    foreach ($obsoleteMessages as $pk => $msg) {
                        if (mb_substr($msg, 0, 2) === '@@' && mb_substr($msg, -2) === '@@') {
                            unset($obsoleteMessages[$pk]);
                        }
                    }
                }
                $obsoleteMessages = array_keys($obsoleteMessages);
                return [$newMessages, $obsoleteMessages];
            //Insert new messages to DB
            })->then(function() use (&$newMessages, &$savedFlag, &$db, $sourceMessageTable, $messageTable, $languages) {
                $srcInsertPromises = [];
                foreach ($newMessages as $category => $msgs) {
                    foreach ($msgs as $msg) {
                        $savedFlag = true;
                        $srcInsertPromises[] = $db->getSchema()
                            ->insert($sourceMessageTable, ['category' => $category, 'message' => $msg])
                            ->then(function($lastPk) use (&$db, $languages, $messageTable) {
                                $promises = [];
                                foreach ($languages as $language) {
                                    $promises[] = $db->createCommand()
                                        ->insert($messageTable, ['id' => $lastPk['id'], 'language' => $language])
                                        ->execute();
                                }
                                return allInOrder($promises);
                            });
                    }
                }
                return !empty($srcInsertPromises) ? all($srcInsertPromises) : resolve(true);
            //Remove or mark unused messages
            })->then(function() use (&$db, &$savedFlag, &$obsoleteMessages, $removeUnused, $markUnused, $sourceMessageTable) {
                $this->stdout($savedFlag ? "saved.\n" : "Nothing to save.\n");
                $this->stdout($removeUnused ? 'Deleting obsoleted messages...' : 'Updating obsoleted messages...');

                if (empty($obsoleteMessages)) {
                    $this->stdout("Nothing obsoleted...skipped.\n");
                    return resolve(true);
                }

                if ($removeUnused) {
                    return $db->createCommand()
                        ->delete($sourceMessageTable, ['in', 'id', $obsoleteMessages])
                        ->execute()
                        ->then(function() {
                            $this->stdout("deleted.\n");
                            return true;
                        });
                } elseif ($markUnused) {
                    return (new Query())
                        ->select(['id', 'message'])
                        ->from($sourceMessageTable)
                        ->where(['in', 'id', $obsoleteMessages])
                        ->all($db)
                        ->then(function($rows) use (&$db, $sourceMessageTable) {
                            $promises = [];
                            foreach ($rows as $row) {
                                $promises[] = $db->createCommand()->update(
                                    $sourceMessageTable,
                                    ['message' => '@@' . $row['message'] . '@@'],
                                    ['id' => $row['id']]
                                )->execute();
                            }
                            return allInOrder($promises);
                        })->then(function() {
                            $this->stdout("updated.\n");
                            return true;
                        });
                } else {
                    $this->stdout("kept untouched.\n");
                    return resolve(true);
                }
            });
    }

    /**
     * Extracts messages from a file.
     *
     * @param string $fileName name of the file to extract messages from
     * @param string $translator name of the function used to translate messages
     * @param array $ignoreCategories message categories to ignore.
     * This parameter is available since version 2.0.4.
     * @return array
     */
    protected function extractMessages($fileName, $translator, $ignoreCategories = [])
    {
        $this->stdout('Extracting messages from ');
        $this->stdout($fileName, Console::FG_CYAN);
        $this->stdout("...\n");

        $subject = file_get_contents($fileName);
        $messages = [];
        $tokens = token_get_all($subject);
        foreach ((array) $translator as $currentTranslator) {
            $translatorTokens = token_get_all('<?php ' . $currentTranslator);
            array_shift($translatorTokens);
            $messages = array_merge_recursive($messages, $this->extractMessagesFromTokens($tokens, $translatorTokens, $ignoreCategories));
        }

        $this->stdout("\n");

        return $messages;
    }

    /**
     * Extracts messages from a parsed PHP tokens list.
     * @param array $tokens tokens to be processed.
     * @param array $translatorTokens translator tokens.
     * @param array $ignoreCategories message categories to ignore.
     * @return array messages.
     */
    protected function extractMessagesFromTokens(array $tokens, array $translatorTokens, array $ignoreCategories)
    {
        $messages = [];
        $translatorTokensCount = count($translatorTokens);
        $matchedTokensCount = 0;
        $buffer = [];
        $pendingParenthesisCount = 0;

        foreach ($tokens as $token) {
            // finding out translator call
            if ($matchedTokensCount < $translatorTokensCount) {
                if ($this->tokensEqual($token, $translatorTokens[$matchedTokensCount])) {
                    $matchedTokensCount++;
                } else {
                    $matchedTokensCount = 0;
                }
            } elseif ($matchedTokensCount === $translatorTokensCount) {
                // translator found

                // end of function call
                if ($this->tokensEqual(')', $token)) {
                    $pendingParenthesisCount--;

                    if ($pendingParenthesisCount === 0) {
                        // end of translator call or end of something that we can't extract
                        if (isset($buffer[0][0], $buffer[1], $buffer[2][0]) && $buffer[0][0] === T_CONSTANT_ENCAPSED_STRING && $buffer[1] === ',' && $buffer[2][0] === T_CONSTANT_ENCAPSED_STRING) {
                            // is valid call we can extract
                            $category = stripcslashes($buffer[0][1]);
                            $category = mb_substr($category, 1, -1);

                            if (!$this->isCategoryIgnored($category, $ignoreCategories)) {
                                $fullMessage = mb_substr($buffer[2][1], 1, -1);
                                $i = 3;
                                while ($i < count($buffer) - 1 && !is_array($buffer[$i]) && $buffer[$i] === '.') {
                                    $fullMessage .= mb_substr($buffer[$i + 1][1], 1, -1);
                                    $i += 2;
                                }

                                $message = stripcslashes($fullMessage);
                                $messages[$category][] = $message;
                            }

                            $nestedTokens = array_slice($buffer, 3);
                            if (count($nestedTokens) > $translatorTokensCount) {
                                // search for possible nested translator calls
                                $messages = array_merge_recursive($messages, $this->extractMessagesFromTokens($nestedTokens, $translatorTokens, $ignoreCategories));
                            }
                        } else {
                            // invalid call or dynamic call we can't extract
                            $line = Console::ansiFormat($this->getLine($buffer), [Console::FG_CYAN]);
                            $skipping = Console::ansiFormat('Skipping line', [Console::FG_YELLOW]);
                            $this->stdout("$skipping $line. Make sure both category and message are static strings.\n");
                        }

                        // prepare for the next match
                        $matchedTokensCount = 0;
                        $pendingParenthesisCount = 0;
                        $buffer = [];
                    } else {
                        $buffer[] = $token;
                    }
                } elseif ($this->tokensEqual('(', $token)) {
                    // count beginning of function call, skipping translator beginning
                    if ($pendingParenthesisCount > 0) {
                        $buffer[] = $token;
                    }
                    $pendingParenthesisCount++;
                } elseif (isset($token[0]) && !in_array($token[0], [T_WHITESPACE, T_COMMENT])) {
                    // ignore comments and whitespaces
                    $buffer[] = $token;
                }
            }
        }

        return $messages;
    }

    /**
     * The method checks, whether the $category is ignored according to $ignoreCategories array.
     *
     * Examples:
     *
     * - `myapp` - will be ignored only `myapp` category;
     * - `myapp*` - will be ignored by all categories beginning with `myapp` (`myapp`, `myapplication`, `myapprove`, `myapp/widgets`, `myapp.widgets`, etc).
     *
     * @param string $category category that is checked
     * @param array $ignoreCategories message categories to ignore.
     * @return bool
     */
    protected function isCategoryIgnored($category, array $ignoreCategories)
    {
        if (!empty($ignoreCategories)) {
            if (in_array($category, $ignoreCategories, true)) {
                return true;
            }
            foreach ($ignoreCategories as $pattern) {
                if (strpos($pattern, '*') > 0 && strpos($category, rtrim($pattern, '*')) === 0) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * Finds out if two PHP tokens are equal.
     *
     * @param array|string $a
     * @param array|string $b
     * @return bool
     */
    protected function tokensEqual($a, $b)
    {
        if (is_string($a) && is_string($b)) {
            return $a === $b;
        }
        if (isset($a[0], $a[1], $b[0], $b[1])) {
            return $a[0] === $b[0] && $a[1] == $b[1];
        }

        return false;
    }

    /**
     * Finds out a line of the first non-char PHP token found.
     *
     * @param array $tokens
     * @return int|string
     */
    protected function getLine($tokens)
    {
        foreach ($tokens as $token) {
            if (isset($token[2])) {
                return $token[2];
            }
        }

        return 'unknown';
    }

    /**
     * Writes messages into PHP files.
     *
     * @param array $messages
     * @param string $dirName name of the directory to write to
     * @param bool $overwrite if existing file should be overwritten without backup
     * @param bool $removeUnused if obsolete translations should be removed
     * @param bool $sort if translations should be sorted
     * @param bool $markUnused if obsolete translations should be marked
     * @return ExtendedPromiseInterface
     */
    protected function saveMessagesToPHP($messages, $dirName, $overwrite, $removeUnused, $sort, $markUnused)
    {
        $promises = [];
        foreach ($messages as $category => $msgs) {
            $file = str_replace('\\', '/', "$dirName/$category.php");
            $path = dirname($file);
            $msgs = array_values(array_unique($msgs));
            $coloredFileName = Console::ansiFormat($file, [Console::FG_CYAN]);
            $this->stdout("Saving messages to $coloredFileName...\n");
            $promises[] = FileHelperAsc::createDir($path, $this->filesystemMode)
                ->then(function() use ($msgs, $file, $overwrite, $removeUnused, $sort, $category, $markUnused) {
                    return $this->saveMessagesCategoryToPHP($msgs, $file, $overwrite, $removeUnused, $sort, $category, $markUnused);
                });
        }
        return all($promises);
    }

    /**
     * Writes category messages into PHP file.
     *
     * @param array $messages
     * @param string $fileName name of the file to write to
     * @param bool $overwrite if existing file should be overwritten without backup
     * @param bool $removeUnused if obsolete translations should be removed
     * @param bool $sort if translations should be sorted
     * @param string $category message category
     * @param bool $markUnused if obsolete translations should be marked
     * @return ExtendedPromiseInterface
     */
    protected function saveMessagesCategoryToPHP($messages, $fileName, $overwrite, $removeUnused, $sort, $category, $markUnused)
    {
        if (is_file($fileName)) {
            $rawExistingMessages = require $fileName;
            $existingMessages = $rawExistingMessages;
            sort($messages);
            ksort($existingMessages);
            if (array_keys($existingMessages) === $messages && (!$sort || array_keys($rawExistingMessages) === $messages)) {
                $this->stdout("Nothing new in \"$category\" category... Nothing to save.\n\n", Console::FG_GREEN);
                return Reaction\Promise\resolve(true);
            }
            unset($rawExistingMessages);
            $merged = [];
            $untranslated = [];
            foreach ($messages as $message) {
                if (array_key_exists($message, $existingMessages) && $existingMessages[$message] !== '') {
                    $merged[$message] = $existingMessages[$message];
                } else {
                    $untranslated[] = $message;
                }
            }
            ksort($merged);
            sort($untranslated);
            $todo = [];
            foreach ($untranslated as $message) {
                $todo[$message] = '';
            }
            ksort($existingMessages);
            foreach ($existingMessages as $message => $translation) {
                if (!$removeUnused && !isset($merged[$message]) && !isset($todo[$message])) {
                    if (!$markUnused || (!empty($translation) && (strncmp($translation, '@@', 2) === 0 && substr_compare($translation, '@@', -2, 2) === 0))) {
                        $todo[$message] = $translation;
                    } else {
                        $todo[$message] = '@@' . $translation . '@@';
                    }
                }
            }
            $merged = array_merge($todo, $merged);
            if ($sort) {
                ksort($merged);
            }
            if (false === $overwrite) {
                $fileName .= '.merged';
            }
            $this->stdout("Translation merged.\n");
        } else {
            $merged = [];
            foreach ($messages as $message) {
                $merged[$message] = '';
            }
            ksort($merged);
        }

        $array = VarDumper::export($merged);
        $content = <<<EOD
<?php
{$this->config['phpFileHeader']}{$this->config['phpDocBlock']}
return $array;

EOD;

        return (new Promise(function($r) use ($fileName, $content) {
            $promise = FileHelperAsc::exists($fileName)
                ->then(null, function() use ($fileName) {
                    return FileHelperAsc::create($fileName, $this->filesystemMode);
                })->then(function() use ($fileName, $content) {
                    return FileHelperAsc::putContents($fileName, $content);
                });
            $r($promise);
        }))->then(function() {
            $this->stdout("Translation saved.\n\n", Console::FG_GREEN);
            return true;
        }, function($error) {
            $this->stdout("Translation was NOT saved.\n\n", Console::FG_RED);
            return reject($error);
        });
    }

    /**
     * Writes messages into PO file.
     *
     * @param array $messages
     * @param string $dirName name of the directory to write to
     * @param bool $overwrite if existing file should be overwritten without backup
     * @param bool $removeUnused if obsolete translations should be removed
     * @param bool $sort if translations should be sorted
     * @param string $catalog message catalog
     * @param bool $markUnused if obsolete translations should be marked
     * @return ExtendedPromiseInterface
     */
    protected function saveMessagesToPO($messages, $dirName, $overwrite, $removeUnused, $sort, $catalog, $markUnused)
    {
        $file = str_replace('\\', '/', "$dirName/$catalog.po");
        FileHelper::createDirectory(dirname($file), $this->filesystemMode);
        $this->stdout("Saving messages to $file...\n");

        $poFile = new GettextPoFile();

        $merged = [];
        $todos = [];

        $hasSomethingToWrite = false;
        foreach ($messages as $category => $msgs) {
            $notTranslatedYet = [];
            $msgs = array_values(array_unique($msgs));

            if (is_file($file)) {
                $existingMessages = $poFile->load($category, $file);

                sort($msgs);
                ksort($existingMessages);
                if (array_keys($existingMessages) == $msgs) {
                    $this->stdout("Nothing new in \"$category\" category...\n");

                    sort($msgs);
                    foreach ($msgs as $message) {
                        $merged[$category . chr(4) . $message] = $existingMessages[$message];
                    }
                    ksort($merged);
                    continue;
                }

                // merge existing message translations with new message translations
                foreach ($msgs as $message) {
                    if (array_key_exists($message, $existingMessages) && $existingMessages[$message] !== '') {
                        $merged[$category . chr(4) . $message] = $existingMessages[$message];
                    } else {
                        $notTranslatedYet[] = $message;
                    }
                }
                ksort($merged);
                sort($notTranslatedYet);

                // collect not yet translated messages
                foreach ($notTranslatedYet as $message) {
                    $todos[$category . chr(4) . $message] = '';
                }

                // add obsolete unused messages
                foreach ($existingMessages as $message => $translation) {
                    if (!$removeUnused && !isset($merged[$category . chr(4) . $message]) && !isset($todos[$category . chr(4) . $message])) {
                        if (!$markUnused || (!empty($translation) && (substr($translation, 0, 2) === '@@' && substr($translation, -2) === '@@'))) {
                            $todos[$category . chr(4) . $message] = $translation;
                        } else {
                            $todos[$category . chr(4) . $message] = '@@' . $translation . '@@';
                        }
                    }
                }

                $merged = array_merge($todos, $merged);
                if ($sort) {
                    ksort($merged);
                }

                if ($overwrite === false) {
                    $file .= '.merged';
                }
            } else {
                sort($msgs);
                foreach ($msgs as $message) {
                    $merged[$category . chr(4) . $message] = '';
                }
                ksort($merged);
            }
            $this->stdout("Category \"$category\" merged.\n");
            $hasSomethingToWrite = true;
        }
        if ($hasSomethingToWrite) {
            $poFile->save($merged, $file);
            $this->stdout("Translation saved.\n", Console::FG_GREEN);
        } else {
            $this->stdout("Nothing to save.\n", Console::FG_GREEN);
        }
        return Reaction\Promise\resolve(true);
    }

    /**
     * Writes messages into POT file.
     *
     * @param array $messages
     * @param string $dirName name of the directory to write to
     * @param string $catalog message catalog
     * @return ExtendedPromiseInterface
     */
    protected function saveMessagesToPOT($messages, $dirName, $catalog)
    {
        $file = str_replace('\\', '/', "$dirName/$catalog.pot");
        FileHelper::createDirectory(dirname($file), $this->filesystemMode);
        $this->stdout("Saving messages to $file...\n");

        $poFile = new GettextPoFile();

        $merged = [];

        $hasSomethingToWrite = false;
        foreach ($messages as $category => $msgs) {
            $msgs = array_values(array_unique($msgs));

            sort($msgs);
            foreach ($msgs as $message) {
                $merged[$category . chr(4) . $message] = '';
            }
            $this->stdout("Category \"$category\" merged.\n");
            $hasSomethingToWrite = true;
        }
        if ($hasSomethingToWrite) {
            return new Promise(function($r, $c) use ($poFile, $merged, $file) {
                ksort($merged);
                $poFile->save($merged, $file);
                $this->stdout("Translation saved.\n", Console::FG_GREEN);
                return true;
            });
        } else {
            $this->stdout("Nothing to save.\n", Console::FG_GREEN);
            return resolve(true);
        }
    }

    /**
     * @param string $configFile
     * @throws Exception If configuration file does not exists.
     */
    protected function initConfig($configFile)
    {
        $configFileContent = [];
        if ($configFile !== null) {
            $configFile = Reaction::getAlias($configFile);
            if (!is_file($configFile)) {
                throw new Exception("The configuration file does not exist: $configFile");
            }
            $configFileContent = require $configFile;
        }

        $this->config = array_merge(
            $this->getOptionValues($this->getCurrentAction()),
            $configFileContent,
            $this->getPassedOptionValues()
        );
        $this->config['sourcePath'] = Reaction::getAlias($this->config['sourcePath']);
        $this->config['messagePath'] = Reaction::getAlias($this->config['messagePath']);

        if (!isset($this->config['sourcePath'], $this->config['languages'])) {
            throw new Exception('The configuration file must specify "sourcePath" and "languages".');
        }
        if (!is_dir($this->config['sourcePath'])) {
            throw new Exception("The source path {$this->config['sourcePath']} is not a valid directory.");
        }
        if (empty($this->config['format']) || !in_array($this->config['format'], ['php', 'po', 'pot', 'db'])) {
            throw new Exception('Format should be either "php", "po", "pot" or "db".');
        }
        if (in_array($this->config['format'], ['php', 'po', 'pot'])) {
            if (!isset($this->config['messagePath'])) {
                throw new Exception('The configuration file must specify "messagePath".');
            }
            if (!is_dir($this->config['messagePath'])) {
                throw new Exception("The message path {$this->config['messagePath']} is not a valid directory.");
            }
        }
        if (empty($this->config['languages'])) {
            throw new Exception('Languages cannot be empty.');
        }

        if ($this->config['format'] === 'php' && $this->config['phpDocBlock'] === null) {
            $this->config['phpDocBlock'] = <<<DOCBLOCK
/**
 * Message translations.
 *
 * This file is automatically generated by 'console {$this->getUniqueId()}/{$this->getCurrentAction()}' command.
 * It contains the localizable messages extracted from source code.
 * You may modify this file by translating the extracted messages.
 *
 * Each array element represents the translation (value) of a message (key).
 * If the value is empty, the message is considered as not translated.
 * Messages that no longer need translation will have their translations
 * enclosed between a pair of '@@' marks.
 *
 * Message string can be used with plural forms format. Check i18n section
 * of the guide for details.
 *
 * NOTE: this file must be saved in UTF-8 encoding.
 */
DOCBLOCK;
        }
    }
}


<?php

namespace SubjectivePHP\Psr\Log;

use ArrayObject;
use Psr\Log\AbstractLogger;
use Psr\Log\LoggerInterface;

/**
 * PSR-3 Logger implementation writing to an array.
 */
final class InMemoryLogger extends AbstractLogger implements LoggerInterface
{
    use MessageInterpolationTrait;

    /**
     * @var ArrayObject
     */
    private $logs;

    /**
     * Construct a new instance of the logger.
     *
     * @param ArrayObject $logs Container for log entries.
     */
    public function __construct(ArrayObject $logs)
    {
        $this->logs = $logs;
    }

    /**
     * Logs with an arbitrary level.
     *
     * @param string $level   A valid RFC-5424 log level.
     * @param string $message The base log message.
     * @param array  $context Any extraneous information that does not fit well in a string.
     *
     * @return void
     */
    public function log($level, $message, array $context = [])
    {
        $this->logs[] = [
            'level' => $level,
            'message' => $this->interpolateMessage($message, $context),
            'context' => $context,
        ];
    }
}


<?php

declare(strict_types = 1);

/*
 * This file is part of the FiveLab AuthorizeAction package
 *
 * (c) FiveLab
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code
 */

namespace FiveLab\Component\AuthorizeAction\Verifier;

use FiveLab\Component\AuthorizeAction\Action\AuthorizeActionInterface;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * The chain for collect authorize action verifiers.
 *
 * @author Vitaliy Zhuk <v.zhuk@fivelab.org>
 */
class AuthorizeActionVerifierChain implements AuthorizeActionVerifierInterface
{
    /**
     * @var array|AuthorizeActionVerifierInterface[]
     */
    private $verifiers = [];

    /**
     * Add verifier to chain
     *
     * @param AuthorizeActionVerifierInterface $verifier
     */
    public function add(AuthorizeActionVerifierInterface $verifier): void
    {
        $this->verifiers[] = $verifier;
    }

    /**
     * {@inheritdoc}
     */
    public function supports(AuthorizeActionInterface $action, UserInterface $user): bool
    {
        foreach ($this->verifiers as $verifier) {
            if ($verifier->supports($action, $user)) {
                return true;
            }
        }

        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function verify(AuthorizeActionInterface $action, UserInterface $user): void
    {
        foreach ($this->verifiers as $verifier) {
            if ($verifier->supports($action, $user)) {
                $verifier->verify($action, $user);
            }
        }
    }
}


<?php

namespace Ekyna\Bundle\CoreBundle\Validator\Constraints;

use Ekyna\Bundle\CoreBundle\Model\UploadableInterface;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

/**
 * Class UploadableValidator
 * @package Ekyna\Bundle\CoreBundle\Validator\Constraints
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
class UploadableValidator extends ConstraintValidator
{
    /**
	 * {@inheritdoc}
	 */
    public function validate($uploadable, Constraint $constraint)
    {
    	if (! $uploadable instanceof UploadableInterface) {
    	    throw new UnexpectedTypeException($uploadable, 'Ekyna\Bundle\CoreBundle\Model\UploadableInterface');
    	}
    	if (! $constraint instanceof Uploadable) {
    	    throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Uploadable');
    	}

		/**
		 * @var Uploadable          $constraint
		 * @var UploadableInterface $uploadable
		 */
    	if ($uploadable->hasFile() || $uploadable->hasKey()) {
    	    if (! $uploadable->hasRename()) {
    	        $this->context->addViolationAt(
    	            'rename',
    	            $constraint->nameIsMandatory
    	        );
    	    }
    	} elseif (! $uploadable->hasPath()) {
            $this->context->addViolationAt(
                'file',
                $constraint->fileIsMandatory
            );
    	    if ($uploadable->hasRename()) {
    	        $this->context->addViolationAt(
    	            'rename',
    	            $constraint->leaveBlank
    	        );
    	    }
    	}
    }
}


<?php

declare(strict_types = 1);

namespace Speicher210\BusinessHours\Day\Time;

/**
 * Builder for Time.
 */
class TimeBuilder
{
    /**
     * Create a new Time from an array.
     *
     * @param array $data The data.
     * @return Time
     */
    public static function fromArray(array $data): Time
    {
        if (!isset($data['hours'])) {
            throw new \InvalidArgumentException('Array is not valid.');
        }

        return new Time(
            $data['hours'],
            $data['minutes'] ?? 0,
            $data['seconds'] ?? 0
        );
    }

    /**
     * Create a new time from a string.
     *
     * @param string $time The time as a string.
     * @return Time
     * @throws \InvalidArgumentException If the passed time is invalid.
     */
    public static function fromString($time): Time
    {
        if (empty($time)) {
            throw new \InvalidArgumentException('Invalid time "".');
        }

        try {
            $date = new \DateTime($time);
        } catch (\Exception $e) {
            throw new \InvalidArgumentException(\sprintf('Invalid time "%s".', $time), 0, $e);
        }

        $return = static::fromDate($date);
        if (\strpos($time, '24') === 0) {
            $return->setHours(24);
        }

        return $return;
    }

    /**
     * Create a new time from a date.
     *
     * @param \DateTime $date The date.
     * @return Time
     */
    public static function fromDate(\DateTime $date): Time
    {
        return new Time((int)$date->format('H'), (int)$date->format('i'), (int)$date->format('s'));
    }

    /**
     * Create a new time from seconds.
     *
     * @param integer $seconds The seconds.
     * @return Time
     */
    public static function fromSeconds(int $seconds): Time
    {
        if ($seconds < 0 || $seconds > 86400) {
            throw new \InvalidArgumentException(\sprintf('Invalid time "%s".', $seconds));
        }

        $data = [
            'hours' => (int)($seconds / 3600),
            'minutes' => ($seconds / 60) % 60,
            'seconds' => $seconds % 60
        ];

        return self::fromArray($data);
    }
}


<?php
namespace CakeTaxonomy\Controller;

use CakeTaxonomy\Controller\AppController;

/**
 * Terms Controller
 *
 * @property \CakeTaxonomy\Model\Table\TermsTable $Terms
 */
abstract class AbstractTermsController extends AppController
{

    /**
     * Index method
     *
     * @return \Cake\Network\Response|null
     */
    public function index()
    {
        $this->paginate = [
            'contain' => ['Vocabularies']
        ];
        $terms = $this->paginate($this->Terms);

        $this->set(compact('terms'));
        $this->set('_serialize', ['terms']);
    }

    /**
     * View method
     *
     * @param string|null $id Term id.
     * @return \Cake\Network\Response|null
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function view($id = null)
    {
        $term = $this->Terms->get($id, [
            'contain' => ['Vocabularies']
        ]);

        $this->set('term', $term);
        $this->set('_serialize', ['term']);
    }

    /**
     * Add method
     *
     * @return \Cake\Network\Response|void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $term = $this->Terms->newEntity();
        if ($this->request->is('post')) {
            $term = $this->Terms->patchEntity($term, $this->request->data);
            if ($this->Terms->save($term)) {
                $this->Flash->success(__('The term has been saved.'));

                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('The term could not be saved. Please, try again.'));
            }
        }
        $vocabularies = $this->Terms->Vocabularies->find('list', ['limit' => 200]);
        $this->set(compact('term', 'vocabularies'));
        $this->set('_serialize', ['term']);
    }

    /**
     * Edit method
     *
     * @param string|null $id Term id.
     * @return \Cake\Network\Response|void Redirects on successful edit, renders view otherwise.
     * @throws \Cake\Network\Exception\NotFoundException When record not found.
     */
    public function edit($id = null)
    {
        $term = $this->Terms->get($id, [
            'contain' => []
        ]);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $term = $this->Terms->patchEntity($term, $this->request->data);
            if ($this->Terms->save($term)) {
                $this->Flash->success(__('The term has been saved.'));

                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('The term could not be saved. Please, try again.'));
            }
        }
        $vocabularies = $this->Terms->Vocabularies->find('list', ['limit' => 200]);
        $this->set(compact('term', 'vocabularies'));
        $this->set('_serialize', ['term']);
    }

    /**
     * Delete method
     *
     * @param string|null $id Term id.
     * @return \Cake\Network\Response|null Redirects to index.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function delete($id = null)
    {
        $this->request->allowMethod(['post', 'delete']);
        $term = $this->Terms->get($id);
        if ($this->Terms->delete($term)) {
            $this->Flash->success(__('The term has been deleted.'));
        } else {
            $this->Flash->error(__('The term could not be deleted. Please, try again.'));
        }

        return $this->redirect(['action' => 'index']);
    }
}


<?php

namespace Ekyna\Bundle\CoreBundle\Cache;

use FOS\HttpCacheBundle\Handler\TagHandler;

/**
 * Class TagManager
 * @package Ekyna\Bundle\CoreBundle\Cache
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
class TagManager
{
    /**
     * @var array
     */
    protected $config;

    /**
     * @var TagHandler
     */
    protected $tagHandler;

    /**
     * @var array
     */
    protected $responseTags;

    /**
     * @var array
     */
    protected $invalidateTags;

    /**
     * Constructor.
     *
     * @param array $config
     */
    public function __construct(array $config)
    {
        $this->config = $config;

        $this->reset();
    }

    /**
     * Sets the tag handler.
     *
     * @param TagHandler $tagHandler
     */
    public function setTagHandler(TagHandler $tagHandler)
    {
        $this->tagHandler = $tagHandler;
    }

    /**
     * Invalidates tags.
     *
     * @param mixed $tags
     */
    public function invalidateTags($tags)
    {
        if (empty($tags) || !$this->isEnabled()) {
            return;
        }

        $tags = $this->encodeTags($tags);

        foreach ($tags as $tag) {
            if (!in_array($tag, $this->invalidateTags)) {
                $this->invalidateTags[] = $tag;
            }
        }
    }

    /**
     * Adds tags (for the response).
     *
     * @param mixed $tags
     */
    public function addTags($tags)
    {
        if (empty($tags) || !$this->isEnabled()) {
            return;
        }

        $tags = $this->encodeTags($tags);

        foreach ($tags as $tag) {
            if (!in_array($tag, $this->responseTags)) {
                $this->responseTags[] = $tag;
            }
        }
    }

    /**
     * Flushes the tag manager.
     */
    public function flush()
    {
        if (!empty($this->invalidateTags)) {
            $this->tagHandler->invalidateTags($this->invalidateTags);
        }

        if (!empty($this->responseTags)) {
            $this->tagHandler->addTags($this->responseTags);
        }

        $this->reset();
    }

    /**
     * Rests the tags arrays.
     */
    private function reset()
    {
        $this->responseTags = [];
        $this->invalidateTags = [];
    }

    /**
     * Encodes the tags.
     *
     * @param mixed $tags
     * @return array
     */
    private function encodeTags($tags)
    {
        if (!is_array($tags)) {
            $tags = array($tags);
        }

        if ($this->config['tag']['encode']) {
            $tmp = [];
            foreach ($tags as $tag) {
                $tmp[] = hash('crc32b', $this->config['tag']['secret'].$tag, false);
            }
            $tags = $tmp;
        }

        return $tags;
    }

    /**
     * Returns whether the tag management is active or not.
     *
     * @return bool
     */
    private function isEnabled()
    {
        return $this->config['enable'] && null !== $this->tagHandler;
    }
}


<?php  namespace Mvalim\PackageUtils\Publishers;

use Mvalim\PackageUtils\Exceptions\FileExistsException;
use Mvalim\PackageUtils\Exceptions\InvalidConfigFileException;
use Mvalim\PackageUtils\Exceptions\PackageConfigMissing;
use Mvalim\PackageUtils\Publisher;

class Config extends Publisher {

	protected $name = 'config';

	/**
	 * Return the path where the resources should be published
	 *
	 * @return String
	 */
	public function getPath()
	{
		return $this->app->make('path.config') . '/' . trim($this->package->getName(), '/\\');
	}

	/**
	 * Register the resources if needed
	 *
	 * @return String
	 */
	public function register()
	{
		$namespace = $this->package->getNamespace();
		$config = $this->app->make('config');

		try
		{
			$path = $this->getPath() . '/config.php';
			if($this->app->environment() === 'testing') {
				if( ! $this->filesystem->exists($path)) {
					return $config->set([
						$namespace => $this->getOptions()
					]);
				}
			}
			return $config->set([
				$namespace => include($path)
			]);
		} catch(\Exception $e) {
			$msg = "You need to publish the configs for the package {$this->package->getName()}";
			$this->error(new PackageConfigMissing($msg));
		}
	}

	public function publish($force = false)
	{
		$configFile = $this->getPath() . '/config.php';
		$config = $this->getOptions();
		if( ! $config)
		{
			return;
		}
		if($this->filesystem->exists($configFile))
		{
			if( ! $force)
			{
				$this->container->command()->line('<fg=yellow>Skipping</fg=yellow> <info>configuration</info>: file already exists in destination.');
				return;
			}
			$this->backup($configFile);
		}

		$this->makeDirectory();
		$this->filesystem->put($configFile, $this->buildFileContents($config));
		$this->container->command()->line('<info>Package configs published to:</info> '.$configFile);
	}

	public function getOptions()
	{
		$files = $this->files();
		if( ! count($files))
		{
			return false;
		}
		foreach($files as $f)
		{
			$f = (string)$f;
			$opts[$f] = include($f);
			if( ! is_array($opts[$f]))
			{
				throw new InvalidConfigFileException("All configuration files must return an array");
			}
		}

		$configArray = [];
		foreach($opts as $arr)
		{
			$configArray = array_merge($configArray, $arr);
		}

		return $configArray;
	}

	protected function buildFileContents(array $data)
	{
		return "<?php \nreturn " . var_export($data, true) . ";";
	}
}


<?php

namespace QCharts\CoreBundle\Repository;

use Doctrine\Bundle\DoctrineBundle\Registry;
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Logging\DebugStack;
use \InvalidArgumentException;
use Doctrine\ORM\EntityManagerInterface;
use QCharts\CoreBundle\Exception\DatabaseException;

class DynamicRepository extends DynamicEntityManager
{
    /** @var Registry $doctrine */
    private $doctrine;
    /** @var DebugStack $logger */
    private $logger;

    /**
     * @param Registry $doctrine
     */
    public function __construct(Registry $doctrine)
    {
        $this->doctrine = $doctrine;
        $this->logger = new DebugStack();
        $this->logger->enabled = false;
    }

    /**
     * @param string $connectionName
     * @throws DatabaseException
     */
    public function setUp($connectionName = 'default')
    {
        try
        {
            /** @var EntityManagerInterface $em */
            $em = $this->doctrine->getManager($connectionName);
            $this->setEntityManager($em);
        }
        catch (InvalidArgumentException $e)
        {
            $className = get_class($e);
            $text = "{$e->getMessage()}, {$className},Check that the connection is set up correctly in the project's configuration";
            $text = $text." Check that the orm.entity_managers defines also the connection: {$connectionName}";
            throw new DatabaseException($text, 500, $e);
        }
    }

    /**
     * @param $query
     * @return array
     * @throws DatabaseException
     */
    public function execute($query)
    {
        try
        {
            $connection = $this->getConnection();
            $connection->getConfiguration()->setSQLLogger($this->logger);
            $this->logger->enabled = true;
            $stmt = $connection->query($query);

            /** @var array $results */
            $results = $stmt->fetchAll();

            $this->logger->enabled = false;

            return $results;
        }
        catch (DBALException $e)
        {
            $exceptionText = "There was an error when executing the query, your database's message:\n\n{$e->getMessage()}";
            throw new DatabaseException($exceptionText, 500, $e);
        }
    }

    /**
     * @param $query
     * @return int
     * @throws DatabaseException
     */
    protected function set($query)
    {
        try
        {
            $connection = $this->getConnection();
            $statement = $connection->prepare($query);
            return $statement->execute();
        }
        catch (DBALException $e)
        {
            $exceptionText = "There was an error when setting the max_%%_time SESSION VARIABLE, your database's message:\n\n{$e->getMessage()}";
            throw new DatabaseException($exceptionText, 500, $e);
        }
    }

    /**
     * @return array
     */
    public function getConnectionNames()
    {
        $connections = $this->doctrine->getConnectionNames();
        return $connections;
    }

    /**
     * @return array
     */
    public function getCanonicalConnectionNames()
    {
        $connections = $this->getConnectionNames();
        $toReturn = [];
        foreach ($connections as $key=>$value)
        {
            $toReturn[$key] = $key;
        }
        return $toReturn;
    }

    /**
     * @return float
     * @throws DatabaseException
     */
    public function getExecutionDuration()
    {
        $totalTime = 0.0;

        if (is_null($this->logger))
        {
            throw new DatabaseException("Logger is not initialized", 500);
        }

        foreach ($this->logger->queries as $query)
        {
            $totalTime = $totalTime + $query["executionMS"];
        }

        // return the seconds
        return $totalTime/1000;
    }

    /**
     * Returns FALSE if the Connection returned no variable regarding to the time limit
     * Returns NUMBER if the Connection encountered a variable regarding to the time limit
     *  in seconds
     * Returns STRING if the Connection encountered a variable regarding to the time limit but
     *  the value is 0 (hence not set)
     *
     * http://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_max_execution_time
     *
     * @return bool|number|string
     */
    public function isMaxExecutionSet()
    {
        $results =  $this->execute(DatabaseQueries::SHOW_SESSION_EXECUTION);

        if (!is_null($results) && count($results) <= 0)
        {
            return false;
        }

        foreach ($results as $row)
        {
            if ($row["Value"] == 0)
            {
                // return the name of the variable evaluated
                return $row["Variable_name"];
            }

            $millisecondsLimit = $row["Value"];
            return $millisecondsLimit / 1000; // return only seconds
        }

        return false;
    }

    /**
     * @param int $duration
     * @param string $variableName
     * @return bool
     * @throws DatabaseException
     */
    public function setMaxExecutionTime($duration, $variableName)
    {
        $millisecondsLimit = 1000 * $duration; // $duration is in seconds -> MySQL in milliseconds
        $millisecondsLimit = intval($millisecondsLimit);
        $query = DatabaseQueries::getSessionVariableUpdate($variableName, $millisecondsLimit);
        return $this->set($query);
    }

    /**
     * Returns the names of the schemas of the current connection
     * @return array
     */
    public function getSchemaNames()
    {
        return $this->execute(DatabaseQueries::SHOW_DATABASES);
    }

    /**
     * Returns the names of the tables from the specified schema, uses the current connection
     * @param $schemaName
     * @return array
     */
    public function getTableNamesOfSchema($schemaName)
    {
        return $this->execute(DatabaseQueries::getSQLForTableNames($schemaName));
    }

    /**
     * Returns all the name of the tables from the connection
     * @return array
     * @throws DatabaseException
     */
    public function getAllTableNames()
    {
        return $this->execute(DatabaseQueries::getSQLForAllTableNames());
    }

    /**
     * Returns the information of the colummns in the given table name
     * @param $tableName
     * @return array
     */
    public function getColumnNamesFromTable($tableName)
    {
        return $this->execute(DatabaseQueries::getSQLForColumnNames($tableName));
    }

}


<?php

declare(strict_types=1);

/**
 * States.
 *
 * LICENSE
 *
 * This source file is subject to the MIT license and the version 3 of the GPL3
 * license that are bundled with this package in the folder licences
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to richarddeloge@gmail.com so we can send you a copy immediately.
 *
 *
 * @copyright   Copyright (c) 2009-2017 Richard Déloge (richarddeloge@gmail.com)
 *
 * @link        http://teknoo.software/states Project website
 *
 * @license     http://teknoo.software/license/mit         MIT License
 * @author      Richard Déloge <richarddeloge@gmail.com>
 */

namespace Teknoo\States\LifeCycle\Trace;

use Teknoo\States\LifeCycle\Observing\ObservedInterface;

/**
 * Class Trace
 * Trace about stated class to keep in memory the story of your object.
 *
 * @copyright   Copyright (c) 2009-2017 Richard Déloge (richarddeloge@gmail.com)
 *
 * @link        http://teknoo.software/states Project website
 *
 * @license     http://teknoo.software/license/mit         MIT License
 * @author      Richard Déloge <richarddeloge@gmail.com>
 */
class Trace implements TraceInterface
{
    /**
     * @var \SplStack
     */
    private $stack;

    /**
     * Default constructor.
     */
    public function __construct()
    {
        $this->stack = new \SplStack();
    }

    /**
     * {@inheritdoc}
     */
    public function getTrace(): \SplStack
    {
        return $this->stack;
    }

    /**
     * @return bool
     */
    public function isEmpty(): bool
    {
        return 0 === $this->stack->count();
    }

    /**
     * {@inheritdoc}
     */
    public function getFirstEntry(): EntryInterface
    {
        if (0 === $this->stack->count()) {
            throw new \RuntimeException('Trace empty');
        }

        return $this->stack->bottom();
    }

    /**
     * {@inheritdoc}
     */
    public function getLastEntry(): EntryInterface
    {
        if (0 === $this->stack->count()) {
            throw new \RuntimeException('Trace empty');
        }

        return $this->stack->top();
    }

    /**
     * {@inheritdoc}
     */
    public function addEntry(ObservedInterface $observed, array $enabledStatesList): TraceInterface
    {
        $lastEntry = null;
        if (false === $this->isEmpty()) {
            $lastEntry = $this->getLastEntry();
        }

        $entry = new Entry($observed, $enabledStatesList, $lastEntry);

        if ($lastEntry instanceof EntryInterface) {
            $lastEntry->setNext($entry);
        }

        $this->stack->push($entry);

        return $this;
    }
}


<?php

/*
 * This file is part of the Valkyrja framework.
 *
 * (c) Melech Mizrachi
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Valkyrja\Http;

/**
 * Class Cookies.
 *
 * @author Melech Mizrachi
 *
 * @property \Valkyrja\Http\Cookie[] $collection
 *
 * @method get(string $key, $default = false): \Valkyrja\Http\Cookie
 */
class Cookies
{
    /**
     * Array of cookies.
     *
     * @var array
     */
    protected $cookies = [];

    /**
     * Returns an array with all cookies.
     *
     * @param bool $asString [optional] Get the cookies as a string?
     *
     * @return \Valkyrja\Http\Cookie[]
     */
    public function all(bool $asString = true): array
    {
        if (! $asString) {
            return $this->cookies;
        }

        $flattenedCookies = [];

        /** @var array $path */
        foreach ($this->cookies as $path) {
            /** @var array $cookies */
            foreach ($path as $cookies) {
                /** @var \Valkyrja\Http\Cookie $cookie */
                foreach ($cookies as $cookie) {
                    $flattenedCookies[] = $cookie;
                }
            }
        }

        return $flattenedCookies;
    }

    /**
     * Set a response cookie.
     *
     * @param Cookie $cookie The cookie object
     *
     * @return \Valkyrja\Http\Cookies
     */
    public function set(Cookie $cookie): self
    {
        $this->cookies[$cookie->getDomain()][$cookie->getPath()][$cookie->getName()] = $cookie;

        return $this;
    }

    /**
     * Removes a cookie from the array, but does not unset it in the browser.
     *
     * @param string $name   Cookie name
     * @param string $path   [optional] Cookie path
     * @param string $domain [optional] Cookie domain
     *
     * @return \Valkyrja\Http\Cookies
     */
    public function remove(string $name, string $path = '/', string $domain = null): self
    {
        $path = $path ?? '/';

        unset($this->cookies[$domain][$path][$name]);

        if (empty($this->cookies[$domain][$path])) {
            unset($this->cookies[$domain][$path]);

            if (empty($this->cookies[$domain])) {
                unset($this->cookies[$domain]);
            }
        }

        return $this;
    }
}