<?php

namespace Sasedev\Commons\SharedBundle\Listener;

use Doctrine\Bundle\DoctrineBundle\Registry as Doctrine;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Sasedev\Commons\SharedBundle\Model\BaseUser;

/**
 * Activity Listener
 *
 * @author sasedev <seif.salah@gmail.com>
 */
class Activity
{

	/**
	 *
	 * @var TokenStorage
	 */
	private $tokenStorage;

	/**
	 *
	 * @var EntityManager
	 */
	private $em;

	/**
	 * Constructor
	 *
	 * @param TokenStorage $tokenStorage
	 * @param Doctrine $doctrine
	 */
	public function __construct(TokenStorage $tokenStorage, Doctrine $doctrine)
	{
		$this->tokenStorage = $tokenStorage;
		$this->em = $doctrine->getManager();
	}

	/**
	 * Update the user "lastActivity" on each request
	 *
	 * @param FilterControllerEvent $event
	 */
	public function onCoreController(FilterControllerEvent $event)
	{
		// Here we are checking that the current request is a "MASTER_REQUEST",
		// and ignore any
		// subrequest in the process (for example when
		// doing a render() in a twig template)
		if ($event->getRequestType() !== HttpKernel::MASTER_REQUEST) {
			return;
		}

		// We are checking a token authentification is available before using
		// the User
		if ($this->tokenStorage->getToken()) {
			$user = $this->tokenStorage->getToken()->getUser();

			// We are using a delay during wich the user will be considered as
			// still active, in order to
			// avoid too much UPDATE in the
			// database
			// $delay = new \DateTime ();
			// $delay->setTimestamp (strtotime ('2 minutes ago'));

			// We are checking the Admin class in order to be certain we can
			// call "getLastActivity".
			// && $user->getLastActivity() < $delay) {
			if ($user instanceof BaseUser) {
				$user->isActiveNow();
				$this->em->persist($user);
				$this->em->flush();
			}
		}
	}
}


<?php
/**
 * PEAR, the PHP Extension and Application Repository
 *
 * PEAR class and PEAR_Error class
 *
 * PHP versions 4 and 5
 *
 * @category   pear
 * @package    PEAR
 * @author     Sterling Hughes <sterling@php.net>
 * @author     Stig Bakken <ssb@php.net>
 * @author     Tomas V.V.Cox <cox@idecnet.com>
 * @author     Greg Beaver <cellog@php.net>
 * @copyright  1997-2010 The Authors
 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
 * @version    CVS: $Id: PEAR.php 313023 2011-07-06 19:17:11Z dufuz $
 * @link       http://pear.php.net/package/PEAR
 * @since      File available since Release 0.1
 */

/**#@+
 * ERROR constants
 */
define('PEAR_ERROR_RETURN',     1);
define('PEAR_ERROR_PRINT',      2);
define('PEAR_ERROR_TRIGGER',    4);
define('PEAR_ERROR_DIE',        8);
define('PEAR_ERROR_CALLBACK',  16);
/**
 * WARNING: obsolete
 * @deprecated
 */
define('PEAR_ERROR_EXCEPTION', 32);
/**#@-*/
define('PEAR_ZE2', (function_exists('version_compare') &&
                    version_compare(zend_version(), "2-dev", "ge")));

if (substr(PHP_OS, 0, 3) == 'WIN') {
    define('OS_WINDOWS', true);
    define('OS_UNIX',    false);
    define('PEAR_OS',    'Windows');
} else {
    define('OS_WINDOWS', false);
    define('OS_UNIX',    true);
    define('PEAR_OS',    'Unix'); // blatant assumption
}

$GLOBALS['_PEAR_default_error_mode']     = PEAR_ERROR_RETURN;
$GLOBALS['_PEAR_default_error_options']  = E_USER_NOTICE;
$GLOBALS['_PEAR_destructor_object_list'] = array();
$GLOBALS['_PEAR_shutdown_funcs']         = array();
$GLOBALS['_PEAR_error_handler_stack']    = array();

@ini_set('track_errors', true);

/**
 * Base class for other PEAR classes.  Provides rudimentary
 * emulation of destructors.
 *
 * If you want a destructor in your class, inherit PEAR and make a
 * destructor method called _yourclassname (same name as the
 * constructor, but with a "_" prefix).  Also, in your constructor you
 * have to call the PEAR constructor: $this->PEAR();.
 * The destructor method will be called without parameters.  Note that
 * at in some SAPI implementations (such as Apache), any output during
 * the request shutdown (in which destructors are called) seems to be
 * discarded.  If you need to get any debug information from your
 * destructor, use error_log(), syslog() or something similar.
 *
 * IMPORTANT! To use the emulated destructors you need to create the
 * objects by reference: $obj =& new PEAR_child;
 *
 * @category   pear
 * @package    PEAR
 * @author     Stig Bakken <ssb@php.net>
 * @author     Tomas V.V. Cox <cox@idecnet.com>
 * @author     Greg Beaver <cellog@php.net>
 * @copyright  1997-2006 The PHP Group
 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
 * @version    Release: 1.9.4
 * @link       http://pear.php.net/package/PEAR
 * @see        PEAR_Error
 * @since      Class available since PHP 4.0.2
 * @link        http://pear.php.net/manual/en/core.pear.php#core.pear.pear
 */
class PEAR
{
    /**
     * Whether to enable internal debug messages.
     *
     * @var     bool
     * @access  private
     */
    var $_debug = false;

    /**
     * Default error mode for this object.
     *
     * @var     int
     * @access  private
     */
    var $_default_error_mode = null;

    /**
     * Default error options used for this object when error mode
     * is PEAR_ERROR_TRIGGER.
     *
     * @var     int
     * @access  private
     */
    var $_default_error_options = null;

    /**
     * Default error handler (callback) for this object, if error mode is
     * PEAR_ERROR_CALLBACK.
     *
     * @var     string
     * @access  private
     */
    var $_default_error_handler = '';

    /**
     * Which class to use for error objects.
     *
     * @var     string
     * @access  private
     */
    var $_error_class = 'PEAR_Error';

    /**
     * An array of expected errors.
     *
     * @var     array
     * @access  private
     */
    var $_expected_errors = array();

    /**
     * Constructor.  Registers this object in
     * $_PEAR_destructor_object_list for destructor emulation if a
     * destructor object exists.
     *
     * @param string $error_class  (optional) which class to use for
     *        error objects, defaults to PEAR_Error.
     * @access public
     * @return void
     */
    function PEAR($error_class = null)
    {
        $classname = strtolower(get_class($this));
        if ($this->_debug) {
            print "PEAR constructor called, class=$classname\n";
        }

        if ($error_class !== null) {
            $this->_error_class = $error_class;
        }

        while ($classname && strcasecmp($classname, "pear")) {
            $destructor = "_$classname";
            if (method_exists($this, $destructor)) {
                global $_PEAR_destructor_object_list;
                $_PEAR_destructor_object_list[] = &$this;
                if (!isset($GLOBALS['_PEAR_SHUTDOWN_REGISTERED'])) {
                    register_shutdown_function("_PEAR_call_destructors");
                    $GLOBALS['_PEAR_SHUTDOWN_REGISTERED'] = true;
                }
                break;
            } else {
                $classname = get_parent_class($classname);
            }
        }
    }

    /**
     * Destructor (the emulated type of...).  Does nothing right now,
     * but is included for forward compatibility, so subclass
     * destructors should always call it.
     *
     * See the note in the class desciption about output from
     * destructors.
     *
     * @access public
     * @return void
     */
    function _PEAR() {
        if ($this->_debug) {
            printf("PEAR destructor called, class=%s\n", strtolower(get_class($this)));
        }
    }

    /**
    * If you have a class that's mostly/entirely static, and you need static
    * properties, you can use this method to simulate them. Eg. in your method(s)
    * do this: $myVar = &PEAR::getStaticProperty('myclass', 'myVar');
    * You MUST use a reference, or they will not persist!
    *
    * @access public
    * @param  string $class  The calling classname, to prevent clashes
    * @param  string $var    The variable to retrieve.
    * @return mixed   A reference to the variable. If not set it will be
    *                 auto initialised to NULL.
    */
    function &getStaticProperty($class, $var)
    {
        static $properties;
        if (!isset($properties[$class])) {
            $properties[$class] = array();
        }

        if (!array_key_exists($var, $properties[$class])) {
            $properties[$class][$var] = null;
        }

        return $properties[$class][$var];
    }

    /**
    * Use this function to register a shutdown method for static
    * classes.
    *
    * @access public
    * @param  mixed $func  The function name (or array of class/method) to call
    * @param  mixed $args  The arguments to pass to the function
    * @return void
    */
    function registerShutdownFunc($func, $args = array())
    {
        // if we are called statically, there is a potential
        // that no shutdown func is registered.  Bug #6445
        if (!isset($GLOBALS['_PEAR_SHUTDOWN_REGISTERED'])) {
            register_shutdown_function("_PEAR_call_destructors");
            $GLOBALS['_PEAR_SHUTDOWN_REGISTERED'] = true;
        }
        $GLOBALS['_PEAR_shutdown_funcs'][] = array($func, $args);
    }

    /**
     * Tell whether a value is a PEAR error.
     *
     * @param   mixed $data   the value to test
     * @param   int   $code   if $data is an error object, return true
     *                        only if $code is a string and
     *                        $obj->getMessage() == $code or
     *                        $code is an integer and $obj->getCode() == $code
     * @access  public
     * @return  bool    true if parameter is an error
     */
    function isError($data, $code = null)
    {
        if (!is_a($data, 'PEAR_Error')) {
            return false;
        }

        if (is_null($code)) {
            return true;
        } elseif (is_string($code)) {
            return $data->getMessage() == $code;
        }

        return $data->getCode() == $code;
    }

    /**
     * Sets how errors generated by this object should be handled.
     * Can be invoked both in objects and statically.  If called
     * statically, setErrorHandling sets the default behaviour for all
     * PEAR objects.  If called in an object, setErrorHandling sets
     * the default behaviour for that object.
     *
     * @param int $mode
     *        One of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT,
     *        PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE,
     *        PEAR_ERROR_CALLBACK or PEAR_ERROR_EXCEPTION.
     *
     * @param mixed $options
     *        When $mode is PEAR_ERROR_TRIGGER, this is the error level (one
     *        of E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR).
     *
     *        When $mode is PEAR_ERROR_CALLBACK, this parameter is expected
     *        to be the callback function or method.  A callback
     *        function is a string with the name of the function, a
     *        callback method is an array of two elements: the element
     *        at index 0 is the object, and the element at index 1 is
     *        the name of the method to call in the object.
     *
     *        When $mode is PEAR_ERROR_PRINT or PEAR_ERROR_DIE, this is
     *        a printf format string used when printing the error
     *        message.
     *
     * @access public
     * @return void
     * @see PEAR_ERROR_RETURN
     * @see PEAR_ERROR_PRINT
     * @see PEAR_ERROR_TRIGGER
     * @see PEAR_ERROR_DIE
     * @see PEAR_ERROR_CALLBACK
     * @see PEAR_ERROR_EXCEPTION
     *
     * @since PHP 4.0.5
     */
    function setErrorHandling($mode = null, $options = null)
    {
        if (isset($this) && is_a($this, 'PEAR')) {
            $setmode     = &$this->_default_error_mode;
            $setoptions  = &$this->_default_error_options;
        } else {
            $setmode     = &$GLOBALS['_PEAR_default_error_mode'];
            $setoptions  = &$GLOBALS['_PEAR_default_error_options'];
        }

        switch ($mode) {
            case PEAR_ERROR_EXCEPTION:
            case PEAR_ERROR_RETURN:
            case PEAR_ERROR_PRINT:
            case PEAR_ERROR_TRIGGER:
            case PEAR_ERROR_DIE:
            case null:
                $setmode = $mode;
                $setoptions = $options;
                break;

            case PEAR_ERROR_CALLBACK:
                $setmode = $mode;
                // class/object method callback
                if (is_callable($options)) {
                    $setoptions = $options;
                } else {
                    trigger_error("invalid error callback", E_USER_WARNING);
                }
                break;

            default:
                trigger_error("invalid error mode", E_USER_WARNING);
                break;
        }
    }

    /**
     * This method is used to tell which errors you expect to get.
     * Expected errors are always returned with error mode
     * PEAR_ERROR_RETURN.  Expected error codes are stored in a stack,
     * and this method pushes a new element onto it.  The list of
     * expected errors are in effect until they are popped off the
     * stack with the popExpect() method.
     *
     * Note that this method can not be called statically
     *
     * @param mixed $code a single error code or an array of error codes to expect
     *
     * @return int     the new depth of the "expected errors" stack
     * @access public
     */
    function expectError($code = '*')
    {
        if (is_array($code)) {
            array_push($this->_expected_errors, $code);
        } else {
            array_push($this->_expected_errors, array($code));
        }
        return count($this->_expected_errors);
    }

    /**
     * This method pops one element off the expected error codes
     * stack.
     *
     * @return array   the list of error codes that were popped
     */
    function popExpect()
    {
        return array_pop($this->_expected_errors);
    }

    /**
     * This method checks unsets an error code if available
     *
     * @param mixed error code
     * @return bool true if the error code was unset, false otherwise
     * @access private
     * @since PHP 4.3.0
     */
    function _checkDelExpect($error_code)
    {
        $deleted = false;
        foreach ($this->_expected_errors as $key => $error_array) {
            if (in_array($error_code, $error_array)) {
                unset($this->_expected_errors[$key][array_search($error_code, $error_array)]);
                $deleted = true;
            }

            // clean up empty arrays
            if (0 == count($this->_expected_errors[$key])) {
                unset($this->_expected_errors[$key]);
            }
        }

        return $deleted;
    }

    /**
     * This method deletes all occurences of the specified element from
     * the expected error codes stack.
     *
     * @param  mixed $error_code error code that should be deleted
     * @return mixed list of error codes that were deleted or error
     * @access public
     * @since PHP 4.3.0
     */
    function delExpect($error_code)
    {
        $deleted = false;
        if ((is_array($error_code) && (0 != count($error_code)))) {
            // $error_code is a non-empty array here; we walk through it trying
            // to unset all values
            foreach ($error_code as $key => $error) {
                $deleted =  $this->_checkDelExpect($error) ? true : false;
            }

            return $deleted ? true : PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME
        } elseif (!empty($error_code)) {
            // $error_code comes alone, trying to unset it
            if ($this->_checkDelExpect($error_code)) {
                return true;
            }

            return PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME
        }

        // $error_code is empty
        return PEAR::raiseError("The expected error you submitted is empty"); // IMPROVE ME
    }

    /**
     * This method is a wrapper that returns an instance of the
     * configured error class with this object's default error
     * handling applied.  If the $mode and $options parameters are not
     * specified, the object's defaults are used.
     *
     * @param mixed $message a text error message or a PEAR error object
     *
     * @param int $code      a numeric error code (it is up to your class
     *                  to define these if you want to use codes)
     *
     * @param int $mode      One of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT,
     *                  PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE,
     *                  PEAR_ERROR_CALLBACK, PEAR_ERROR_EXCEPTION.
     *
     * @param mixed $options If $mode is PEAR_ERROR_TRIGGER, this parameter
     *                  specifies the PHP-internal error level (one of
     *                  E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR).
     *                  If $mode is PEAR_ERROR_CALLBACK, this
     *                  parameter specifies the callback function or
     *                  method.  In other error modes this parameter
     *                  is ignored.
     *
     * @param string $userinfo If you need to pass along for example debug
     *                  information, this parameter is meant for that.
     *
     * @param string $error_class The returned error object will be
     *                  instantiated from this class, if specified.
     *
     * @param bool $skipmsg If true, raiseError will only pass error codes,
     *                  the error message parameter will be dropped.
     *
     * @access public
     * @return object   a PEAR error object
     * @see PEAR::setErrorHandling
     * @since PHP 4.0.5
     */
    function &raiseError($message = null,
                         $code = null,
                         $mode = null,
                         $options = null,
                         $userinfo = null,
                         $error_class = null,
                         $skipmsg = false)
    {
        // The error is yet a PEAR error object
        if (is_object($message)) {
            $code        = $message->getCode();
            $userinfo    = $message->getUserInfo();
            $error_class = $message->getType();
            $message->error_message_prefix = '';
            $message     = $message->getMessage();
        }

        if (
            isset($this) &&
            isset($this->_expected_errors) &&
            count($this->_expected_errors) > 0 &&
            count($exp = end($this->_expected_errors))
        ) {
            if ($exp[0] == "*" ||
                (is_int(reset($exp)) && in_array($code, $exp)) ||
                (is_string(reset($exp)) && in_array($message, $exp))
            ) {
                $mode = PEAR_ERROR_RETURN;
            }
        }

        // No mode given, try global ones
        if ($mode === null) {
            // Class error handler
            if (isset($this) && isset($this->_default_error_mode)) {
                $mode    = $this->_default_error_mode;
                $options = $this->_default_error_options;
            // Global error handler
            } elseif (isset($GLOBALS['_PEAR_default_error_mode'])) {
                $mode    = $GLOBALS['_PEAR_default_error_mode'];
                $options = $GLOBALS['_PEAR_default_error_options'];
            }
        }

        if ($error_class !== null) {
            $ec = $error_class;
        } elseif (isset($this) && isset($this->_error_class)) {
            $ec = $this->_error_class;
        } else {
            $ec = 'PEAR_Error';
        }

        if (intval(PHP_VERSION) < 5) {
            // little non-eval hack to fix bug #12147
            include 'PEAR/FixPHP5PEARWarnings.php';
            return $a;
        }

        if ($skipmsg) {
            $a = new $ec($code, $mode, $options, $userinfo);
        } else {
            $a = new $ec($message, $code, $mode, $options, $userinfo);
        }

        return $a;
    }

    /**
     * Simpler form of raiseError with fewer options.  In most cases
     * message, code and userinfo are enough.
     *
     * @param mixed $message a text error message or a PEAR error object
     *
     * @param int $code      a numeric error code (it is up to your class
     *                  to define these if you want to use codes)
     *
     * @param string $userinfo If you need to pass along for example debug
     *                  information, this parameter is meant for that.
     *
     * @access public
     * @return object   a PEAR error object
     * @see PEAR::raiseError
     */
    function &throwError($message = null, $code = null, $userinfo = null)
    {
        if (isset($this) && is_a($this, 'PEAR')) {
            $a = &$this->raiseError($message, $code, null, null, $userinfo);
            return $a;
        }

        $a = &PEAR::raiseError($message, $code, null, null, $userinfo);
        return $a;
    }

    function staticPushErrorHandling($mode, $options = null)
    {
        $stack       = &$GLOBALS['_PEAR_error_handler_stack'];
        $def_mode    = &$GLOBALS['_PEAR_default_error_mode'];
        $def_options = &$GLOBALS['_PEAR_default_error_options'];
        $stack[] = array($def_mode, $def_options);
        switch ($mode) {
            case PEAR_ERROR_EXCEPTION:
            case PEAR_ERROR_RETURN:
            case PEAR_ERROR_PRINT:
            case PEAR_ERROR_TRIGGER:
            case PEAR_ERROR_DIE:
            case null:
                $def_mode = $mode;
                $def_options = $options;
                break;

            case PEAR_ERROR_CALLBACK:
                $def_mode = $mode;
                // class/object method callback
                if (is_callable($options)) {
                    $def_options = $options;
                } else {
                    trigger_error("invalid error callback", E_USER_WARNING);
                }
                break;

            default:
                trigger_error("invalid error mode", E_USER_WARNING);
                break;
        }
        $stack[] = array($mode, $options);
        return true;
    }

    function staticPopErrorHandling()
    {
        $stack = &$GLOBALS['_PEAR_error_handler_stack'];
        $setmode     = &$GLOBALS['_PEAR_default_error_mode'];
        $setoptions  = &$GLOBALS['_PEAR_default_error_options'];
        array_pop($stack);
        list($mode, $options) = $stack[sizeof($stack) - 1];
        array_pop($stack);
        switch ($mode) {
            case PEAR_ERROR_EXCEPTION:
            case PEAR_ERROR_RETURN:
            case PEAR_ERROR_PRINT:
            case PEAR_ERROR_TRIGGER:
            case PEAR_ERROR_DIE:
            case null:
                $setmode = $mode;
                $setoptions = $options;
                break;

            case PEAR_ERROR_CALLBACK:
                $setmode = $mode;
                // class/object method callback
                if (is_callable($options)) {
                    $setoptions = $options;
                } else {
                    trigger_error("invalid error callback", E_USER_WARNING);
                }
                break;

            default:
                trigger_error("invalid error mode", E_USER_WARNING);
                break;
        }
        return true;
    }

    /**
     * Push a new error handler on top of the error handler options stack. With this
     * you can easily override the actual error handler for some code and restore
     * it later with popErrorHandling.
     *
     * @param mixed $mode (same as setErrorHandling)
     * @param mixed $options (same as setErrorHandling)
     *
     * @return bool Always true
     *
     * @see PEAR::setErrorHandling
     */
    function pushErrorHandling($mode, $options = null)
    {
        $stack = &$GLOBALS['_PEAR_error_handler_stack'];
        if (isset($this) && is_a($this, 'PEAR')) {
            $def_mode    = &$this->_default_error_mode;
            $def_options = &$this->_default_error_options;
        } else {
            $def_mode    = &$GLOBALS['_PEAR_default_error_mode'];
            $def_options = &$GLOBALS['_PEAR_default_error_options'];
        }
        $stack[] = array($def_mode, $def_options);

        if (isset($this) && is_a($this, 'PEAR')) {
            $this->setErrorHandling($mode, $options);
        } else {
            PEAR::setErrorHandling($mode, $options);
        }
        $stack[] = array($mode, $options);
        return true;
    }

    /**
    * Pop the last error handler used
    *
    * @return bool Always true
    *
    * @see PEAR::pushErrorHandling
    */
    function popErrorHandling()
    {
        $stack = &$GLOBALS['_PEAR_error_handler_stack'];
        array_pop($stack);
        list($mode, $options) = $stack[sizeof($stack) - 1];
        array_pop($stack);
        if (isset($this) && is_a($this, 'PEAR')) {
            $this->setErrorHandling($mode, $options);
        } else {
            PEAR::setErrorHandling($mode, $options);
        }
        return true;
    }

    /**
    * OS independant PHP extension load. Remember to take care
    * on the correct extension name for case sensitive OSes.
    *
    * @param string $ext The extension name
    * @return bool Success or not on the dl() call
    */
    function loadExtension($ext)
    {
        if (extension_loaded($ext)) {
            return true;
        }

        // if either returns true dl() will produce a FATAL error, stop that
        if (
            function_exists('dl') === false ||
            ini_get('enable_dl') != 1 ||
            ini_get('safe_mode') == 1
        ) {
            return false;
        }

        if (OS_WINDOWS) {
            $suffix = '.dll';
        } elseif (PHP_OS == 'HP-UX') {
            $suffix = '.sl';
        } elseif (PHP_OS == 'AIX') {
            $suffix = '.a';
        } elseif (PHP_OS == 'OSX') {
            $suffix = '.bundle';
        } else {
            $suffix = '.so';
        }

        return @dl('php_'.$ext.$suffix) || @dl($ext.$suffix);
    }
}

if (PEAR_ZE2) {
    include_once 'PEAR5.php';
}

function _PEAR_call_destructors()
{
    global $_PEAR_destructor_object_list;
    if (is_array($_PEAR_destructor_object_list) &&
        sizeof($_PEAR_destructor_object_list))
    {
        reset($_PEAR_destructor_object_list);
        if (PEAR_ZE2) {
            $destructLifoExists = PEAR5::getStaticProperty('PEAR', 'destructlifo');
        } else {
            $destructLifoExists = PEAR::getStaticProperty('PEAR', 'destructlifo');
        }

        if ($destructLifoExists) {
            $_PEAR_destructor_object_list = array_reverse($_PEAR_destructor_object_list);
        }

        while (list($k, $objref) = each($_PEAR_destructor_object_list)) {
            $classname = get_class($objref);
            while ($classname) {
                $destructor = "_$classname";
                if (method_exists($objref, $destructor)) {
                    $objref->$destructor();
                    break;
                } else {
                    $classname = get_parent_class($classname);
                }
            }
        }
        // Empty the object list to ensure that destructors are
        // not called more than once.
        $_PEAR_destructor_object_list = array();
    }

    // Now call the shutdown functions
    if (
        isset($GLOBALS['_PEAR_shutdown_funcs']) &&
        is_array($GLOBALS['_PEAR_shutdown_funcs']) &&
        !empty($GLOBALS['_PEAR_shutdown_funcs'])
    ) {
        foreach ($GLOBALS['_PEAR_shutdown_funcs'] as $value) {
            call_user_func_array($value[0], $value[1]);
        }
    }
}

/**
 * Standard PEAR error class for PHP 4
 *
 * This class is supserseded by {@link PEAR_Exception} in PHP 5
 *
 * @category   pear
 * @package    PEAR
 * @author     Stig Bakken <ssb@php.net>
 * @author     Tomas V.V. Cox <cox@idecnet.com>
 * @author     Gregory Beaver <cellog@php.net>
 * @copyright  1997-2006 The PHP Group
 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
 * @version    Release: 1.9.4
 * @link       http://pear.php.net/manual/en/core.pear.pear-error.php
 * @see        PEAR::raiseError(), PEAR::throwError()
 * @since      Class available since PHP 4.0.2
 */
class PEAR_Error
{
    var $error_message_prefix = '';
    var $mode                 = PEAR_ERROR_RETURN;
    var $level                = E_USER_NOTICE;
    var $code                 = -1;
    var $message              = '';
    var $userinfo             = '';
    var $backtrace            = null;

    /**
     * PEAR_Error constructor
     *
     * @param string $message  message
     *
     * @param int $code     (optional) error code
     *
     * @param int $mode     (optional) error mode, one of: PEAR_ERROR_RETURN,
     * PEAR_ERROR_PRINT, PEAR_ERROR_DIE, PEAR_ERROR_TRIGGER,
     * PEAR_ERROR_CALLBACK or PEAR_ERROR_EXCEPTION
     *
     * @param mixed $options   (optional) error level, _OR_ in the case of
     * PEAR_ERROR_CALLBACK, the callback function or object/method
     * tuple.
     *
     * @param string $userinfo (optional) additional user/debug info
     *
     * @access public
     *
     */
    function PEAR_Error($message = 'unknown error', $code = null,
                        $mode = null, $options = null, $userinfo = null)
    {
        if ($mode === null) {
            $mode = PEAR_ERROR_RETURN;
        }
        $this->message   = $message;
        $this->code      = $code;
        $this->mode      = $mode;
        $this->userinfo  = $userinfo;

        if (PEAR_ZE2) {
            $skiptrace = PEAR5::getStaticProperty('PEAR_Error', 'skiptrace');
        } else {
            $skiptrace = PEAR::getStaticProperty('PEAR_Error', 'skiptrace');
        }

        if (!$skiptrace) {
            $this->backtrace = debug_backtrace();
            if (isset($this->backtrace[0]) && isset($this->backtrace[0]['object'])) {
                unset($this->backtrace[0]['object']);
            }
        }

        if ($mode & PEAR_ERROR_CALLBACK) {
            $this->level = E_USER_NOTICE;
            $this->callback = $options;
        } else {
            if ($options === null) {
                $options = E_USER_NOTICE;
            }

            $this->level = $options;
            $this->callback = null;
        }

        if ($this->mode & PEAR_ERROR_PRINT) {
            if (is_null($options) || is_int($options)) {
                $format = "%s";
            } else {
                $format = $options;
            }

            printf($format, $this->getMessage());
        }

        if ($this->mode & PEAR_ERROR_TRIGGER) {
            trigger_error($this->getMessage(), $this->level);
        }

        if ($this->mode & PEAR_ERROR_DIE) {
            $msg = $this->getMessage();
            if (is_null($options) || is_int($options)) {
                $format = "%s";
                if (substr($msg, -1) != "\n") {
                    $msg .= "\n";
                }
            } else {
                $format = $options;
            }
            die(sprintf($format, $msg));
        }

        if ($this->mode & PEAR_ERROR_CALLBACK && is_callable($this->callback)) {
            call_user_func($this->callback, $this);
        }

        if ($this->mode & PEAR_ERROR_EXCEPTION) {
            trigger_error("PEAR_ERROR_EXCEPTION is obsolete, use class PEAR_Exception for exceptions", E_USER_WARNING);
            eval('$e = new Exception($this->message, $this->code);throw($e);');
        }
    }

    /**
     * Get the error mode from an error object.
     *
     * @return int error mode
     * @access public
     */
    function getMode()
    {
        return $this->mode;
    }

    /**
     * Get the callback function/method from an error object.
     *
     * @return mixed callback function or object/method array
     * @access public
     */
    function getCallback()
    {
        return $this->callback;
    }

    /**
     * Get the error message from an error object.
     *
     * @return  string  full error message
     * @access public
     */
    function getMessage()
    {
        return ($this->error_message_prefix . $this->message);
    }

    /**
     * Get error code from an error object
     *
     * @return int error code
     * @access public
     */
     function getCode()
     {
        return $this->code;
     }

    /**
     * Get the name of this error/exception.
     *
     * @return string error/exception name (type)
     * @access public
     */
    function getType()
    {
        return get_class($this);
    }

    /**
     * Get additional user-supplied information.
     *
     * @return string user-supplied information
     * @access public
     */
    function getUserInfo()
    {
        return $this->userinfo;
    }

    /**
     * Get additional debug information supplied by the application.
     *
     * @return string debug information
     * @access public
     */
    function getDebugInfo()
    {
        return $this->getUserInfo();
    }

    /**
     * Get the call backtrace from where the error was generated.
     * Supported with PHP 4.3.0 or newer.
     *
     * @param int $frame (optional) what frame to fetch
     * @return array Backtrace, or NULL if not available.
     * @access public
     */
    function getBacktrace($frame = null)
    {
        if (defined('PEAR_IGNORE_BACKTRACE')) {
            return null;
        }
        if ($frame === null) {
            return $this->backtrace;
        }
        return $this->backtrace[$frame];
    }

    function addUserInfo($info)
    {
        if (empty($this->userinfo)) {
            $this->userinfo = $info;
        } else {
            $this->userinfo .= " ** $info";
        }
    }

    function __toString()
    {
        return $this->getMessage();
    }

    /**
     * Make a string representation of this object.
     *
     * @return string a string with an object summary
     * @access public
     */
    function toString()
    {
        $modes = array();
        $levels = array(E_USER_NOTICE  => 'notice',
                        E_USER_WARNING => 'warning',
                        E_USER_ERROR   => 'error');
        if ($this->mode & PEAR_ERROR_CALLBACK) {
            if (is_array($this->callback)) {
                $callback = (is_object($this->callback[0]) ?
                    strtolower(get_class($this->callback[0])) :
                    $this->callback[0]) . '::' .
                    $this->callback[1];
            } else {
                $callback = $this->callback;
            }
            return sprintf('[%s: message="%s" code=%d mode=callback '.
                           'callback=%s prefix="%s" info="%s"]',
                           strtolower(get_class($this)), $this->message, $this->code,
                           $callback, $this->error_message_prefix,
                           $this->userinfo);
        }
        if ($this->mode & PEAR_ERROR_PRINT) {
            $modes[] = 'print';
        }
        if ($this->mode & PEAR_ERROR_TRIGGER) {
            $modes[] = 'trigger';
        }
        if ($this->mode & PEAR_ERROR_DIE) {
            $modes[] = 'die';
        }
        if ($this->mode & PEAR_ERROR_RETURN) {
            $modes[] = 'return';
        }
        return sprintf('[%s: message="%s" code=%d mode=%s level=%s '.
                       'prefix="%s" info="%s"]',
                       strtolower(get_class($this)), $this->message, $this->code,
                       implode("|", $modes), $levels[$this->level],
                       $this->error_message_prefix,
                       $this->userinfo);
    }
}

/*
 * Local Variables:
 * mode: php
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 */


<?php
namespace FzyCommon;

use Doctrine\ORM\Events;
use FzyCommon\Listener\ServiceAwareEntity as ServiceAwareEntityListener;
use Zend\EventManager\EventInterface;
use Zend\ModuleManager\Feature\BootstrapListenerInterface;

class Module implements BootstrapListenerInterface {
	public function getAutoloaderConfig()
	{
		return array(
			'Zend\Loader\ClassMapAutoloader' => array(
				__DIR__ . '/autoload_classmap.php',
			),
			'Zend\Loader\StandardAutoloader' => array(
				'namespaces' => array(
					__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
				),
			),
		);
	}

	public function getConfig()
	{
		return include __DIR__ . '/config/module.config.php';
	}

	/**
	 * Listen to the bootstrap event
	 *
	 * @param EventInterface $e
	 * @return array
	 */
	public function onBootstrap(EventInterface $e)
	{
		/* @var $sm \Zend\ServiceManager\ServiceLocatorInterface */
		$sm = $e->getApplication()->getServiceManager();
		/* @var $em \Doctrine\ORM\EntityManager */
		$em = $sm->get('Doctrine\ORM\EntityManager');
		$em->getEventManager()->addEventSubscriber(new ServiceAwareEntityListener($sm));
	}

}


<?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\Console\Commands;

use Valkyrja\Console\CommandHandler;
use Valkyrja\Console\Support\ProvidesCommand;

/**
 * Class Optimize.
 *
 * @author Melech Mizrachi
 */
class OptimizeCommand extends CommandHandler
{
    use ProvidesCommand;

    /**
     * The command.
     */
    public const COMMAND           = 'optimize';
    public const PATH              = self::COMMAND;
    public const SHORT_DESCRIPTION = 'Optimize the application';

    /**
     * Optimize the application.
     *
     * @return int
     */
    public function run(): int
    {
        // If the cache file already exists, delete it
        if (file_exists(config()['cacheFilePath'])) {
            unlink(config()['cacheFilePath']);
        }

        app()->setup(
            [
                'app' => [
                    'debug' => false,
                    'env'   => 'production',
                ],
            ],
            true
        );

        $containerCache = container()->getCacheable();
        $consoleCache   = console()->getCacheable();
        $eventsCache    = events()->getCacheable();
        $routesCache    = router()->getCacheable();
        $configCache    = config();

        $configCache['cache']['container'] = $containerCache;
        $configCache['cache']['console']   = $consoleCache;
        $configCache['cache']['events']    = $eventsCache;
        $configCache['cache']['routing']   = $routesCache;

        $configCache['container']['useCache'] = true;
        $configCache['console']['useCache']   = true;
        $configCache['events']['useCache']    = true;
        $configCache['routing']['useCache']   = true;

        // Get the results of the cache attempt
        $result = file_put_contents(
            config()['cacheFilePath'],
            '<?php return ' . var_export($configCache, true) . ';',
            LOCK_EX
        );

        if ($result === false) {
            output()->writeMessage(
                'An error occurred while optimizing the application.',
                true
            );

            return 1;
        }

        output()->writeMessage('Application optimized successfully', true);

        return 0;
    }
}


<?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: Openssl.php 24593 2012-01-05 20:35:02Z matthew $
 */

/**
 * @see Zend_Filter_Encrypt_Interface
 */

/**
 * Encryption adapter for openssl
 *
 * @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_Encrypt_Openssl implements Zend_Filter_Encrypt_Interface
{
    /**
     * Definitions for encryption
     * array(
     *     'public'   => public keys
     *     'private'  => private keys
     *     'envelope' => resulting envelope keys
     * )
     */
    protected $_keys = array(
        'public'   => array(),
        'private'  => array(),
        'envelope' => array()
    );

    /**
     * Internal passphrase
     *
     * @var string
     */
    protected $_passphrase;

    /**
     * Internal compression
     *
     * @var array
     */
    protected $_compression;

    /**
     * Internal create package
     *
     * @var boolean
     */
    protected $_package = false;

    /**
     * Class constructor
     * Available options
     *   'public'      => public key
     *   'private'     => private key
     *   'envelope'    => envelope key
     *   'passphrase'  => passphrase
     *   'compression' => compress value with this compression adapter
     *   'package'     => pack envelope keys into encrypted string, simplifies decryption
     *
     * @param string|array $options Options for this adapter
     */
    public function __construct($options = array())
    {
        if (!extension_loaded('openssl')) {

            throw new Zend_Filter_Exception('This filter needs the openssl extension');
        }

        if ($options instanceof Zend_Config) {
            $options = $options->toArray();
        }

        if (!is_array($options)) {
            $options = array('public' => $options);
        }

        if (array_key_exists('passphrase', $options)) {
            $this->setPassphrase($options['passphrase']);
            unset($options['passphrase']);
        }

        if (array_key_exists('compression', $options)) {
            $this->setCompression($options['compression']);
            unset($options['compress']);
        }

        if (array_key_exists('package', $options)) {
            $this->setPackage($options['package']);
            unset($options['package']);
        }

        $this->_setKeys($options);
    }

    /**
     * Sets the encryption keys
     *
     * @param  string|array $keys Key with type association
     * @return Zend_Filter_Encrypt_Openssl
     */
    protected function _setKeys($keys)
    {
        if (!is_array($keys)) {

            throw new Zend_Filter_Exception('Invalid options argument provided to filter');
        }

        foreach ($keys as $type => $key) {
            if (is_file($key) and is_readable($key)) {
                $file = fopen($key, 'r');
                $cert = fread($file, 8192);
                fclose($file);
            } else {
                $cert = $key;
                $key  = count($this->_keys[$type]);
            }

            switch ($type) {
                case 'public':
                    $test = openssl_pkey_get_public($cert);
                    if ($test === false) {

                        throw new Zend_Filter_Exception("Public key '{$cert}' not valid");
                    }

                    openssl_free_key($test);
                    $this->_keys['public'][$key] = $cert;
                    break;
                case 'private':
                    $test = openssl_pkey_get_private($cert, $this->_passphrase);
                    if ($test === false) {

                        throw new Zend_Filter_Exception("Private key '{$cert}' not valid");
                    }

                    openssl_free_key($test);
                    $this->_keys['private'][$key] = $cert;
                    break;
                case 'envelope':
                    $this->_keys['envelope'][$key] = $cert;
                    break;
                default:
                    break;
            }
        }

        return $this;
    }

    /**
     * Returns all public keys
     *
     * @return array
     */
    public function getPublicKey()
    {
        $key = $this->_keys['public'];
        return $key;
    }

    /**
     * Sets public keys
     *
     * @param  string|array $key Public keys
     * @return Zend_Filter_Encrypt_Openssl
     */
    public function setPublicKey($key)
    {
        if (is_array($key)) {
            foreach($key as $type => $option) {
                if ($type !== 'public') {
                    $key['public'] = $option;
                    unset($key[$type]);
                }
            }
        } else {
            $key = array('public' => $key);
        }

        return $this->_setKeys($key);
    }

    /**
     * Returns all private keys
     *
     * @return array
     */
    public function getPrivateKey()
    {
        $key = $this->_keys['private'];
        return $key;
    }

    /**
     * Sets private keys
     *
     * @param  string $key Private key
     * @param  string $passphrase
     * @return Zend_Filter_Encrypt_Openssl
     */
    public function setPrivateKey($key, $passphrase = null)
    {
        if (is_array($key)) {
            foreach($key as $type => $option) {
                if ($type !== 'private') {
                    $key['private'] = $option;
                    unset($key[$type]);
                }
            }
        } else {
            $key = array('private' => $key);
        }

        if ($passphrase !== null) {
            $this->setPassphrase($passphrase);
        }

        return $this->_setKeys($key);
    }

    /**
     * Returns all envelope keys
     *
     * @return array
     */
    public function getEnvelopeKey()
    {
        $key = $this->_keys['envelope'];
        return $key;
    }

    /**
     * Sets envelope keys
     *
     * @param  string|array $options Envelope keys
     * @return Zend_Filter_Encrypt_Openssl
     */
    public function setEnvelopeKey($key)
    {
        if (is_array($key)) {
            foreach($key as $type => $option) {
                if ($type !== 'envelope') {
                    $key['envelope'] = $option;
                    unset($key[$type]);
                }
            }
        } else {
            $key = array('envelope' => $key);
        }

        return $this->_setKeys($key);
    }

    /**
     * Returns the passphrase
     *
     * @return string
     */
    public function getPassphrase()
    {
        return $this->_passphrase;
    }

    /**
     * Sets a new passphrase
     *
     * @param string $passphrase
     * @return Zend_Filter_Encrypt_Openssl
     */
    public function setPassphrase($passphrase)
    {
        $this->_passphrase = $passphrase;
        return $this;
    }

    /**
     * Returns the compression
     *
     * @return array
     */
    public function getCompression()
    {
        return $this->_compression;
    }

    /**
     * Sets a internal compression for values to encrypt
     *
     * @param string|array $compression
     * @return Zend_Filter_Encrypt_Openssl
     */
    public function setCompression($compression)
    {
        if (is_string($this->_compression)) {
            $compression = array('adapter' => $compression);
        }

        $this->_compression = $compression;
        return $this;
    }

    /**
     * Returns if header should be packaged
     *
     * @return boolean
     */
    public function getPackage()
    {
        return $this->_package;
    }

    /**
     * Sets if the envelope keys should be included in the encrypted value
     *
     * @param boolean $package
     * @return Zend_Filter_Encrypt_Openssl
     */
    public function setPackage($package)
    {
        $this->_package = (boolean) $package;
        return $this;
    }

    /**
     * Encrypts $value with the defined settings
     * Note that you also need the "encrypted" keys to be able to decrypt
     *
     * @param  string $value Content to encrypt
     * @return string The encrypted content
     * @throws Zend_Filter_Exception
     */
    public function encrypt($value)
    {
        $encrypted     = array();
        $encryptedkeys = array();

        if (count($this->_keys['public']) == 0) {

            throw new Zend_Filter_Exception('Openssl can not encrypt without public keys');
        }

        $keys         = array();
        $fingerprints = array();
        $count        = -1;
        foreach($this->_keys['public'] as $key => $cert) {
            $keys[$key] = openssl_pkey_get_public($cert);
            if ($this->_package) {
                $details = openssl_pkey_get_details($keys[$key]);
                if ($details === false) {
                    $details = array('key' => 'ZendFramework');
                }

                ++$count;
                $fingerprints[$count] = md5($details['key']);
            }
        }

        // compress prior to encryption
        if (!empty($this->_compression)) {

            $compress = new Zend_Filter_Compress($this->_compression);
            $value    = $compress->filter($value);
        }

        $crypt  = openssl_seal($value, $encrypted, $encryptedkeys, $keys);
        foreach ($keys as $key) {
            openssl_free_key($key);
        }

        if ($crypt === false) {

            throw new Zend_Filter_Exception('Openssl was not able to encrypt your content with the given options');
        }

        $this->_keys['envelope'] = $encryptedkeys;

        // Pack data and envelope keys into single string
        if ($this->_package) {
            $header = pack('n', count($this->_keys['envelope']));
            foreach($this->_keys['envelope'] as $key => $envKey) {
                $header .= pack('H32n', $fingerprints[$key], strlen($envKey)) . $envKey;
            }

            $encrypted = $header . $encrypted;
        }

        return $encrypted;
    }

    /**
     * Defined by Zend_Filter_Interface
     *
     * Decrypts $value with the defined settings
     *
     * @param  string $value Content to decrypt
     * @return string The decrypted content
     * @throws Zend_Filter_Exception
     */
    public function decrypt($value)
    {
        $decrypted = "";
        $envelope  = current($this->getEnvelopeKey());

        if (count($this->_keys['private']) !== 1) {

            throw new Zend_Filter_Exception('Please give a private key for decryption with Openssl');
        }

        if (!$this->_package && empty($envelope)) {

            throw new Zend_Filter_Exception('Please give a envelope key for decryption with Openssl');
        }

        foreach($this->_keys['private'] as $key => $cert) {
            $keys = openssl_pkey_get_private($cert, $this->getPassphrase());
        }

        if ($this->_package) {
            $details = openssl_pkey_get_details($keys);
            if ($details !== false) {
                $fingerprint = md5($details['key']);
            } else {
                $fingerprint = md5("ZendFramework");
            }

            $count = unpack('ncount', $value);
            $count = $count['count'];
            $length  = 2;
            for($i = $count; $i > 0; --$i) {
                $header = unpack('H32print/nsize', substr($value, $length, 18));
                $length  += 18;
                if ($header['print'] == $fingerprint) {
                    $envelope = substr($value, $length, $header['size']);
                }

                $length += $header['size'];
            }

            // remainder of string is the value to decrypt
            $value = substr($value, $length);
        }

        $crypt  = openssl_open($value, $decrypted, $envelope, $keys);
        openssl_free_key($keys);

        if ($crypt === false) {

            throw new Zend_Filter_Exception('Openssl was not able to decrypt you content with the given options');
        }

        // decompress after decryption
        if (!empty($this->_compression)) {

            $decompress = new Zend_Filter_Decompress($this->_compression);
            $decrypted  = $decompress->filter($decrypted);
        }

        return $decrypted;
    }

    /**
     * Returns the adapter name
     *
     * @return string
     */
    public function toString()
    {
        return 'Openssl';
    }
}


<?php

namespace FzyCommon\Entity;

use Doctrine\ORM\Mapping as ORM;
use Zend\Form\Annotation;

/**
 * @ORM\MappedSuperclass
 */
abstract class Base implements BaseInterface
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer");
     * @ORM\GeneratedValue(strategy="AUTO")
     *
     * @Annotation\Exclude()
     *
     * @var int
     */
    protected $id;

    /**
     * Ephemeral value set per-request. Not to be stored in the db
     * @var
     */
    private $formTag;

    public function __construct()
    {
    }

    /**
     * Turn this entity into an associative array
     * @param  boolean $extended
     * @return array
     */
    public function flatten()
    {
        return array('id' => $this->id());
    }

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

    /**
     * Returns whether this is a null object
     * @return bool
     */
    public function isNull()
    {
        return false;
    }

    /**
     * Calls flatten on each of the entities in a collection. If $indexById is true
     * the returned array is a key/value associative array with the entity ids as the key
     * @param $collection
     * @param  bool  $extended
     * @param  bool  $indexById
     * @return array
     */
    public function flatCollection($collection, $extended = false, $indexById = false)
    {
        $results = array();
        foreach ($collection as $entity) {
            if (!$entity instanceof BaseInterface) {
                $results[] = $entity;
                continue;
            }
            $value = $extended ? $entity->flatten() : $entity->id();
            if ($indexById) {
                $results[$entity->id()] = $value;
            } else {
                $results[] = $value;
            }
        }

        return $results;
    }

    /**
     * Helper method to allow entities to set $this->property = $entity->asDoctrineProperty()
     * which will translate setting a null entity to setting a null value
     * @return \FzyCommon\Entity\Base|null
     */
    public function asDoctrineProperty()
    {
        return $this;
    }

    /**
     * Adds $this to collection
     * @param  \Doctrine\Common\Collections\Collection $collection
     * @return mixed
     */
    public function addSelfTo(\Doctrine\Common\Collections\Collection $collection, $allowDuplicates = false)
    {
        if ($allowDuplicates || !$collection->contains($this)) {
            $collection->add($this);
        }

        return $this;
    }

    /**
     * Helper method to allow entities to return
     * $this->nullGet($this->property)
     * and have the entity never return an actual null
     * The second parameter is optional and allows overriding of
     * the null object instantiated by naming convention (classname + 'Null')
     *
     * @param  \FzyCommon\Entity\BaseInterface $entity
     * @param  \FzyCommon\Entity\BaseNull|null $nullObject
     * @return \FzyCommon\Entity\BaseInterface
     */
    public function nullGet(BaseInterface $entity = null, BaseNull $nullObject = null)
    {
        if ($entity === null) {
            if ($nullObject === null) {
                throw new \RuntimeException('Unable to instantiate null class');
            }

            return $nullObject;
        }

        return $entity;
    }

    /**
     * Used to verify the value is valid to be assigned to timestamp property.
     * Acceptable: either \DateTime object or string which can be parsed to a \DateTime value.
     * An \InvalidArgumentException is thrown if the passed value does not meet that criteria
     * @param $ts
     * @param  string | boolean          $timezone - Pass in a \DateTimeZone timezone string or false
     * @return \DateTime
     * @throws \InvalidArgumentException
     */
    public function tsSet($ts, $createIfEmpty = true, $timezone = false)
    {
        if ($ts instanceof \DateTime) {
            return $this->setDtTz($ts, $timezone);
        } elseif (is_string($ts)) {
            return $this->setDtTz(new \DateTime($ts), $timezone);
        } elseif (empty($ts)) {
            return $createIfEmpty ? $this->setDtTz(new \DateTime(), $timezone) : null;
        }

        throw new \InvalidArgumentException("The passed value '".var_export($ts, true)."' is not a valid timestamp.");
    }

    /**
     * @param \DateTime $dt
     * @param $timezone
     *
     * @return \DateTime
     */
    protected function setDtTz(\DateTime $dt, $timezone)
    {
        if ($timezone) {
            $dt->setTimezone(new \DateTimeZone($timezone));
        }

        return $dt;
    }

    /**
     * Used to ensure a \DateTime is returned. If the given property is null, a new \DateTime
     * object is returned.
     * @param  \DateTime $ts The property which may contain a \DateTime value
     * @return \DateTime
     */
    public function tsGet(\DateTime $tsProperty = null)
    {
        if (empty($tsProperty)) {
            $tsProperty = new \DateTime();
        }

        return $tsProperty;
    }

    /**
     * Returns a formatted form of the datetime property, if the property is not null
     *
     * NOTE: the datetime is cloned and converted to EDT timezone since all doctrine
     * data is UTC (coming from RDS)
     * @param  \DateTime $tsProperty
     * @param $format
     * @param  string    $timezone   - Pass in a timezone string or false
     * @return string
     */
    public function tsGetFormatted(\DateTime $tsProperty = null, $format = self::DEFAULT_DATE_FORMAT, $timezone = null)
    {
        if ($tsProperty === null) {
            return '';
        }
        $shiftedTs = clone $tsProperty;

        return $this->setDtTz($shiftedTs, $timezone)->format($format);
    }

    public function __toString()
    {
        return json_encode($this);
    }

    /**
     * Form Tag set on this entity for this request
     * @return mixed
     */
    public function getFormTag()
    {
        return $this->formTag;
    }

    /**
     * Retrieve tag set on this entity
     * @param $tag
     * @return mixed
     */
    public function setFormTag($tag)
    {
        $this->formTag = $tag;

        return $this;
    }

    /**
     * (PHP 5 >= 5.4.0)

     * Specify data which should be serialized to JSON
     * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
     * @return mixed data which can be serialized by json_encode,
     *               which is a value of any type other than a resource.
     */
    public function jsonSerialize()
    {
        return $this->flatten();
    }
}


<?php namespace Ordercloud\Requests\Auth\Handlers;

use Ordercloud\Ordercloud;
use Ordercloud\Requests\Auth\ExpiredTokenRequest;
use Ordercloud\Requests\Exceptions\AccessTokenExpiredException;
use Ordercloud\Requests\Handlers\OrdercloudRequestHandler;
use Ordercloud\Services\AuthService;
use Ordercloud\Support\CommandBus\CommandHandler;
use Ordercloud\Support\Http\Client;
use Ordercloud\Support\Http\Response;
use Ordercloud\Support\Http\UrlParameteriser;
use Ordercloud\Support\TokenRefresher;

class ExpiredTokenRequestHandler implements CommandHandler
{
    /**
     * @var Ordercloud
     */
    private $ordercloud;
    /**
     * @var TokenRefresher
     */
    private $tokenRefresher;
    /**
     * @var AuthService
     */
    private $auth;

    public function __construct(Ordercloud $ordercloud, TokenRefresher $tokenRefresher, AuthService $auth)
    {
        $this->ordercloud = $ordercloud;
        $this->tokenRefresher = $tokenRefresher;
        $this->auth = $auth;
    }

    /**
     * @param ExpiredTokenRequest $request
     *
     * @return Response
     *
     * @throws AccessTokenExpiredException
     */
    public function handle($request)
    {
        $accessToken = $this->tokenRefresher->refresh($this->auth);

        $this->ordercloud->setAccessToken((string) $accessToken);

        return $this->ordercloud->exec($request->getPreviousRequest());
    }
}


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

use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * The default user provider for getting user from Symfony Token Storage.
 *
 * @author Vitaliy Zhuk <v.zhuk@fivelab.org>
 */
class SymfonyTokenStorageUserProvider implements UserProviderInterface
{
    /**
     * @var TokenStorageInterface
     */
    private $tokenStorage;

    /**
     * Constructor.
     *
     * @param TokenStorageInterface $tokenStorage
     */
    public function __construct(TokenStorageInterface $tokenStorage)
    {
        $this->tokenStorage = $tokenStorage;
    }

    /**
     * {@inheritdoc}
     */
    public function getUser(): UserInterface
    {
        $token = $this->tokenStorage->getToken();

        if (!$token) {
            throw new AccessDeniedException('The token was not found.');
        }

        $user = $token->getUser();

        if (!$user || !$user instanceof UserInterface) {
            throw new AccessDeniedException('The user is invalid.');
        }

        return $user;
    }
}


<?php
namespace Gosyl\CommonBundle\Service;

use Doctrine\ORM\EntityManager;
use Gosyl\CommonBundle\Constantes;
use Gosyl\CommonBundle\Entity\ParamUsersRepository;
use Symfony\Component\DependencyInjection\Container;

class Users {
    private $_sUrl = 'ajax/listerutilisateur';

	private $_cols = array(
			'id' => array(
					'title' => 'id',
					'data' => 'id',
					'visible' => false,
			),
			'username' => array(
					'title' => 'Login',
					'data' => 'username',
			),
			'nom' => array(
					'title' => 'Nom',
					'data' => 'name'
			),
			'prenom' => array(
					'title' => 'Prenom',
					'data' => 'prenom'
			),
			'dateInscription' => array(
					'title' => 'Date d\'inscription',
					'data' => 'dateInscription',
			),
			'dateNaissance' => array(
					'title' => 'Date de naissance',
					'data' => 'dateNaissance',
					'visible' => false,
			),
			'isActive' => array(
					'title' => 'Utilisateur Actif',
					'data' => 'isActive',
					'visible' => false,
			),
			'roles' => array(
					'title' => 'Type d\'utilisateur',
					'data' => 'roles',
			),
			'email' => array(
					'data' => 'email',
					'title' => 'Email',
			),
			'action' => array(
					'title' => 'action',
					'data' => 'null',
					"orderable" => false,
					'render' => array(
							'render' => 'function(oObject) {
			                    var contenu = Gosyl.Common.GestionUtilisateur.gereUtilisateur(oObject);
			                    return contenu;
			                }',
                    )
			),
	);

	private $_allUserOptions = array(
        //'jQueryUI' => true,
        'responsive' => true,
        'paging' => true,
        'autoWidth' => false,
        'stateSave' => true,
        'retrieve' => false,
        'searching' => false,
        'pageLength' => 10,
        'pagingType' => 'full_numbers',
        'dom' => '<"H"RCTlf>t<"F"rpi>',
        'initComplete' => array(
            'function' => 'function(settings, json) {
                Gosyl.Common.GestionUtilisateur.dataTableId = $(this).attr("id");
                Gosyl.Common.GestionUtilisateur.init();
            }'
        ),
        'createdRow' => array(
            'function' => 'function(row, data, dataIndex) {
                $(row).data(\'user\', data);
                $(row).attr(\'id\', \'data_\' + data.id);
            }',
        ),
	);

	private $_OneUserOptions = array(
        //'jQueryUI' => true,
        'responsive' => true,
        'paging' => false,
        'autoWidth' => false,
        'stateSave' => true,
        'retrieve' => true,
        'searching' => false,
        'info' => false,
        'sort' => false,
        'lengthChange' => false,
        //'pageLength' => 10,
        //'pagingType' => 'full_numbers',
        'dom' => '<"H"RCTlf>t<"F"rpi>',
        'initComplete' => array(
            'function' => 'function(settings, json) {
                Gosyl.Common.GestionUtilisateur.dataTableId = $(this).attr("id");
                Gosyl.Common.GestionUtilisateur.init();
            }'
        ),
        'createdRow' => array(
            'function' => 'function(row, data, dataIndex) {
                $(row).data(\'user\', data);
                $(row).attr(\'id\', \'data_\' + data.id);
            }',
        ),
	);

	static public $aDialogMsgErreurSuppr = 'Erreur lors de la suppression de l\'utilisateur';

	static public $aDialogMsgErreurRest = 'Erreur lors de la restauration de l\'utilisateur';

	static public $aDialogOptionsErreur = array(
			'dialogOptions' => array(
					'events' => array(
							'open' => array(
									'data' => array(
											'function' => '{
					                            $("#" + $(this).attr("id") + " p").append(" " + $(this).data("dataUtilisateur").login + "");
					                        }',
									),
									'ecrasement' => false,
							),
							'close' => array(
									'data' => array(
											'function' => '{
					                            $("#" + $(this).attr("id") + " p b").remove();
					                        }',
									),
									'ecrasement' => true,
							),
					),
			),
			'idDialog' => 'dialogErrorSupprUtilisateur',
	);

	/*-- Modal form ModifUser --*/
	public static $aModalFormModifUser = array(
			'dialogOptions' => array(
					'options' => array(
							'autoOpen' => array(
									'data' => false,
									'ecrasement' => true,
							),
							'resizable' => array(
									'data' => false,
									'ecrasement' => true,
							),
							'width' => array(
									'data' => "auto",
									'ecrasement' => true,
							),
							'buttons' => array(
									'data' => array(),
									'ecrasement' => true,
							),
					),
					'events' => array(
							'open' => array(
									'data' => array(
											'function' => '{
					    	                    Gosyl.Common.GestionUtilisateur.populateModifForm($(event.target).data("dataUtilisateur"));
					    	                    $(".ui-dialog .ui-dialog-titlebar .ui-dialog-title").css("display", "none");
					    	                    $(".ui-dialog .ui-dialog-titlebar .ui-dialog-title").parent().css("display", "none");
					                        }',
									),
									'ecrasement' => false,
							),
							'close' => array(
									'data' => array(
											'function' => '{
					                            /*var elemPrec = $("#dialogModifUtilisateur #modification_roles_element").get(0).previousElementSibling;
					                            $(elemPrec).html(" ");*/
					    	                    $.each($("#modification input"), function(i, oInput) {
					                                $(oInput).prop("disabled", false);
					                            });
					    	                    $.each($("#modification .espace"), function(i, oDiv){
					                                $(oDiv).html(" ").removeClass("error");
					                            });
					                            $(".ui-dialog .ui-dialog-titlebar .ui-dialog-title").css("display", "block");
					    	                    $(".ui-dialog .ui-dialog-titlebar .ui-dialog-title").parent().css("display", "block");
					                        }',
									),
									'ecrasement' => true,
							),
					),
			),
			'idDialog' => 'dialogModifUtilisateur',
	);

	/**
	 * @var EntityManager
	 */
	protected $_oDoctrine;

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

	/**
	 * @var ParamUsersRepository
	 */
	protected $_oParamUsersRepository;

	public function __construct(EntityManager $oDoctrine, Container $oContainer) {
		$this->_oDoctrine = $oDoctrine;
		$this->_oContainer = $oContainer;

		$this->_oParamUsersRepository = $this->_oDoctrine->getRepository('GosylCommonBundle:ParamUsers');
	}

    public function getAllUserForDataTable($sUrl) {
		$aResult = array();
		$aResult['options'] = array_merge($this->_allUserOptions, Constantes::$aDataTableLanguage);
		$aResult['cols'] = $this->_cols;
        $aResult['results'] = $sUrl;

		return $aResult;
	}

    public function getOneUserForDataTable($idUser, $sUrl)
    {
		$aResult = array();
		$aResult['options'] = array_merge($this->_OneUserOptions, Constantes::$aDataTableLanguage);
		$aResult['cols'] = $this->_cols;
		unset($aResult['cols']['roles']);
        //$aUser = $this->listerUtilisateursForDataTable($this->_oContainer->get('security.token_storage')->getToken()->getUser(), $idUser);
        $aResult['results'] = $sUrl . '/' . $idUser;

		return $aResult;
	}

	public function listerUtilisateursForDataTable($oActualUser, $idUser) {
		//echo "
";var_dump(get_class_methods ($this->_oParamUsersRepository));die('
');
		if(!is_null($idUser)) {
			$aWhere = array('U.id' => array('val' => $idUser, 'type' => 'number', 'bind' => ':idUser'));
		} else {
			$aWhere = null;
		}

		$aResultSet = $this->_oParamUsersRepository->getAllForDataTable($aWhere);
		foreach ($aResultSet['data'] as $key => $aValue) {
			$aResultSet['data'][$key]['roles'] = array_key_exists(0, $aValue['roles']) ? $aValue['roles'][0] : 'ROLE_USER';
			$aResultSet['data'][$key]['dateNaissance'] = $aValue['dateNaissance']->format('d/m/Y');
			$aResultSet['data'][$key]['dateInscription'] = $aValue['dateInscription']->format('d/m/Y');

			if(!is_null($aValue['dateSuppression'])) {
				$aResultSet['data'][$key]['dateSuppression'] = $aValue['dateSuppression']->format('d/m/Y');
				$aResultSet['data'][$key]['bDeleted'] = true;
			} else {
				$aResultSet['data'][$key]['bDeleted'] = false;
			}

			if($oActualUser->getId() == $aValue['id']) {
				$aResultSet['data'][$key]['isActualUser'] = true;
			} else {
				$aResultSet['data'][$key]['isActualUser'] = false;
			}

		}
		//var_dump($aResultSet);die;
		return $aResultSet;
	}

	public function banUtilisateur($idUser, $sMode) {
		$result = $this->_oParamUsersRepository->banUtilisateur($idUser, $sMode == 'active' ? '1' : '0');

		$aVarReturn = array('error' => false, 'result' => $result, 'reasons' => array());

		return $aVarReturn;
	}

	/**
	 * Suppression d'un utilisateur
	 * @param int $idUser
	 * @return array
	 */
	public function supprimerUtilisateur($idUser) {
		$oDateNow = new \DateTime('now');

		$iReturn = $this->_oParamUsersRepository->supprimerUtilisateur($idUser, $oDateNow);

		if($iReturn != 1) {
			$aVarReturn = array(
					'error' => true,
					'reasons' => array(
							'msg'=>'Une erreur s\'est produite durant la suppression'
					),
			);
		} else {
			$aVarReturn = array(
					'error' => false,
					'reasons' => null,
					'nbMaj' => $iReturn,
			);
		}
		return $aVarReturn;
	}

	public function restaurerUtilisateur($idUser) {
		$iReturn = $this->_oParamUsersRepository->restaureUtilisateur($idUser);

		if($iReturn != 1) {
			$aVarReturn = array(
					'error' => true,
					'reasons' => array(
							'msg'=>'Une erreur s\'est produite durant la suppression'
					),
			);
		} else {
			$aVarReturn = array(
					'error' => false,
					'reasons' => null,
					'nbMaj' => $iReturn,
			);
		}
		return $aVarReturn;
	}

    public function updateUtilisateur($aData, $sOldRole = null) {
		if(array_key_exists('dateNaissance', $aData)) {
		    $aData['dateNaissance'] = \DateTime::createFromFormat('d/m/Y H:i:s', $aData['dateNaissance'] . ' 00:00:00');
		}

        $aDataToModify = array();
        foreach ($aData as $key => $value) {
            $aDataToModify['U.' . $key] = $value;
        }

        if (!is_null($sOldRole)) {
            $bIsAdmin = false;
            if (array_key_exists('roles', $aData)) {
                foreach (Constantes::$aPrivileges as $role => $key) {
                    if ($key == $aData['roles']) {
                        $aData['roles'] = serialize(array($role));
                        $bIsAdmin = $role == Constantes::ROLE_ADMIN ? true : false;
                    }
                }

            } else {
                $bIsAdmin = $sOldRole == Constantes::ROLE_ADMIN ? true : false;
            }

            $iNbAdmin = count($this->getAdmin());

            if ($iNbAdmin >= 1 && $sOldRole == Constantes::ROLE_ADMIN && $bIsAdmin) {
                // On peut modifier les informations d'un admin
                $result = $this->_oParamUsersRepository->modifierUsers($aDataToModify, $aData['id']);
                $aVarReturn = array('error' => false, 'result' => $result, 'reasons' => array());
            } elseif ($iNbAdmin == 1 && $sOldRole == Constantes::ROLE_ADMIN && !$bIsAdmin) {
                // On ne peut pas changer le privilege d'un admin s'il est le seul
                $aVarReturn = array('error' => true, 'reasons' => array('form' => 'Changement de privilège du dernier admin'));
            } elseif ($iNbAdmin > 1 && $sOldRole == Constantes::ROLE_ADMIN && !$bIsAdmin) {
                // On peut changer le privilège d'un admin s'il n'est pas le seul
                $result = $this->_oParamUsersRepository->modifierUsers($aDataToModify, $aData['id']);
                $aVarReturn = array('error' => false, 'result' => $result, 'reasons' => array());
            } else {
                // On peut modifier les autres utilisateurs
                $result = $this->_oParamUsersRepository->modifierUsers($aDataToModify, $aData['id']);
                $aVarReturn = array('error' => false, 'result' => $result, 'reasons' => array());
            }
        } else {
            $result = $this->_oParamUsersRepository->modifierUsers($aDataToModify, $aData['id']);
            $aVarReturn = array('error' => false, 'result' => $result, 'reasons' => array());
        }

	    return $aVarReturn;
	}

	public function updatePassword($PwdEncoded, $idUser) {
		$iReturn = $this->_oParamUsersRepository->updatePassword($PwdEncoded, $idUser);

		return $iReturn;
	}

	public function getAdmin() {
		$aReturn = $this->_oParamUsersRepository->getAdmin();

		return $aReturn;
	}

	public function getUserById($id) {
		$aReturn = $this->_oParamUsersRepository->getUserById($id);

		return $aReturn;
	}
}


<?php

namespace Kcs\FunctionMock\Promise;

use Kcs\FunctionMock\Exception\InvalidArgumentException;
use Kcs\FunctionMock\FunctionProphecy;

/**
 * Return argument promise.
 */
class ReturnArgumentPromise implements PromiseInterface
{
    /**
     * @var int
     */
    private $index;

    /**
     * Initializes callback promise.
     *
     * @param int $index The zero-indexed number of the argument to return
     *
     * @throws InvalidArgumentException
     */
    public function __construct($index = 0)
    {
        if (!is_int($index) || $index < 0) {
            throw new InvalidArgumentException(sprintf(
                'Zero-based index expected as argument to ReturnArgumentPromise, but got %s.',
                $index
            ));
        }
        $this->index = $index;
    }

    /**
     * Returns nth argument if has one, null otherwise.
     *
     * @param array          $args
     * @param FunctionProphecy $function
     *
     * @return null|mixed
     */
    public function execute(array $args, FunctionProphecy $function)
    {
        return count($args) > $this->index ? $args[$this->index] : null;
    }
}


<?php

namespace Reaction\Console\Controllers;

use Reaction\Base\ComponentInitBlockingInterface;
use Reaction\Db\DatabaseInterface;
use Reaction\Db\Query;
use Reaction\Db\TableSchema;
use Reaction\DI\Instance;
use Reaction\Helpers\ArrayHelper;
use Reaction\Helpers\Console;
use function Reaction\Promise\allInOrder;
use Reaction\Promise\ExtendedPromiseInterface;
use function Reaction\Promise\resolve;
use Reaction\RequestApplicationInterface;

/**
 * Manages application migrations.
 * A migration means a set of persistent changes to the application environment
 * that is shared among different developers. For example, in an application
 * backed by a database, a migration may refer to a set of changes to
 * the database, such as creating a new table, adding a new table column.
 *
 * This command provides support for tracking the migration history, upgrading
 * or downloading with migrations, and creating new migration skeletons.
 *
 * The migration history is stored in a database table named
 * as [[migrationTable]]. The table will be automatically created the first time
 * this command is executed, if it does not exist. You may also manually
 * create it as follows:
 *
 * ```sql
 * CREATE TABLE migration (
 *     version varchar(180) PRIMARY KEY,
 *     apply_time integer
 * )
 * ```
 *
 * Below are some common usages of this command:
 *
 * ```
 * # creates a new migration named 'create_user_table'
 * console migrate/create create_user_table
 *
 * # applies ALL new migrations
 * console migrate
 *
 * # reverts the last applied migration
 * console migrate/down
 * ```
 *
 * You can use namespaced migrations. In order to enable this feature you should configure [[migrationNamespaces]]
 * property for the controller at application configuration:
 *
 * ```php
 * return [
 *     'controllerMap' => [
 *         'migrate' => [
 *             'class' => 'Reaction\Console\Controllers\MigrateController',
 *             'migrationNamespaces' => [
 *                 'App\Migrations',
 *                 'Some\Namespace\Migrations',
 *             ],
 *             //'migrationPath' => null, // allows to disable not namespaced migration completely
 *         ],
 *     ],
 * ];
 * ```
 */
class MigrateController extends BaseMigrateController
{
    /**
     * Maximum length of a migration name.
     */
    const MAX_NAME_LENGTH = 180;

    /**
     * @var string the name of the table for keeping applied migration information.
     */
    public $migrationTable = '{{%migration}}';
    /**
     * {@inheritdoc}
     */
    public $templateFile = '@reaction/Views/migration/migration.php';
    /**
     * @var array a set of template paths for generating migration code automatically.
     *
     * The key is the template type, the value is a path or the alias. Supported types are:
     * - `create_table`: table creating template
     * - `drop_table`: table dropping template
     * - `add_column`: adding new column template
     * - `drop_column`: dropping column template
     * - `create_junction`: create junction template
     */
    public $generatorTemplateFiles = [
        'create_table' => '@reaction/Views/migration/createTableMigration.php',
        'drop_table' => '@reaction/Views/migration/dropTableMigration.php',
        'add_column' => '@reaction/Views/migration/addColumnMigration.php',
        'drop_column' => '@reaction/Views/migration/dropColumnMigration.php',
        'create_junction' => '@reaction/Views/migration/createTableMigration.php',
    ];
    /**
     * @var bool indicates whether the table names generated should consider
     * the `tablePrefix` setting of the DB connection. For example, if the table
     * name is `post` the generator wil return `{{%post}}`.
     */
    public $useTablePrefix = false;
    /**
     * @var array column definition strings used for creating migration code.
     *
     * The format of each definition is `COLUMN_NAME:COLUMN_TYPE:COLUMN_DECORATOR`. Delimiter is `,`.
     * For example, `--fields="name:string(12):notNull:unique"`
     * produces a string column of size 12 which is not null and unique values.
     *
     * Note: primary key is added automatically and is named id by default.
     * If you want to use another name you may specify it explicitly like
     * `--fields="id_key:primaryKey,name:string(12):notNull:unique"`
     */
    public $fields = [];
    /**
     * @var DatabaseInterface|array|string the DB connection object or the application component ID of the DB connection to use
     * when applying migrations. Starting from version 2.0.3, this can also be a configuration array
     * for creating the object.
     */
    public $db = 'db';
    /**
     * @var string the comment for the table being created.
     */
    public $comment = '';

    /**
     * {@inheritdoc}
     */
    public function options($actionId = null)
    {
        return array_merge(
            parent::options($actionId),
            ['migrationTable', 'db'], // global for all actions
            $actionId === 'create'
                ? ['templateFile', 'fields', 'useTablePrefix', 'comment']
                : []
        );
    }

    /**
     * {@inheritdoc}
     */
    public function optionAliases()
    {
        return array_merge(parent::optionAliases(), [
            'C' => 'comment',
            'f' => 'fields',
            'p' => 'migrationPath',
            't' => 'migrationTable',
            'F' => 'templateFile',
            'P' => 'useTablePrefix',
            'c' => 'compact',
        ]);
    }

    /**
     * This method is invoked right before an action is to be executed (after all possible filters.)
     * It checks the existence of the [[migrationPath]].
     * @param string $actionId the action to be executed.
     * @return bool whether the action should continue to be executed.
     */
    public function beforeAction($actionId)
    {
        if (parent::beforeAction($actionId)) {
            if (!is_object($this->db)) {
                $this->db = \Reaction::$app->get($this->db);
            }
            return true;
        }

        return false;
    }

    /**
     * Creates a new migration instance.
     * @param string $class the migration class name
     * @return ExtendedPromiseInterface with \Reaction\Db\Migration the migration instance
     */
    protected function createMigration($class)
    {
        $this->includeMigrationFile($class);

        $migration = \Reaction::create([
            'class' => $class,
            'db' => $this->db,
            'compact' => $this->compact,
        ]);

        if ($migration instanceof ComponentInitBlockingInterface) {
            return $migration->initComponent()
                ->then(function() use ($migration) {
                    return $migration;
                });
        }

        return resolve($migration);
    }

    /**
     * {@inheritdoc}
     */
    protected function getMigrationHistory($limit)
    {
        if ($this->db->getSchema()->getTableSchema($this->migrationTable, true) === null) {
            $promise = $this->createMigrationHistoryTable();
        } else {
            $promise = resolve(true);
        }
        return $promise->then(function() use ($limit) {
            $query = (new Query())
                ->select(['version', 'apply_time'])
                ->from($this->migrationTable)
                ->orderBy(['apply_time' => SORT_DESC, 'version' => SORT_DESC]);

            if (empty($this->migrationNamespaces)) {
                $query->limit($limit);
            }
            return $query->all($this->db);
        })->then(function($rows) use ($limit) {
            if (empty($this->migrationNamespaces)) {
                $history = ArrayHelper::map($rows, 'version', 'apply_time');
                unset($history[self::BASE_MIGRATION]);
                return $history;
            }

            $history = [];
            foreach ($rows as $key => $row) {
                if ($row['version'] === self::BASE_MIGRATION) {
                    continue;
                }
                if (preg_match('/m?(\d{6}_?\d{6})(\D.*)?$/is', $row['version'], $matches)) {
                    $time = str_replace('_', '', $matches[1]);
                    $row['canonicalVersion'] = $time;
                } else {
                    $row['canonicalVersion'] = $row['version'];
                }
                $row['apply_time'] = (int)$row['apply_time'];
                $history[] = $row;
            }

            usort($history, function($a, $b) {
                if ($a['apply_time'] === $b['apply_time']) {
                    if (($compareResult = strcasecmp($b['canonicalVersion'], $a['canonicalVersion'])) !== 0) {
                        return $compareResult;
                    }

                    return strcasecmp($b['version'], $a['version']);
                }

                return ($a['apply_time'] > $b['apply_time']) ? -1 : +1;
            });

            $history = array_slice($history, 0, $limit);

            $history = ArrayHelper::map($history, 'version', 'apply_time');

            return $history;
        });
    }

    /**
     * Creates the migration history table.
     * @return ExtendedPromiseInterface
     */
    protected function createMigrationHistoryTable()
    {
        $tableName = $this->db->getSchema()->getRawTableName($this->migrationTable);
        $this->stdout("Creating migration history table \"$tableName\"...", Console::FG_YELLOW);
        $promises = [];
        $promises[] = $this->db->createCommand()->createTable($this->migrationTable, [
            'version' => 'varchar(' . static::MAX_NAME_LENGTH . ') NOT NULL PRIMARY KEY',
            'apply_time' => 'integer',
        ])->execute();
        $promises[] = $this->db->createCommand()->insert($this->migrationTable, [
            'version' => self::BASE_MIGRATION,
            'apply_time' => time(),
        ])->execute();
        return allInOrder($promises)->then(function() {
            $this->stdout("Done.\n", Console::FG_GREEN);
            return true;
        });
    }

    /**
     * {@inheritdoc}
     */
    protected function addMigrationHistory($version)
    {
        $command = $this->db->createCommand();
        return $command->insert($this->migrationTable, [
            'version' => $version,
            'apply_time' => time(),
        ])->execute();
    }

    /**
     * {@inheritdoc}
     */
    protected function truncateDatabase()
    {
        $db = $this->db;
        return $db->getSchema()->getTableSchemas()->then(
            function($schemas) use (&$db) {
                /** @var TableSchema[] $schemas */
                $promises = [];
                // First drop all foreign keys,
                foreach ($schemas as $schema) {
                    if ($schema->foreignKeys) {
                        foreach ($schema->foreignKeys as $name => $foreignKey) {
                            $promises[] = $db->createCommand()->dropForeignKey($name, $schema->name)->execute(true)
                                ->thenLazy(function() use ($name) {
                                    $this->stdout("Foreign key $name dropped.\n");
                                    return true;
                                });
                        }
                    }
                }
                // Then drop the tables:
                foreach ($schemas as $schema) {
                    $promises[] = $db->createCommand()->dropTable($schema->name)->execute(true)
                        ->thenLazy(function() use ($schema) {
                            $this->stdout("Table {$schema->name} dropped.\n");
                            return true;
                        });
                }
                return allInOrder($promises);
            }
        );
    }

    /**
     * {@inheritdoc}
     */
    protected function removeMigrationHistory($version)
    {
        $command = $this->db->createCommand();
        return $command->delete($this->migrationTable, [
            'version' => $version,
        ])->execute();
    }

    private $_migrationNameLimit;

    /**
     * {@inheritdoc}
     */
    protected function getMigrationNameLimit()
    {
        if ($this->_migrationNameLimit !== null) {
            return $this->_migrationNameLimit;
        }
        $tableSchema = $this->db->getSchema() ? $this->db->getSchema()->getTableSchema($this->migrationTable, true) : null;
        if ($tableSchema !== null) {
            return $this->_migrationNameLimit = $tableSchema->columns['version']->size;
        }

        return static::MAX_NAME_LENGTH;
    }

    /**
     * {@inheritdoc}
     */
    protected function generateMigrationSourceCode($params, RequestApplicationInterface $app)
    {
        $parsedFields = $this->parseFields();
        $fields = $parsedFields['fields'];
        $foreignKeys = $parsedFields['foreignKeys'];

        $name = $params['name'];

        $templateFile = $this->templateFile;
        $table = null;
        if (preg_match('/^create_junction(?:_table_for_|_for_|_)(.+)_and_(.+)_tables?$/', $name, $matches)) {
            $templateFile = $this->generatorTemplateFiles['create_junction'];
            $firstTable = $matches[1];
            $secondTable = $matches[2];

            $fields = array_merge(
                [
                    [
                        'property' => $firstTable . '_id',
                        'decorators' => 'integer()',
                    ],
                    [
                        'property' => $secondTable . '_id',
                        'decorators' => 'integer()',
                    ],
                ],
                $fields,
                [
                    [
                        'property' => 'PRIMARY KEY(' .
                            $firstTable . '_id, ' .
                            $secondTable . '_id)',
                    ],
                ]
            );

            $foreignKeys[$firstTable . '_id']['table'] = $firstTable;
            $foreignKeys[$secondTable . '_id']['table'] = $secondTable;
            $foreignKeys[$firstTable . '_id']['column'] = null;
            $foreignKeys[$secondTable . '_id']['column'] = null;
            $table = $firstTable . '_' . $secondTable;
        } elseif (preg_match('/^add_(.+)_columns?_to_(.+)_table$/', $name, $matches)) {
            $templateFile = $this->generatorTemplateFiles['add_column'];
            $table = $matches[2];
        } elseif (preg_match('/^drop_(.+)_columns?_from_(.+)_table$/', $name, $matches)) {
            $templateFile = $this->generatorTemplateFiles['drop_column'];
            $table = $matches[2];
        } elseif (preg_match('/^create_(.+)_table$/', $name, $matches)) {
            $this->addDefaultPrimaryKey($fields);
            $templateFile = $this->generatorTemplateFiles['create_table'];
            $table = $matches[1];
        } elseif (preg_match('/^drop_(.+)_table$/', $name, $matches)) {
            $this->addDefaultPrimaryKey($fields);
            $templateFile = $this->generatorTemplateFiles['drop_table'];
            $table = $matches[1];
        }

        foreach ($foreignKeys as $column => $foreignKey) {
            $relatedColumn = $foreignKey['column'];
            $relatedTable = $foreignKey['table'];
            // If related column name is not specified,
            // we're trying to get it from table schema
            // @see https://github.com/yiisoft/yii2/issues/12748
            if ($relatedColumn === null) {
                $relatedColumn = 'id';
                try {
                    $this->db = Instance::ensure($this->db, DatabaseInterface::class);
                    $relatedTableSchema = $this->db->getTableSchema($relatedTable);
                    if ($relatedTableSchema !== null) {
                        $primaryKeyCount = count($relatedTableSchema->primaryKey);
                        if ($primaryKeyCount === 1) {
                            $relatedColumn = $relatedTableSchema->primaryKey[0];
                        } elseif ($primaryKeyCount > 1) {
                            $this->stdout("Related table for field \"{$column}\" exists, but primary key is composite. Default name \"id\" will be used for related field\n", Console::FG_YELLOW);
                        } elseif ($primaryKeyCount === 0) {
                            $this->stdout("Related table for field \"{$column}\" exists, but does not have a primary key. Default name \"id\" will be used for related field.\n", Console::FG_YELLOW);
                        }
                    }
                } catch (\ReflectionException $e) {
                    $this->stdout("Cannot initialize database component to try reading referenced table schema for field \"{$column}\". Default name \"id\" will be used for related field.\n", Console::FG_YELLOW);
                }
            }
            $foreignKeys[$column] = [
                'idx' => $this->generateTableName("idx-$table-$column"),
                'fk' => $this->generateTableName("fk-$table-$column"),
                'relatedTable' => $this->generateTableName($relatedTable),
                'relatedColumn' => $relatedColumn,
            ];
        }

        return $this->renderFile($app, \Reaction::$app->getAlias($templateFile), array_merge($params, [
            'table' => $this->generateTableName($table),
            'fields' => $fields,
            'foreignKeys' => $foreignKeys,
            'tableComment' => $this->comment,
        ]));
    }

    /**
     * If `useTablePrefix` equals true, then the table name will contain the
     * prefix format.
     *
     * @param string $tableName the table name to generate.
     * @return string
     */
    protected function generateTableName($tableName)
    {
        if (!$this->useTablePrefix) {
            return $tableName;
        }

        return '{{%' . $tableName . '}}';
    }

    /**
     * Parse the command line migration fields.
     * @return array parse result with following fields:
     *
     * - fields: array, parsed fields
     * - foreignKeys: array, detected foreign keys
     */
    protected function parseFields()
    {
        $fields = [];
        $foreignKeys = [];

        foreach ($this->fields as $index => $field) {
            $chunks = preg_split('/\s?:\s?/', $field, null);
            $property = array_shift($chunks);

            foreach ($chunks as $i => &$chunk) {
                if (strncmp($chunk, 'foreignKey', 10) === 0) {
                    preg_match('/foreignKey\((\w*)\s?(\w*)\)/', $chunk, $matches);
                    $foreignKeys[$property] = [
                        'table' => isset($matches[1])
                            ? $matches[1]
                            : preg_replace('/_id$/', '', $property),
                        'column' => !empty($matches[2])
                            ? $matches[2]
                            : null,
                    ];

                    unset($chunks[$i]);
                    continue;
                }

                if (!preg_match('/^(.+?)\(([^(]+)\)$/', $chunk)) {
                    $chunk .= '()';
                }
            }
            $fields[] = [
                'property' => $property,
                'decorators' => implode('->', $chunks),
            ];
        }

        return [
            'fields' => $fields,
            'foreignKeys' => $foreignKeys,
        ];
    }

    /**
     * Adds default primary key to fields list if there's no primary key specified.
     * @param array $fields parsed fields
     */
    protected function addDefaultPrimaryKey(&$fields)
    {
        foreach ($fields as $field) {
            if (false !== strripos($field['decorators'], 'primarykey()')) {
                return;
            }
        }
        array_unshift($fields, ['property' => 'id', 'decorators' => 'primaryKey()']);
    }
}