<?php
/**
 * PEAR_Command, command pattern class
 *
 * PHP versions 4 and 5
 *
 * @category   pear
 * @package    PEAR
 * @author     Stig Bakken <ssb@php.net>
 * @author     Greg Beaver <cellog@php.net>
 * @copyright  1997-2009 The Authors
 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
 * @version    CVS: $Id: Command.php 313023 2011-07-06 19:17:11Z dufuz $
 * @link       http://pear.php.net/package/PEAR
 * @since      File available since Release 0.1
 */

/**
 * Needed for error handling
 */
require_once 'PEAR.php';
require_once 'PEAR/Frontend.php';
require_once 'PEAR/XMLParser.php';

/**
 * List of commands and what classes they are implemented in.
 * @var array command => implementing class
 */
$GLOBALS['_PEAR_Command_commandlist'] = array();

/**
 * List of commands and their descriptions
 * @var array command => description
 */
$GLOBALS['_PEAR_Command_commanddesc'] = array();

/**
 * List of shortcuts to common commands.
 * @var array shortcut => command
 */
$GLOBALS['_PEAR_Command_shortcuts'] = array();

/**
 * Array of command objects
 * @var array class => object
 */
$GLOBALS['_PEAR_Command_objects'] = array();

/**
 * PEAR command class, a simple factory class for administrative
 * commands.
 *
 * How to implement command classes:
 *
 * - The class must be called PEAR_Command_Nnn, installed in the
 *   "PEAR/Common" subdir, with a method called getCommands() that
 *   returns an array of the commands implemented by the class (see
 *   PEAR/Command/Install.php for an example).
 *
 * - The class must implement a run() function that is called with three
 *   params:
 *
 *    (string) command name
 *    (array)  assoc array with options, freely defined by each
 *             command, for example:
 *             array('force' => true)
 *    (array)  list of the other parameters
 *
 *   The run() function returns a PEAR_CommandResponse object.  Use
 *   these methods to get information:
 *
 *    int getStatus()   Returns PEAR_COMMAND_(SUCCESS|FAILURE|PARTIAL)
 *                      *_PARTIAL means that you need to issue at least
 *                      one more command to complete the operation
 *                      (used for example for validation steps).
 *
 *    string getMessage()  Returns a message for the user.  Remember,
 *                         no HTML or other interface-specific markup.
 *
 *   If something unexpected happens, run() returns a PEAR error.
 *
 * - DON'T OUTPUT ANYTHING! Return text for output instead.
 *
 * - DON'T USE HTML! The text you return will be used from both Gtk,
 *   web and command-line interfaces, so for now, keep everything to
 *   plain text.
 *
 * - DON'T USE EXIT OR DIE! Always use pear errors.  From static
 *   classes do PEAR::raiseError(), from other classes do
 *   $this->raiseError().
 * @category   pear
 * @package    PEAR
 * @author     Stig Bakken <ssb@php.net>
 * @author     Greg Beaver <cellog@php.net>
 * @copyright  1997-2009 The Authors
 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
 * @version    Release: 1.9.4
 * @link       http://pear.php.net/package/PEAR
 * @since      Class available since Release 0.1
 */
class PEAR_Command
{
    // {{{ factory()

    /**
     * Get the right object for executing a command.
     *
     * @param string $command The name of the command
     * @param object $config  Instance of PEAR_Config object
     *
     * @return object the command object or a PEAR error
     *
     * @access public
     * @static
     */
    function &factory($command, &$config)
    {
        if (empty($GLOBALS['_PEAR_Command_commandlist'])) {
            PEAR_Command::registerCommands();
        }
        if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) {
            $command = $GLOBALS['_PEAR_Command_shortcuts'][$command];
        }
        if (!isset($GLOBALS['_PEAR_Command_commandlist'][$command])) {
            $a = PEAR::raiseError("unknown command `$command'");
            return $a;
        }
        $class = $GLOBALS['_PEAR_Command_commandlist'][$command];
        if (!class_exists($class)) {
            require_once $GLOBALS['_PEAR_Command_objects'][$class];
        }
        if (!class_exists($class)) {
            $a = PEAR::raiseError("unknown command `$command'");
            return $a;
        }
        $ui =& PEAR_Command::getFrontendObject();
        $obj = &new $class($ui, $config);
        return $obj;
    }

    // }}}
    // {{{ & getObject()
    function &getObject($command)
    {
        $class = $GLOBALS['_PEAR_Command_commandlist'][$command];
        if (!class_exists($class)) {
            require_once $GLOBALS['_PEAR_Command_objects'][$class];
        }
        if (!class_exists($class)) {
            return PEAR::raiseError("unknown command `$command'");
        }
        $ui =& PEAR_Command::getFrontendObject();
        $config = &PEAR_Config::singleton();
        $obj = &new $class($ui, $config);
        return $obj;
    }

    // }}}
    // {{{ & getFrontendObject()

    /**
     * Get instance of frontend object.
     *
     * @return object|PEAR_Error
     * @static
     */
    function &getFrontendObject()
    {
        $a = &PEAR_Frontend::singleton();
        return $a;
    }

    // }}}
    // {{{ & setFrontendClass()

    /**
     * Load current frontend class.
     *
     * @param string $uiclass Name of class implementing the frontend
     *
     * @return object the frontend object, or a PEAR error
     * @static
     */
    function &setFrontendClass($uiclass)
    {
        $a = &PEAR_Frontend::setFrontendClass($uiclass);
        return $a;
    }

    // }}}
    // {{{ setFrontendType()

    /**
     * Set current frontend.
     *
     * @param string $uitype Name of the frontend type (for example "CLI")
     *
     * @return object the frontend object, or a PEAR error
     * @static
     */
    function setFrontendType($uitype)
    {
        $uiclass = 'PEAR_Frontend_' . $uitype;
        return PEAR_Command::setFrontendClass($uiclass);
    }

    // }}}
    // {{{ registerCommands()

    /**
     * Scan through the Command directory looking for classes
     * and see what commands they implement.
     *
     * @param bool   (optional) if FALSE (default), the new list of
     *               commands should replace the current one.  If TRUE,
     *               new entries will be merged with old.
     *
     * @param string (optional) where (what directory) to look for
     *               classes, defaults to the Command subdirectory of
     *               the directory from where this file (__FILE__) is
     *               included.
     *
     * @return bool TRUE on success, a PEAR error on failure
     *
     * @access public
     * @static
     */
    function registerCommands($merge = false, $dir = null)
    {
        $parser = new PEAR_XMLParser;
        if ($dir === null) {
            $dir = dirname(__FILE__) . '/Command';
        }
        if (!is_dir($dir)) {
            return PEAR::raiseError("registerCommands: opendir($dir) '$dir' does not exist or is not a directory");
        }
        $dp = @opendir($dir);
        if (empty($dp)) {
            return PEAR::raiseError("registerCommands: opendir($dir) failed");
        }
        if (!$merge) {
            $GLOBALS['_PEAR_Command_commandlist'] = array();
        }

        while ($file = readdir($dp)) {
            if ($file{0} == '.' || substr($file, -4) != '.xml') {
                continue;
            }

            $f = substr($file, 0, -4);
            $class = "PEAR_Command_" . $f;
            // List of commands
            if (empty($GLOBALS['_PEAR_Command_objects'][$class])) {
                $GLOBALS['_PEAR_Command_objects'][$class] = "$dir/" . $f . '.php';
            }

            $parser->parse(file_get_contents("$dir/$file"));
            $implements = $parser->getData();
            foreach ($implements as $command => $desc) {
                if ($command == 'attribs') {
                    continue;
                }

                if (isset($GLOBALS['_PEAR_Command_commandlist'][$command])) {
                    return PEAR::raiseError('Command "' . $command . '" already registered in ' .
                        'class "' . $GLOBALS['_PEAR_Command_commandlist'][$command] . '"');
                }

                $GLOBALS['_PEAR_Command_commandlist'][$command] = $class;
                $GLOBALS['_PEAR_Command_commanddesc'][$command] = $desc['summary'];
                if (isset($desc['shortcut'])) {
                    $shortcut = $desc['shortcut'];
                    if (isset($GLOBALS['_PEAR_Command_shortcuts'][$shortcut])) {
                        return PEAR::raiseError('Command shortcut "' . $shortcut . '" already ' .
                            'registered to command "' . $command . '" in class "' .
                            $GLOBALS['_PEAR_Command_commandlist'][$command] . '"');
                    }
                    $GLOBALS['_PEAR_Command_shortcuts'][$shortcut] = $command;
                }

                if (isset($desc['options']) && $desc['options']) {
                    foreach ($desc['options'] as $oname => $option) {
                        if (isset($option['shortopt']) && strlen($option['shortopt']) > 1) {
                            return PEAR::raiseError('Option "' . $oname . '" short option "' .
                                $option['shortopt'] . '" must be ' .
                                'only 1 character in Command "' . $command . '" in class "' .
                                $class . '"');
                        }
                    }
                }
            }
        }

        ksort($GLOBALS['_PEAR_Command_shortcuts']);
        ksort($GLOBALS['_PEAR_Command_commandlist']);
        @closedir($dp);
        return true;
    }

    // }}}
    // {{{ getCommands()

    /**
     * Get the list of currently supported commands, and what
     * classes implement them.
     *
     * @return array command => implementing class
     *
     * @access public
     * @static
     */
    function getCommands()
    {
        if (empty($GLOBALS['_PEAR_Command_commandlist'])) {
            PEAR_Command::registerCommands();
        }
        return $GLOBALS['_PEAR_Command_commandlist'];
    }

    // }}}
    // {{{ getShortcuts()

    /**
     * Get the list of command shortcuts.
     *
     * @return array shortcut => command
     *
     * @access public
     * @static
     */
    function getShortcuts()
    {
        if (empty($GLOBALS['_PEAR_Command_shortcuts'])) {
            PEAR_Command::registerCommands();
        }
        return $GLOBALS['_PEAR_Command_shortcuts'];
    }

    // }}}
    // {{{ getGetoptArgs()

    /**
     * Compiles arguments for getopt.
     *
     * @param string $command     command to get optstring for
     * @param string $short_args  (reference) short getopt format
     * @param array  $long_args   (reference) long getopt format
     *
     * @return void
     *
     * @access public
     * @static
     */
    function getGetoptArgs($command, &$short_args, &$long_args)
    {
        if (empty($GLOBALS['_PEAR_Command_commandlist'])) {
            PEAR_Command::registerCommands();
        }
        if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) {
            $command = $GLOBALS['_PEAR_Command_shortcuts'][$command];
        }
        if (!isset($GLOBALS['_PEAR_Command_commandlist'][$command])) {
            return null;
        }
        $obj = &PEAR_Command::getObject($command);
        return $obj->getGetoptArgs($command, $short_args, $long_args);
    }

    // }}}
    // {{{ getDescription()

    /**
     * Get description for a command.
     *
     * @param  string $command Name of the command
     *
     * @return string command description
     *
     * @access public
     * @static
     */
    function getDescription($command)
    {
        if (!isset($GLOBALS['_PEAR_Command_commanddesc'][$command])) {
            return null;
        }
        return $GLOBALS['_PEAR_Command_commanddesc'][$command];
    }

    // }}}
    // {{{ getHelp()

    /**
     * Get help for command.
     *
     * @param string $command Name of the command to return help for
     *
     * @access public
     * @static
     */
    function getHelp($command)
    {
        $cmds = PEAR_Command::getCommands();
        if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) {
            $command = $GLOBALS['_PEAR_Command_shortcuts'][$command];
        }
        if (isset($cmds[$command])) {
            $obj = &PEAR_Command::getObject($command);
            return $obj->getHelp($command);
        }
        return false;
    }
    // }}}
}


<?php

declare(strict_types=1);

namespace Psi\Bridge\ObjectAgent\Doctrine\Collections;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Criteria;
use Psi\Component\ObjectAgent\AgentInterface;
use Psi\Component\ObjectAgent\Capabilities;
use Psi\Component\ObjectAgent\Exception\BadMethodCallException;
use Psi\Component\ObjectAgent\Exception\ObjectNotFoundException;
use Psi\Component\ObjectAgent\Query\Comparison;
use Psi\Component\ObjectAgent\Query\Query;

class CollectionsAgent implements AgentInterface
{
    private $store;

    public function __construct(Store $store)
    {
        $this->store = $store;
    }

    /**
     * {@inheritdoc}
     */
    public function supports(string $classFqn): bool
    {
        return $this->store->hasCollection($classFqn);
    }

    /**
     * {@inheritdoc}
     */
    public function getCapabilities(): Capabilities
    {
        return Capabilities::create([
            'can_query_join' => false,
            'can_set_parent' => false,
            'can_query_count' => true,
            'supported_comparators' => [
                Comparison::EQUALS,
                Comparison::NOT_EQUALS,
                Comparison::LESS_THAN,
                Comparison::LESS_THAN_EQUAL,
                Comparison::GREATER_THAN,
                Comparison::GREATER_THAN_EQUAL,
                Comparison::IN,
                Comparison::NOT_IN,
                Comparison::CONTAINS,
                Comparison::NULL,
            ],
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function find($identifier, string $classFqn = null)
    {
        if (null === $classFqn) {
            throw BadMethodCallException::classArgumentIsMandatory(__CLASS__);
        }

        $object = $this->store->find($classFqn, $identifier);

        if (null === $object) {
            throw ObjectNotFoundException::forClassAndIdentifier($classFqn, $identifier);
        }

        return $object;
    }

    /**
     * {@inheritdoc}
     */
    public function findMany(array $identifiers, string $classFqn = null)
    {
        $collection = [];
        foreach ($identifiers as $identifier) {
            $collection[] = $this->find($identifier, $classFqn);
        }

        return new ArrayCollection($collection);
    }

    /**
     * {@inheritdoc}
     */
    public function persist($object)
    {
        // do nothing ...
    }

    /**
     * {@inheritdoc}
     */
    public function flush()
    {
        // do nothing ...
    }

    /**
     * {@inheritdoc}
     */
    public function remove($object)
    {
        $this->store->remove($object);
    }

    /**
     * {@inheritdoc}
     */
    public function query(Query $query): \Traversable
    {
        return $this->doQuery(
            $query,
            $query->getFirstResult(),
            $query->getMaxResults()
        );
    }

    /**
     * {@inheritdoc}
     */
    public function queryCount(Query $query): int
    {
        return count($this->doQuery($query, 0));
    }

    /**
     * {@inheritdoc}
     */
    public function getIdentifier($object)
    {
        foreach ($this->store->getCollection(get_class($object)) as $identifier => $element) {
            if ($element === $object) {
                return $identifier;
            }
        }

        throw new \RuntimeException(sprintf(
            'Could not find identifier for object of class "%s"',
            get_class($object)
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function setParent($object, $parent)
    {
        throw BadMethodCallException::setParentNotSupported(__CLASS__);
    }

    /**
     * {@inheritdoc}
     */
    public function getCanonicalClassFqn(string $classFqn): string
    {
        return $classFqn;
    }

    private function doQuery(Query $query, int $firstResult = null, int $maxResults = null)
    {
        $collection = $this->store->getCollection($query->getClassFqn());

        $doctrineExpression = null;
        if ($query->hasExpression()) {
            $expressionBuilder = Criteria::expr();
            $visitor = new CollectionsVisitor($expressionBuilder);
            $doctrineExpression = $visitor->dispatch($query->getExpression());
        }

        $criteria = new Criteria(
            $doctrineExpression,
            $query->getOrderings(),
            $firstResult,
            $maxResults
        );

        return $collection->matching($criteria);
    }
}


<?php
/**
 * PEAR_Frontend, the singleton-based frontend for user input/output
 *
 * PHP versions 4 and 5
 *
 * @category   pear
 * @package    PEAR
 * @author     Greg Beaver <cellog@php.net>
 * @copyright  1997-2009 The Authors
 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
 * @version    CVS: $Id: Frontend.php 313023 2011-07-06 19:17:11Z dufuz $
 * @link       http://pear.php.net/package/PEAR
 * @since      File available since Release 1.4.0a1
 */

/**
 * Include error handling
 */
//require_once 'PEAR.php';

/**
 * Which user interface class is being used.
 * @var string class name
 */
$GLOBALS['_PEAR_FRONTEND_CLASS'] = 'PEAR_Frontend_CLI';

/**
 * Instance of $_PEAR_Command_uiclass.
 * @var object
 */
$GLOBALS['_PEAR_FRONTEND_SINGLETON'] = null;

/**
 * Singleton-based frontend for PEAR user input/output
 *
 * @category   pear
 * @package    PEAR
 * @author     Greg Beaver <cellog@php.net>
 * @copyright  1997-2009 The Authors
 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
 * @version    Release: 1.9.4
 * @link       http://pear.php.net/package/PEAR
 * @since      Class available since Release 1.4.0a1
 */
class PEAR_Frontend extends PEAR
{
    /**
     * Retrieve the frontend object
     * @return PEAR_Frontend_CLI|PEAR_Frontend_Web|PEAR_Frontend_Gtk
     * @static
     */
    function &singleton($type = null)
    {
        if ($type === null) {
            if (!isset($GLOBALS['_PEAR_FRONTEND_SINGLETON'])) {
                $a = false;
                return $a;
            }
            return $GLOBALS['_PEAR_FRONTEND_SINGLETON'];
        }

        $a = PEAR_Frontend::setFrontendClass($type);
        return $a;
    }

    /**
     * Set the frontend class that will be used by calls to {@link singleton()}
     *
     * Frontends are expected to conform to the PEAR naming standard of
     * _ => DIRECTORY_SEPARATOR (PEAR_Frontend_CLI is in PEAR/Frontend/CLI.php)
     * @param string $uiclass full class name
     * @return PEAR_Frontend
     * @static
     */
    function &setFrontendClass($uiclass)
    {
        if (is_object($GLOBALS['_PEAR_FRONTEND_SINGLETON']) &&
              is_a($GLOBALS['_PEAR_FRONTEND_SINGLETON'], $uiclass)) {
            return $GLOBALS['_PEAR_FRONTEND_SINGLETON'];
        }

        if (!class_exists($uiclass)) {
            $file = str_replace('_', '/', $uiclass) . '.php';
            if (PEAR_Frontend::isIncludeable($file)) {
                include_once $file;
            }
        }

        if (class_exists($uiclass)) {
            $obj = &new $uiclass;
            // quick test to see if this class implements a few of the most
            // important frontend methods
            if (is_a($obj, 'PEAR_Frontend')) {
                $GLOBALS['_PEAR_FRONTEND_SINGLETON'] = &$obj;
                $GLOBALS['_PEAR_FRONTEND_CLASS'] = $uiclass;
                return $obj;
            }

            $err = PEAR::raiseError("not a frontend class: $uiclass");
            return $err;
        }

        $err = PEAR::raiseError("no such class: $uiclass");
        return $err;
    }

    /**
     * Set the frontend class that will be used by calls to {@link singleton()}
     *
     * Frontends are expected to be a descendant of PEAR_Frontend
     * @param PEAR_Frontend
     * @return PEAR_Frontend
     * @static
     */
    function &setFrontendObject($uiobject)
    {
        if (is_object($GLOBALS['_PEAR_FRONTEND_SINGLETON']) &&
              is_a($GLOBALS['_PEAR_FRONTEND_SINGLETON'], get_class($uiobject))) {
            return $GLOBALS['_PEAR_FRONTEND_SINGLETON'];
        }

        if (!is_a($uiobject, 'PEAR_Frontend')) {
            $err = PEAR::raiseError('not a valid frontend class: (' .
                get_class($uiobject) . ')');
            return $err;
        }

        $GLOBALS['_PEAR_FRONTEND_SINGLETON'] = &$uiobject;
        $GLOBALS['_PEAR_FRONTEND_CLASS'] = get_class($uiobject);
        return $uiobject;
    }

    /**
     * @param string $path relative or absolute include path
     * @return boolean
     * @static
     */
    function isIncludeable($path)
    {
        if (file_exists($path) && is_readable($path)) {
            return true;
        }

        $fp = @fopen($path, 'r', true);
        if ($fp) {
            fclose($fp);
            return true;
        }

        return false;
    }

    /**
     * @param PEAR_Config
     */
    function setConfig(&$config)
    {
    }

    /**
     * This can be overridden to allow session-based temporary file management
     *
     * By default, all files are deleted at the end of a session.  The web installer
     * needs to be able to sustain a list over many sessions in order to support
     * user interaction with install scripts
     */
    function addTempFile($file)
    {
        $GLOBALS['_PEAR_Common_tempfiles'][] = $file;
    }

    /**
     * Log an action
     *
     * @param string $msg the message to log
     * @param boolean $append_crlf
     * @return boolean true
     * @abstract
     */
    function log($msg, $append_crlf = true)
    {
    }

    /**
     * Run a post-installation script
     *
     * @param array $scripts array of post-install scripts
     * @abstract
     */
    function runPostinstallScripts(&$scripts)
    {
    }

    /**
     * Display human-friendly output formatted depending on the
     * $command parameter.
     *
     * This should be able to handle basic output data with no command
     * @param mixed  $data    data structure containing the information to display
     * @param string $command command from which this method was called
     * @abstract
     */
    function outputData($data, $command = '_default')
    {
    }

    /**
     * Display a modal form dialog and return the given input
     *
     * A frontend that requires multiple requests to retrieve and process
     * data must take these needs into account, and implement the request
     * handling code.
     * @param string $command  command from which this method was called
     * @param array  $prompts  associative array. keys are the input field names
     *                         and values are the description
     * @param array  $types    array of input field types (text, password,
     *                         etc.) keys have to be the same like in $prompts
     * @param array  $defaults array of default values. again keys have
     *                         to be the same like in $prompts.  Do not depend
     *                         on a default value being set.
     * @return array input sent by the user
     * @abstract
     */
    function userDialog($command, $prompts, $types = array(), $defaults = array())
    {
    }
}


<?php

namespace gries\NumberSystem;

use gries\NumberSystem\Exception\NumberParseException;

/**
 * Class ExpressionConverter
 *
 * Use this class to convert expression from one NumberSystem to another.
 * Example:
 *  "2 + 3" => "10 + 11" binary to decimal
 *
 * @package gries\NumberSystem
 */
class ExpressionConverter
{

    /**
     * Convert expression from one NumberSystem to another
     *
     * @param Expression   $expression
     * @param NumberSystem $targetSystem
     *
     * @return Expression
     */
    public function convert(Expression $expression, NumberSystem $targetSystem)
    {
        $parsingResult   = $expression->value();
        $expressionParts = $this->getExpressionParts($expression);

        foreach ($expressionParts as $part) {
            $parsedPart = $this->parseExpressionPart($part, $expression->getNumberSystem(), $targetSystem);

            if ($parsedPart !== $part) {
                $parsingResult = preg_replace('/'.$part.'/', $parsedPart, $parsingResult, 1);
            }
        }

        return new Expression($parsingResult, $targetSystem);
    }

    /**
     * Parse the part of an expression.
     *
     * @param $part
     *
     * @return Number
     */
    protected function parseExpressionPart($part, NumberSystem $sourceSystem, NumberSystem $targetSystem)
    {
        try {
            // if it is a valid number of the source-system convert it
            $sourceNumber = new Number($part, $sourceSystem);

            return $sourceNumber->convert($targetSystem)->value();
        } catch (NumberParseException $e) {
            return $part;
        }
    }

    /**
     * @param Expression $expression
     *
     * @return array
     */
    public function getExpressionParts(Expression $expression)
    {
        $cleanedExpression = preg_replace('/[()*\-+\/]/', ' ', $expression->value());
        $expressionParts   = explode(' ', $cleanedExpression);

        return$expressionParts;
    }
}


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

/**
 * @category   Zend
 * @package    Zend_Config
 * @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_Config_Ini extends Zend_Config
{
    /**
     * String that separates nesting levels of configuration data identifiers
     *
     * @var string
     */
    protected $_nestSeparator = '.';

    /**
     * String that separates the parent section name
     *
     * @var string
     */
    protected $_sectionSeparator = ':';

    /**
     * Whether to skip extends or not
     *
     * @var boolean
     */
    protected $_skipExtends = false;

    /**
     * Loads the section $section from the config file $filename for
     * access facilitated by nested object properties.
     *
     * If the section name contains a ":" then the section name to the right
     * is loaded and included into the properties. Note that the keys in
     * this $section will override any keys of the same
     * name in the sections that have been included via ":".
     *
     * If the $section is null, then all sections in the ini file are loaded.
     *
     * If any key includes a ".", then this will act as a separator to
     * create a sub-property.
     *
     * example ini file:
     *      [all]
     *      db.connection = database
     *      hostname = live
     *
     *      [staging : all]
     *      hostname = staging
     *
     * after calling $data = new Zend_Config_Ini($file, 'staging'); then
     *      $data->hostname === "staging"
     *      $data->db->connection === "database"
     *
     * The $options parameter may be provided as either a boolean or an array.
     * If provided as a boolean, this sets the $allowModifications option of
     * Zend_Config. If provided as an array, there are three configuration
     * directives that may be set. For example:
     *
     * $options = array(
     *     'allowModifications' => false,
     *     'nestSeparator'      => ':',
     *     'skipExtends'        => false,
     *      );
     *
     * @param  string        $filename
     * @param  mixed         $section
     * @param  boolean|array $options
     * @throws Zend_Config_Exception
     * @return void
     */
    public function __construct($filename, $section = null, $options = false)
    {
        if (empty($filename)) {
            /**
             * @see Zend_Config_Exception
             */

            throw new Zend_Config_Exception('Filename is not set');
        }

        $allowModifications = false;
        if (is_bool($options)) {
            $allowModifications = $options;
        } elseif (is_array($options)) {
            if (isset($options['allowModifications'])) {
                $allowModifications = (bool) $options['allowModifications'];
            }
            if (isset($options['nestSeparator'])) {
                $this->_nestSeparator = (string) $options['nestSeparator'];
            }
            if (isset($options['skipExtends'])) {
                $this->_skipExtends = (bool) $options['skipExtends'];
            }
        }

        $iniArray = $this->_loadIniFile($filename);

        if (null === $section) {
            // Load entire file
            $dataArray = array();
            foreach ($iniArray as $sectionName => $sectionData) {
                if(!is_array($sectionData)) {
                    $dataArray = $this->_arrayMergeRecursive($dataArray, $this->_processKey(array(), $sectionName, $sectionData));
                } else {
                    $dataArray[$sectionName] = $this->_processSection($iniArray, $sectionName);
                }
            }
            parent::__construct($dataArray, $allowModifications);
        } else {
            // Load one or more sections
            if (!is_array($section)) {
                $section = array($section);
            }
            $dataArray = array();
            foreach ($section as $sectionName) {
                if (!isset($iniArray[$sectionName])) {
                    /**
                     * @see Zend_Config_Exception
                     */

                    throw new Zend_Config_Exception("Section '$sectionName' cannot be found in $filename");
                }
                $dataArray = $this->_arrayMergeRecursive($this->_processSection($iniArray, $sectionName), $dataArray);

            }
            parent::__construct($dataArray, $allowModifications);
        }

        $this->_loadedSection = $section;
    }

    /**
     * Load the INI file from disk using parse_ini_file(). Use a private error
     * handler to convert any loading errors into a Zend_Config_Exception
     *
     * @param string $filename
     * @throws Zend_Config_Exception
     * @return array
     */
    protected function _parseIniFile($filename)
    {
        set_error_handler(array($this, '_loadFileErrorHandler'));
        $iniArray = parse_ini_file($filename, true); // Warnings and errors are suppressed
        restore_error_handler();

        // Check if there was a error while loading file
        if ($this->_loadFileErrorStr !== null) {
            /**
             * @see Zend_Config_Exception
             */

            throw new Zend_Config_Exception($this->_loadFileErrorStr);
        }

        return $iniArray;
    }

    /**
     * Load the ini file and preprocess the section separator (':' in the
     * section name (that is used for section extension) so that the resultant
     * array has the correct section names and the extension information is
     * stored in a sub-key called ';extends'. We use ';extends' as this can
     * never be a valid key name in an INI file that has been loaded using
     * parse_ini_file().
     *
     * @param string $filename
     * @throws Zend_Config_Exception
     * @return array
     */
    protected function _loadIniFile($filename)
    {
        $loaded = $this->_parseIniFile($filename);
        $iniArray = array();
        foreach ($loaded as $key => $data)
        {
            $pieces = explode($this->_sectionSeparator, $key);
            $thisSection = trim($pieces[0]);
            switch (count($pieces)) {
                case 1:
                    $iniArray[$thisSection] = $data;
                    break;

                case 2:
                    $extendedSection = trim($pieces[1]);
                    $iniArray[$thisSection] = array_merge(array(';extends'=>$extendedSection), $data);
                    break;

                default:
                    /**
                     * @see Zend_Config_Exception
                     */

                    throw new Zend_Config_Exception("Section '$thisSection' may not extend multiple sections in $filename");
            }
        }

        return $iniArray;
    }

    /**
     * Process each element in the section and handle the ";extends" inheritance
     * key. Passes control to _processKey() to handle the nest separator
     * sub-property syntax that may be used within the key name.
     *
     * @param  array  $iniArray
     * @param  string $section
     * @param  array  $config
     * @throws Zend_Config_Exception
     * @return array
     */
    protected function _processSection($iniArray, $section, $config = array())
    {
        $thisSection = $iniArray[$section];

        foreach ($thisSection as $key => $value) {
            if (strtolower($key) == ';extends') {
                if (isset($iniArray[$value])) {
                    $this->_assertValidExtend($section, $value);

                    if (!$this->_skipExtends) {
                        $config = $this->_processSection($iniArray, $value, $config);
                    }
                } else {
                    /**
                     * @see Zend_Config_Exception
                     */

                    throw new Zend_Config_Exception("Parent section '$section' cannot be found");
                }
            } else {
                $config = $this->_processKey($config, $key, $value);
            }
        }
        return $config;
    }

    /**
     * Assign the key's value to the property list. Handles the
     * nest separator for sub-properties.
     *
     * @param  array  $config
     * @param  string $key
     * @param  string $value
     * @throws Zend_Config_Exception
     * @return array
     */
    protected function _processKey($config, $key, $value)
    {
        if (strpos($key, $this->_nestSeparator) !== false) {
            $pieces = explode($this->_nestSeparator, $key, 2);
            if (strlen($pieces[0]) && strlen($pieces[1])) {
                if (!isset($config[$pieces[0]])) {
                    if ($pieces[0] === '0' && !empty($config)) {
                        // convert the current values in $config into an array
                        $config = array($pieces[0] => $config);
                    } else {
                        $config[$pieces[0]] = array();
                    }
                } elseif (!is_array($config[$pieces[0]])) {
                    /**
                     * @see Zend_Config_Exception
                     */

                    throw new Zend_Config_Exception("Cannot create sub-key for '{$pieces[0]}' as key already exists");
                }
                $config[$pieces[0]] = $this->_processKey($config[$pieces[0]], $pieces[1], $value);
            } else {
                /**
                 * @see Zend_Config_Exception
                 */

                throw new Zend_Config_Exception("Invalid key '$key'");
            }
        } else {
            $config[$key] = $value;
        }
        return $config;
    }
}


<?php

namespace Gosyl\CommonBundle\Event;

use Doctrine\ORM\EntityManager;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\HttpKernel;
use Gosyl\CommonBundle\Entity\ParamUsers;

class ActivityListener {

	/**
	 *
	 * @var TokenStorage
	 */
	protected $_oTokenStorage;

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

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

	public function __construct(EntityManager $oDoctrine, Container $oContainer, TokenStorage $oToken) {
		$this->_oEntityManager = $oDoctrine;
		$this->_oContainer = $oContainer;
		$this->_oTokenStorage = $oToken;
	}

	/**
	 * Update the user "lastActivity" on each request
	 *
	 * @param FilterControllerEvent $event
	 */
	public function onCoreController(FilterControllerEvent $event) {
		// ici nous vérifions que la requête est une "MASTER_REQUEST" pour que les sous-requête soit ingoré (par exemple si vous faites un render() dans votre template)
		if($event->getRequestType() !== HttpKernel::MASTER_REQUEST) {
			return;
		}

		// Nous vérifions qu'un token d'autentification est bien présent avant d'essayer manipuler l'utilisateur courant.
		if($this->_oTokenStorage->getToken()) {
			/**
			 * @var ParamUsers $user
			 */
			$user = $this->_oTokenStorage->getToken()->getUser();

			// Nous vérifions que l'utilisateur est bien du bon type pour ne pas appeler getLastActivity() sur un objet autre objet User
			if($user instanceof ParamUsers && !($user->isActiveNow())) {
				$user->setLastActivityAt(new \DateTime('now'));
				$this->_oEntityManager->flush($user);
			}
		}
	}
}


<?php

namespace Ekyna\Bundle\CoreBundle\Form\Extension;

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\Exception\MissingOptionsException;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class ChoiceTypeParentExtension
 * @package Ekyna\Bundle\CoreBundle\Form\Extension
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
class ChoiceTypeParentExtension extends AbstractTypeExtension
{
    const BOTH_OR_NONE = 'You may define both "parent_choice_field" and "parent_choice_route", or none of them.';

    /**
     * {@inheritDoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver
            ->setDefaults([
                'parent_choice_field' => null,
                'parent_choice_route' => null,
            ])
            ->setAllowedTypes('parent_choice_field',  ['string', 'null'])
            ->setAllowedTypes('parent_choice_route',  ['string', 'null'])
        ;
    }

    /**
     * {@inheritDoc}
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $fieldDefined = 0 < strlen($options['parent_choice_field']);
        $routeDefined = 0 < strlen($options['parent_choice_route']);

        if (($fieldDefined && !$routeDefined) || (!$fieldDefined && $routeDefined)) {
            throw new MissingOptionsException(self::BOTH_OR_NONE);
        }

        if ($fieldDefined && $routeDefined) {
            $view->vars['attr']['data-parent-choice'] = json_encode([
                'field' => $view->parent->vars['id'].'_'.$options['parent_choice_field'],
                'route' => $options['parent_choice_route'],
            ]);
        }
    }

    /**
     * {@inheritDoc}
     */
    public function getExtendedType()
    {
        return 'choice';
    }
}


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

/**
 * @see Zend_Filter_Interface
 */

/**
 * @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_StringTrim implements Zend_Filter_Interface
{
    /**
     * List of characters provided to the trim() function
     *
     * If this is null, then trim() is called with no specific character list,
     * and its default behavior will be invoked, trimming whitespace.
     *
     * @var string|null
     */
    protected $_charList;

    /**
     * Sets filter options
     *
     * @param  string|array|Zend_Config $options
     * @return void
     */
    public function __construct($options = null)
    {
        if ($options instanceof Zend_Config) {
            $options = $options->toArray();
        } else if (!is_array($options)) {
            $options          = func_get_args();
            $temp['charlist'] = array_shift($options);
            $options          = $temp;
        }

        if (array_key_exists('charlist', $options)) {
            $this->setCharList($options['charlist']);
        }
    }

    /**
     * Returns the charList option
     *
     * @return string|null
     */
    public function getCharList()
    {
        return $this->_charList;
    }

    /**
     * Sets the charList option
     *
     * @param  string|null $charList
     * @return Zend_Filter_StringTrim Provides a fluent interface
     */
    public function setCharList($charList)
    {
        $this->_charList = $charList;
        return $this;
    }

    /**
     * Defined by Zend_Filter_Interface
     *
     * Returns the string $value with characters stripped from the beginning and end
     *
     * @param  string $value
     * @return string
     */
    public function filter($value)
    {
        if (null === $this->_charList) {
            return $this->_unicodeTrim((string) $value);
        } else {
            return $this->_unicodeTrim((string) $value, $this->_charList);
        }
    }

    /**
     * Unicode aware trim method
     * Fixes a PHP problem
     *
     * @param string $value
     * @param string $charlist
     * @return string
     */
    protected function _unicodeTrim($value, $charlist = '\\\\s')
    {
        $chars = preg_replace(
            array( '/[\^\-\]\\\]/S', '/\\\{4}/S', '/\//'),
            array( '\\\\\\0', '\\', '\/' ),
            $charlist
        );

        $pattern = '^[' . $chars . ']*|[' . $chars . ']*$';
        return preg_replace("/$pattern/sSD", '', $value);
    }
}


<?php

namespace Reaction\Db\Pgsql;

use Reaction\Db\Expressions\ArrayExpression;
use Reaction\Db\Expressions\ExpressionBuilderInterface;
use Reaction\Db\Expressions\ExpressionBuilderTrait;
use Reaction\Db\Expressions\ExpressionInterface;
use Reaction\Db\Expressions\JsonExpression;
use Reaction\Db\Query;
use Reaction\Helpers\Json;

/**
 * Class JsonExpressionBuilder builds [[JsonExpression]] for PostgreSQL DBMS.
 */
class JsonExpressionBuilder implements ExpressionBuilderInterface
{
    use ExpressionBuilderTrait;

    /**
     * {@inheritdoc}
     * @param JsonExpression $expression the expression to be built
     */
    public function build($expression, array &$params = [])
    {
        $value = $expression->getValue();

        if ($value instanceof Query) {
            list ($sql, $params) = $this->queryBuilder->build($value, $params);
            return "($sql)" . $this->getTypecast($expression);
        }
        if ($value instanceof ArrayExpression) {
            $placeholder = 'array_to_json(' . $this->queryBuilder->buildExpression($value, $params) . ')';
        } else {
            $placeholder = $this->queryBuilder->bindParam(Json::encode($value), $params);
        }

        return $placeholder . $this->getTypecast($expression);
    }

    /**
     * @param JsonExpression $expression
     * @return string the typecast expression based on [[type]].
     */
    protected function getTypecast(JsonExpression $expression)
    {
        if ($expression->getType() === null) {
            return '';
        }

        return '::' . $expression->getType();
    }
}


<?php namespace Ordercloud\Requests\Handlers;

use Ordercloud\Requests\Exceptions\OrdercloudRequestException;
use Ordercloud\Requests\OrdercloudRequest;
use Ordercloud\Support\CommandBus\CommandHandler;
use Ordercloud\Support\ExceptionGenerators\ExceptionGeneratorService;
use Ordercloud\Support\Http\Client;
use Ordercloud\Support\Http\OrdercloudHttpException;
use Ordercloud\Support\Http\Response;
use Ordercloud\Support\Http\UrlParameteriser;

class OrdercloudRequestHandler implements CommandHandler
{
    /** @var Client */
    private $client;

    /**
     * @var ExceptionGeneratorService
     */
    private $exceptionGenerator;

    public function __construct(Client $client, ExceptionGeneratorService $exceptionGenerator)
    {
        $this->client = $client;
        $this->exceptionGenerator = $exceptionGenerator;
    }

    /**
     * @param OrdercloudRequest $request
     *
     * @return Response
     *
     * @throws OrdercloudRequestException
     */
    public function handle($request)
    {
        try {
            return $this->client->send(
                $request->getUrl(),
                $request->getMethod(),
                $request->getParameters(),
                $request->getHeaders()
            );
        }
        catch (OrdercloudHttpException $e) {
            throw $this->exceptionGenerator->generateException($request, $e);
        }
    }
}


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

/**
 * @see Zend_Filter_Interface
 */

/**
 * @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_StringToUpper implements Zend_Filter_Interface
{
    /**
     * Encoding for the input string
     *
     * @var string
     */
    protected $_encoding = null;

    /**
     * Constructor
     *
     * @param string|array $options OPTIONAL
     */
    public function __construct($options = null)
    {
        if ($options instanceof Zend_Config) {
            $options = $options->toArray();
        } else if (!is_array($options)) {
            $options = func_get_args();
            $temp    = array();
            if (!empty($options)) {
                $temp['encoding'] = array_shift($options);
            }
            $options = $temp;
        }

        if (!array_key_exists('encoding', $options) && function_exists('mb_internal_encoding')) {
            $options['encoding'] = mb_internal_encoding();
        }

        if (array_key_exists('encoding', $options)) {
            $this->setEncoding($options['encoding']);
        }
    }

    /**
     * Returns the set encoding
     *
     * @return string
     */
    public function getEncoding()
    {
        return $this->_encoding;
    }

    /**
     * Set the input encoding for the given string
     *
     * @param  string $encoding
     * @return Zend_Filter_StringToUpper Provides a fluent interface
     * @throws Zend_Filter_Exception
     */
    public function setEncoding($encoding = null)
    {
        if ($encoding !== null) {
            if (!function_exists('mb_strtoupper')) {

                throw new Zend_Filter_Exception('mbstring is required for this feature');
            }

            $encoding = (string) $encoding;
            if (!in_array(strtolower($encoding), array_map('strtolower', mb_list_encodings()))) {

                throw new Zend_Filter_Exception("The given encoding '$encoding' is not supported by mbstring");
            }
        }

        $this->_encoding = $encoding;
        return $this;
    }

    /**
     * Defined by Zend_Filter_Interface
     *
     * Returns the string $value, converting characters to uppercase as necessary
     *
     * @param  string $value
     * @return string
     */
    public function filter($value)
    {
        if ($this->_encoding) {
            return mb_strtoupper((string) $value, $this->_encoding);
        }

        return strtoupper((string) $value);
    }
}


<?php

namespace Dhii\Iterator;

use Dhii\Iterator\Exception\IteratorException;
use Dhii\Util\String\StringableInterface as Stringable;
use Exception as RootException;

/**
 * Common functionality for objects that can create iterator exceptions.
 *
 * @since [*next-version*]
 */
trait CreateIteratorExceptionCapableTrait
{
    /**
     * Creates a new iterator exception instance.
     *
     * @since [*next-version*]
     *
     * @param string|Stringable|null $message  The error message, if any.
     * @param int|null               $code     The error code, if any.
     * @param RootException|null     $previous The previous exception for chaining, if any.
     * @param IteratorInterface      $iterator The iterator instance that erred.
     *
     * @return IteratorException The created exception instance.
     */
    protected function _createIteratorException(
        $message = null,
        $code = null,
        RootException $previous = null,
        IteratorInterface $iterator
    ) {
        return new IteratorException($message, $code, $previous, $iterator);
    }
}


<?php

namespace Reaction\I18n;

use React\Promise\PromiseInterface;
use Reaction;
use Reaction\Base\Component;
use Reaction\Base\ComponentAutoloadInterface;
use Reaction\Base\ComponentInitBlockingInterface;
use Reaction\Exceptions\InvalidConfigException;
use function Reaction\Promise\all;
use function Reaction\Promise\reject;
use function Reaction\Promise\resolve;

/**
 * I18N provides features related with internationalization (I18N) and localization (L10N).
 *
 * I18N is configured as an application component in [[\Reaction\StaticApplicationInterface]] by default.
 * You can access that instance via `Reaction::$app->i18n` || `Reaction::$app->getI18n()`.
 *
 * If you are using DbMessageSource, then add database component as dependency so it will init first,
 * for example:
 *
 * ```
 * ...
 * //Internationalization
 *  'i18n' => [
 *      'class' => 'Reaction\I18n\I18N',
 *      'languages' => ['uk', 'ru'],
 *      'translations' => [
 *          '*' => [
 *              'class' => 'Reaction\I18n\GettextMessageSource',
 *              'basePath' => '@app/Messages',
 *          ],
 *      ],
 *      'dependsOn' => ['db'], //'i18n' component depends on 'db' component
 *  ],
 * ...
 *
 * @property MessageFormatter $messageFormatter The message formatter to be used to format message via ICU
 * message format. Note that the type of this property differs in getter and setter. See
 * [[getMessageFormatter()]] and [[setMessageFormatter()]] for details.
 */
class I18N extends Component implements ComponentAutoloadInterface, ComponentInitBlockingInterface
{
    const DOMAIN_CORE = 'rct';

    /**
     * @var array list of [[MessageSource]] configurations or objects. The array keys are message
     * category patterns, and the array values are the corresponding [[MessageSource]] objects or the configurations
     * for creating the [[MessageSource]] objects.
     *
     * The message category patterns can contain the wildcard `*` at the end to match multiple categories with the same prefix.
     * For example, `app/*` matches both `app/cat1` and `app/cat2`.
     *
     * The `*` category pattern will match all categories that do not match any other category patterns.
     *
     * This property may be modified on the fly by extensions who want to have their own message sources
     * registered under their own namespaces.
     *
     * The category `yii` and `app` are always defined. The former refers to the messages used in the Yii core
     * framework code, while the latter refers to the default message category for custom application code.
     * By default, both of these categories use [[PhpMessageSource]] and the corresponding message files are
     * stored under `@reaction/Messages` and `@app/Messages`, respectively.
     *
     * You may override the configuration of both categories.
     */
    public $translations;
    /**
     * @var string[] List of used languages to preload messages on init
     */
    public $languages = [];
    /**
     * @var array List of language prefixes used for UrlManager.
     * Key is url prefix without start or end slash and the value is language, that will be used.
     * For example:
     * ```
     *  [ 'en' => 'en-US', 'ua' => 'uk' ]
     */
    public $languagePrefixes = ['' => 'uk'];
    /**
     * @var bool Detect application language by URL prefix or not
     */
    public $detectLanguageByUrl = true;
    /**
     * @var bool
     */
    protected $_initialized = false;

    /**
     * Initializes the component by configuring the default message categories.
     */
    public function init()
    {
        parent::init();
        if (empty($this->languages)) {
            $this->languages = [Reaction::$app->language];
        }
        $this->initUrlLanguagePrefixes();
        if (!isset($this->translations['rct']) && !isset($this->translations['rct*'])) {
            $this->translations['rct'] = [
                'class' => 'Reaction\I18n\PhpMessageSource',
                'sourceLanguage' => 'en-US',
                'basePath' => '@reaction/Messages',
            ];
        }

        if (!isset($this->translations['app']) && !isset($this->translations['app*']) && !isset($this->translations['*'])) {
            $this->translations['app'] = [
                'class' => 'Reaction\I18n\PhpMessageSource',
                'sourceLanguage' => Reaction::$app->sourceLanguage,
                'basePath' => '@app/Messages',
            ];
        }
    }

    /**
     * Fill url language prefixes
     */
    protected function initUrlLanguagePrefixes()
    {
        $prefixes = $this->languagePrefixes;
        $defaultLanguage = isset($prefixes['']) ? $prefixes[''] : reset($this->languages);
        $prefixes[''] = $defaultLanguage;
        foreach ($this->languages as $language) {
            if (in_array($language, $prefixes)) {
                continue;
            }
            $prefix = Reaction\Helpers\Inflector::slug($language);
            $prefixes[$prefix] = $language;
        }
        $this->languagePrefixes = $prefixes;
    }

    /**
     * Translates a message to the specified language.
     *
     * After translation the message will be formatted using [[MessageFormatter]] if it contains
     * ICU message format and `$params` are not empty.
     *
     * @param string $category the message category.
     * @param string $message the message to be translated.
     * @param array $params the parameters that will be used to replace the corresponding placeholders in the message.
     * @param string $language the language code (e.g. `en-US`, `en`).
     * @return string the translated and formatted message.
     */
    public function translate($category, $message, $params, $language)
    {
        $messageSource = $this->getMessageSource($category);
        $translation = $messageSource->translate($category, $message, $language);
        if ($translation === false) {
            return $this->format($message, $params, $messageSource->sourceLanguage);
        }

        return $this->format($translation, $params, $language);
    }

    /**
     * Formats a message using [[MessageFormatter]].
     *
     * @param string $message the message to be formatted.
     * @param array $params the parameters that will be used to replace the corresponding placeholders in the message.
     * @param string $language the language code (e.g. `en-US`, `en`).
     * @return string the formatted message.
     */
    public function format($message, $params, $language)
    {
        $params = (array)$params;
        if ($params === []) {
            return $message;
        }

        if (preg_match('~{\s*[\w.]+\s*,~u', $message)) {
            $formatter = $this->getMessageFormatter();
            $result = $formatter->format($message, $params, $language);
            if ($result === false) {
                $errorMessage = $formatter->getErrorMessage();
                Reaction::warning("Formatting message for language '$language' failed with error: $errorMessage. The message being formatted was: $message.");

                return $message;
            }

            return $result;
        }

        $p = [];
        foreach ($params as $name => $value) {
            $p['{' . $name . '}'] = $value;
        }

        return strtr($message, $p);
    }

    /**
     * @var string|array|MessageFormatter
     */
    private $_messageFormatter;

    /**
     * Returns the message formatter instance.
     * @return MessageFormatter the message formatter to be used to format message via ICU message format.
     */
    public function getMessageFormatter()
    {
        if ($this->_messageFormatter === null) {
            $this->_messageFormatter = new MessageFormatter();
        } elseif (is_array($this->_messageFormatter) || is_string($this->_messageFormatter)) {
            $this->_messageFormatter = Reaction::create($this->_messageFormatter);
        }

        return $this->_messageFormatter;
    }

    /**
     * @param string|array|MessageFormatter $value the message formatter to be used to format message via ICU message format.
     * Can be given as array or string configuration that will be given to [[Yii::createObject]] to create an instance
     * or a [[MessageFormatter]] instance.
     */
    public function setMessageFormatter($value)
    {
        $this->_messageFormatter = $value;
    }

    /**
     * Returns the message source for the given category.
     * @param string $category the category name.
     * @return MessageSource the message source for the given category.
     * @throws InvalidConfigException if there is no message source available for the specified category.
     */
    public function getMessageSource($category)
    {
        if (isset($this->translations[$category])) {
            $source = $this->translations[$category];
            if ($source instanceof MessageSource) {
                return $source;
            }

            return $this->translations[$category] = Reaction::create($source);
        }
        // try wildcard matching
        foreach ($this->translations as $pattern => $source) {
            if (strpos($pattern, '*') > 0 && strpos($category, rtrim($pattern, '*')) === 0) {
                if ($source instanceof MessageSource) {
                    return $source;
                }

                return $this->translations[$category] = $this->translations[$pattern] = Reaction::create($source);
            }
        }

        // match '*' in the last
        if (isset($this->translations['*'])) {
            $source = $this->translations['*'];
            if ($source instanceof MessageSource) {
                return $source;
            }

            return $this->translations[$category] = $this->translations['*'] = Reaction::create($source);
        }

        throw new InvalidConfigException("Unable to locate message source for category '$category'.");
    }

    /**
     * Init callback. Called by parent container/service/component on init and must return a fulfilled Promise
     * @return PromiseInterface
     */
    public function initComponent()
    {
        return resolve(true)
            ->then(function() {
                $promises = [];
                foreach ($this->translations as $category => $config) {
                    $source = $this->getMessageSource($category);
                    $promises[] = $source
                        ->preloadMessages($category, $this->languages)
                        ->otherwise(function($error) {
                            echo gettype($error);
                        });
                }
                if (empty($promises)) {
                    return true;
                }
                return all($promises);
            })->then(function() {
                $initMessage = sprintf("%s initialized", __CLASS__);
                if (!Reaction::isConsoleApp()) {
                    Reaction::info($initMessage);
                }
                return $this->_initialized = true;
            })->otherwise(function($error) {
                if ($error instanceof \Throwable) {
                    Reaction::error($error->getMessage());
                }
                return reject($error);
            });
    }

    /**
     * Check that component was initialized earlier
     * @return bool
     */
    public function isInitialized()
    {
        return $this->_initialized;
    }
}


<?php
/**
 *  Soluble Components (http://belgattitude.github.io/solublecomponents)
 *
 *  @link      http://github.com/belgattitude/solublecomponents for the canonical source repository
 *  @copyright Copyright (c) 2013-2014 Sébastien Vanvelthem
 *  @license   https://github.com/belgattitude/solublecomponents/blob/master/LICENSE.txt MIT License
 */

namespace Soluble\Normalist\Synthetic;

use Zend\Db\Adapter\Adapter;

class Transaction
{
    const STATE_NULL = 'null';
    const STATE_STARTED = 'started';
    const STATE_ROLLBACKED = 'rollbacked';
    const STATE_COMMITTED = 'committed';
    const STATE_ERRORED = 'errored';

    /**
     *
     * @param \Zend\Db\Adapter\Adapter $adapter
     */
    protected $adapter;

    /**
     *
     * @var string state of current transaction
     */
    protected $state;

    /**
     *
     * @param \Zend\Db\Adapter\Adapter $adapter
     */
    public function __construct(Adapter $adapter)
    {
        $this->adapter = $adapter;
        $this->state = self::STATE_NULL;
    }

    /**
     * Start a new transaction
     *
     * @throws Exception\TransactionException
     * @return Transaction
     */
    public function start()
    {
        try {
            if ($this->state == self::STATE_STARTED) {
                throw new Exception\TransactionException(__METHOD__ . " Starting transaction on an already started one is not permitted.");
            }
            $this->adapter->getDriver()->getConnection()->beginTransaction();
            $this->state = self::STATE_STARTED;
        } catch (\Exception $e) {
            throw new Exception\TransactionException(__METHOD__ . ". Cannot start transaction '{$e->getMessage()}'.");
        }
        return $this;
    }

    /**
     * Commit changes
     *
     * @throws Exception\TransactionException
     * @return Transaction
     */
    public function commit()
    {
        try {
            $this->adapter->getDriver()->getConnection()->commit();
            $this->state = self::STATE_COMMITTED;
        } catch (\Exception $e) {
            $this->state = self::STATE_ERRORED;
            throw new Exception\TransactionException(__CLASS__ . '::' . __METHOD__ . ". cannot commit transaction '{$e->getMessage()}'.");
        }

        return $this;
    }

    /**
     * Rollback transaction
     *
     * @throws Exception\TransactionException
     * @return Transaction
     */
    public function rollback()
    {
        try {
            $this->adapter->getDriver()->getConnection()->rollback();
            $this->state = self::STATE_ROLLBACKED;
        } catch (\Exception $e) {
            $this->state = self::STATE_ERRORED;
            throw new Exception\TransactionException(__CLASS__ . '::' . __METHOD__ . ". cannot rollback transaction '{$e->getMessage()}'.");
        }

        return $this;
    }
}


<?php
namespace wiggum\services\errorHandler;

use \wiggum\commons\Handler;
use \wiggum\http\Request;
use \wiggum\http\Response;
use \wiggum\commons\template\Template;

class ErrorHandler extends Handler {

	protected $app;
	protected $verboseMode;
	protected $templates;

	/**
	 */
	public function __construct(\wiggum\foundation\Application $app) {
		$this->app = $app;
		$this->verboseMode = $app->config->get('app.environment', 'development') == 'development' ? true : false;
		$this->templates = $app->config->get('services.errorHandler', []);
	}

	/**
	 * Invoke error handler
	 *
	 * @param Request $request
	 * @param Response $response
	 * @param \Throwable $error
	 *
	 * @return Response
	 * @throws UnexpectedValueException
	 */
	public function __invoke(Request $request, Response $response, \Throwable $error) {
		$output = '';
		$contentType = $this->determineContentType($request);
		switch ($contentType) {
			case 'application/json' :
				$output = $this->renderErrorMessage($error, 'json');
				break;

			case 'text/xml' :
			case 'application/xml' :
				$output = $this->renderErrorMessage($error, 'xml');
				break;

			case 'text/html' :
				$output = $this->renderErrorMessage($error, 'html');
				break;
			default :
				throw new UnexpectedValueException('Cannot render unknown content type ' . $contentType);
		}

		$this->writeToErrorLog($error);

		$response->withStatus(500);
		$response->setContentType($contentType);
		$response->setOutput($output);
		return $response;
	}

	/**
	 * Render error
	 *
	 * @param \Throwable $error
	 *
	 * @return string
	 */
	protected function renderErrorMessage(\Throwable $error, $type) {
		if (!isset($this->templates[$type]))
			throw new UnexpectedValueException('Cannot render template type "' . $type . '"');

		$tpl = new Template('', '');
		$tpl->setTemplatePath($this->templates[$type]);

		$tpl->set('app', $this->app);
		$tpl->set('error', $error);
		$tpl->set('verboseMode', $this->verboseMode);

		return $tpl->fetch('');
	}

}
?>


<?php
/**
 * Facade for current module for dependent modules repos.
 * User: Alex Gusev <alex@flancer64.com>
 */
namespace Praxigento\Bonus\GlobalSales\Lib\Repo\Def;

use Praxigento\Bonus\GlobalSales\Lib\Entity\Cfg\Param;
use Praxigento\Bonus\GlobalSales\Lib\Entity\Qualification;
use Praxigento\Bonus\GlobalSales\Lib\Repo\decimal;
use Praxigento\Bonus\GlobalSales\Lib\Repo\IModule;
use Praxigento\BonusBase\Repo\Data\Compress;
use Praxigento\BonusLoyalty\Repo\IModule as BonusLoyaltyRepo;
use Praxigento\Core\App\Repo\Db;
use Praxigento\Pv\Repo\Data\Sale as PvSale;

class Module extends Db implements IModule
{
    /** @var \Praxigento\Core\Api\App\Repo\Transaction\Manager */
    protected $_manTrans;
    /** @var \Praxigento\Core\Api\App\Repo\Generic */
    protected $_repoBasic;
    /** @var \Praxigento\BonusBase\Repo\Dao\Log\Rank */
    protected $_repoBonusLogRank;
    /** @var BonusLoyaltyRepo */
    protected $_repoBonusLoyalty;
    /** @var \Praxigento\Core\Api\Helper\Period */
    protected $_toolPeriod;

    public function __construct(
        \Magento\Framework\App\ResourceConnection $resource,
        \Praxigento\Core\Api\App\Repo\Transaction\Manager $manTrans,
        \Praxigento\Core\Api\App\Repo\Generic $daoBasic,
        BonusLoyaltyRepo $daoBonusLoyalty,
        \Praxigento\BonusBase\Repo\Dao\Log\Rank $daoBonusLogRank,
        \Praxigento\Core\Api\Helper\Period $toolPeriod
    ) {
        parent::__construct($resource);
        $this->_manTrans = $manTrans;
        $this->_repoBasic = $daoBasic;
        $this->_repoBonusLoyalty = $daoBonusLoyalty;
        $this->_repoBonusLogRank = $daoBonusLogRank;
        $this->_toolPeriod = $toolPeriod;
    }

    /**
     * SELECT
     * pbbc.customer_id,
     * pbbc.parent_id,
     * pbgq.gv,
     * pbgq.rank_id
     * FROM prxgt_bon_globsal_qual pbgq
     * LEFT JOIN prxgt_bon_base_compress pbbc
     * ON pbbc.id = pbgq.compress_id
     * WHERE pbbc.calc_id = 1
     *
     * @param $calcId
     */
    public function getCompressedTreeWithQualifications($calcId)
    {
        /* aliases and tables */
        $asQual = 'pbgq';
        $asCompress = 'pbbc';
        $tblQual = $this->resource->getTableName(Qualification::ENTITY_NAME);
        $tblCompress = $this->resource->getTableName(Compress::ENTITY_NAME);
        // SELECT FROM prxgt_bon_globsal_qual pbgq
        $query = $this->conn->select();
        $query->from([$asQual => $tblQual], [Qualification::A_GV, Qualification::A_RANK_ID]);
        // LEFT JOIN prxgt_bon_base_compress pbbc ON pbbc.id = pbgq.compress_id
        $on = "$asCompress." . Compress::A_ID . "=$asQual." . Qualification::A_COMPRESS_ID;
        $cols = [
            Compress::A_CUSTOMER_ID,
            Compress::A_PARENT_ID
        ];
        $query->joinLeft([$asCompress => $tblCompress], $on, $cols);
        // where
        $where = $asCompress . '.' . Compress::A_CALC_ID . '=' . (int)$calcId;
        $query->where($where);
        // $sql = (string)$query;
        $result = $this->conn->fetchAll($query);
        return $result;
    }

    public function getConfigParams()
    {
        $result = [];
        $order = Param::A_GV . ' ASC';
        $data = $this->_repoBasic->getEntities(Param::ENTITY_NAME, null, null, $order);
        foreach ($data as $item) {
            $rankId = $item[Param::A_RANK_ID];
            $result[$rankId] = $item;
        }
        return $result;
    }

    function getQualificationData($dsFrom, $dsTo)
    {
        $result = $this->_repoBonusLoyalty->getQualificationData($dsFrom, $dsTo);
        return $result;
    }

    /**
     * SELECT
     * SUM(pps.total)
     * FROM `prxgt_pv_sale` AS `pps`
     * WHERE (pps.date_paid >= '2016-01-01 08:00:00')
     * AND (pps.date_paid <= '2017-01-01 07:59:59')
     *
     * @param string $dsFrom
     * @param string $dsTo
     */
    function getSalesOrdersPvForPeriod($dsFrom, $dsTo)
    {
        $tsFrom = $this->_toolPeriod->getTimestampFrom($dsFrom);
        $tsTo = $this->_toolPeriod->getTimestampTo($dsTo);
        /* aliases and tables */
        $asSummary = 'summary';
        $asPv = 'pps';
        $tblPv = $this->resource->getTableName(PvSale::ENTITY_NAME);
        // SELECT FROM prxgt_pv_sale pps
        $query = $this->conn->select();
        $query->from([$asPv => $tblPv], [$asSummary => 'SUM(' . PvSale::A_TOTAL . ')']);
        // where
        $whereFrom = $asPv . '.' . PvSale::A_DATE_PAID . '>=' . $this->conn->quote($tsFrom);
        $whereTo = $asPv . '.' . PvSale::A_DATE_PAID . '<=' . $this->conn->quote($tsTo);
        $query->where("$whereFrom AND $whereTo");
        // $sql = (string)$query;
        $result = $this->conn->fetchOne($query);
        return $result;
    }

    public function saveLogRanks($logs)
    {
        foreach ($logs as $transRef => $rankRef) {
            $data = [
                \Praxigento\BonusBase\Repo\Data\Log\Rank::A_TRANS_REF => $transRef,
                \Praxigento\BonusBase\Repo\Data\Log\Rank::A_RANK_REF => $rankRef
            ];
            $this->_repoBonusLogRank->create($data);
        }
    }

    public function saveQualificationParams($updates)
    {
        $def = $this->_manTrans->begin();
        try {
            foreach ($updates as $item) {
                $this->_repoBasic->addEntity(Qualification::ENTITY_NAME, $item);
            }
            $this->_manTrans->commit($def);
        } finally {
            $this->_manTrans->end($def);
        }
    }

}


<?php

/**
 * Phergie plugin for returning the current or last played song for a user on last.fm or libre.fm
 *
 * @link https://github.com/chrismou/phergie-irc-plugin-react-audioscrobbler for the canonical source repository
 * @copyright Copyright (c) 2016 Chris Chrisostomou (https://mou.me)
 * @license http://phergie.org/license New BSD License
 * @package Chrismou\Phergie\Plugin\Audioscrobbler
 */

namespace Chrismou\Phergie\Plugin\Audioscrobbler\Provider;

use Phergie\Irc\Plugin\React\Command\CommandEvent as Event;

/**
 * Last.fm provider for the Audioscrobbler plugin for Phergie
 *
 * @category Chrismou
 * @package Chrismou\Phergie\Plugin\Audioscrobbler\Provider
 */
class Lastfm implements AudioscrobblerProviderInterface
{
    /**
     * @var string
     */
    protected $apiUrl = 'http://ws.audioscrobbler.com/2.0/';

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

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

    /**
     * Validate the provided config
     *
     * @param array $config
     * @return boolean
     */
    public static function validateConfig($config)
    {
        // Requires an API key
        return ($config) ? true : false;
    }

    /**
     * Validate the provided parameters
     *
     * @param array $params
     * @return boolean
     */
    public function validateParams(array $params)
    {
        return (count($params) === 1) ? true : false;
    }

    /**
     * Get the url for the API request
     *
     * @param \Phergie\Irc\Plugin\React\Command\CommandEvent $event
     * @return string
     */
    public function getApiRequestUrl(Event $event)
    {
        return sprintf("%s?%s", $this->apiUrl, http_build_query($this->getApiRequestParams($event)));
    }

    /**
     * Returns a querystring parameters array
     *
     * @param \Phergie\Irc\Plugin\React\Command\CommandEvent $event
     * @return array
     */
    protected function getApiRequestParams(Event $event)
    {
        $params = $event->getCustomParams();
        $user = $params[0];

        return array(
            'format' => 'json',
            'api_key' => $this->apiKey,
            'method' => 'user.getrecenttracks',
            'user' => $user,
            'limit' => '1'
        );
    }

    /**
     * Returns an array of lines to send back to IRC when the http request is successful
     *
     * @param \Phergie\Irc\Plugin\React\Command\CommandEvent $event
     * @param string $apiResponse
     * @return array
     */
    public function getSuccessLines(Event $event, $apiResponse)
    {
        $response = json_decode($apiResponse);
        if (isset($response->recenttracks)) {
            $messages = array($this->getSuccessMessage($response));
        } else {
            $messages = $this->getNoResultsLines($event);
        }

        return $messages;
    }

    /**
     * Returns a message generated from the api request to use in the final response
     *
     * @param object $response
     * @return string
     */
    protected function getSuccessMessage($response)
    {
        $track = (is_array($response->recenttracks->track))
            ? $response->recenttracks->track[0]
            : $response->recenttracks->track;

        return sprintf(
            "%s %s listening to %s by %s %s[ %s ]",
            $response->recenttracks->{'@attr'}->user,
            (isset($track->{'@attr'}->nowplaying)) ? "is" : "was",
            $track->name,
            $track->artist->{'#text'},
            (!isset($track->{'@attr'}->nowplaying)) ? age($track->date->uts) . "ago " : "",
            $track->url
        );
    }

    /**
     * Returns an array of lines to send back to IRC when there are no results
     *
     * @param \Phergie\Irc\Plugin\React\Command\CommandEvent $event
     * @return array
     */
    public function getNoResultsLines(Event $event)
    {
        return array(sprintf('%s does not exist on last.fm', $event->getCustomParams()[0]));
    }

    /**
     * Returns an array of lines for the help response
     *
     * @return array
     */
    public function getHelpLines()
    {
        return array(
            'Usage: lastfm [username]',
            '[username] - the last.fm user to look up',
            'Instructs the bot to query last.fm for this user\'s most recent listened track'
        );
    }
}


<?php
namespace gossi\trixionary\client\action;

use keeko\framework\foundation\AbstractAction;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use gossi\trixionary\model\ObjectQuery;
use keeko\framework\domain\payload\Success;
use keeko\framework\domain\payload\Blank;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Delete an Object
 *
 * This code is automatically created. Modifications will probably be overwritten.
 *
 * @author Thomas Gossmann
 */
class ObjectsDeleteAction extends AbstractAction {

	protected function configureParams(OptionsResolver $resolver) {
		$resolver->setRequired(['id', 'objectId']);
	}

	/**
	 * Automatically generated run method
	 *
	 * @param Request $request
	 * @return Response
	 */
	public function run(Request $request) {
		$object = ObjectQuery::create()->findOneById($this->getParam('objectId'));
		$data = ['sport' => $object->getSport(), 'object' => $object];
		$payload = null;

		if ($request->isMethod('POST')) {
			if ($request->request->get('name') == $object->getTitle()) {
				$object->delete();
				$payload = new Success(['sport' => $object->getSport()]);
			} else {
				$data['error'] = 'Name is wrong';
			}
		}

		if ($payload === null) {
			$payload = new Blank($data);
		}

		return $this->responder->run($request, $payload);
	}
}


<?php
/**
 * @section LICENSE
 * This file is part of MediaWiki simple i18n.
 *
 * MediaWiki simple i18n is free software: you can redistribute it
 * and/or modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * MediaWiki simple i18n is distributed in the hope that it will
 * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 * Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with MediaWiki simple i18n.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @file
 */

namespace Wikimedia\SimpleI18n;

use Psr\Log\LoggerInterface;

/**
 * Holds and optionally detects language for current request. Also serves as
 * a factory for creating Message objects which can be used to subsitute
 * localized message content based on the current language.
 *
 * Collaborates with a MessageCache instance to find localized content for
 * a given Message name.
 *
 * When language detection is performed, the current request paramters are
 * examined for a 'uselang' key. If the get/post data does not specifiy
 * a language the current PHP session is checked for the same key. Finally
 * detection falls back to the Accept-Language header. The best match between
 * languages specified by the header and languages available in the current
 * message cache is used. Any value chosen is stored in the current PHP
 * session for use by later requests.
 *
 * Based on code from the MediaWiki core application and the Wikimania
 * Scholarships application.
 *
 * @copyright © 2014 Bryan Davis and Wikimedia Foundation
 */
class I18nContext {

	/**
	 * @var LoggerInterface $logger
	 */
	protected $logger;

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

	/**
	 * @var MessageCache $messageCache
	 */
	protected $messageCache;

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

	/**
	 * @param MessageCache $cache
	 * @param string $defaultLanguage Language code
	 * @param LoggerInterface $logger
	 */
	public function __construct(
		MessageCache $cache,
		$defaultLanguage = 'en',
		LoggerInterface $logger = null
	) {
		$this->logger = $logger ?: new \Psr\Log\NullLogger();
		$this->messageCache = $cache;
		$this->defaultLanguage = $defaultLanguage;
	}

  /**
   * @param string Language code
   */
	public function setDefaultLangauge( $lang ) {
		$this->defaultLanguage = $lang;
	}

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

	/**
	 * @return MessageCache
	 */
	public function getMessageCache() {
		return $this->messageCache;
	}

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

	/**
	 * @param string $lang Language code
	 */
	public function setCurrentLanguage( $lang ) {
		if ( $lang !== 'qqx' ) {
			if ( !in_array( $lang, $this->getAvailableLanguages() ) ) {
				$lang = $this->defaultLanguage;
			}

			// Remember this language selection for future requests
			$_SESSION['uselang'] = $lang;
		}
		$this->currentLang = $lang;
	}

	/**
	 * Get current language.
	 *
	 * If no language has been set or detected, this will attempt to detect
	 * the user's preferred language by examining the current request, session
	 * and HTTP headers.
	 *
	 * The key 'uselang' is checked in the HTTP request and PHP session. If
	 * not set in either, the Accept-Language header from the request is
	 * parsed to determine potential langauges to select. In all cases, the
	 * current list of known localizations is consulted and if no match is
	 * found, the configured system wide default language is used as
	 * a fallback.
	 *
	 * @return string
	 */
	public function getCurrentLanguage() {
		if ( $this->currentLang === null ) {
			$lang = $this->defaultLanguage;
			if ( isset( $_REQUEST['uselang'] ) ) {
				$lang = $_REQUEST['uselang'];

			} elseif ( isset( $_SESSION['uselang'] ) ) {
				$lang = $_SESSION['uselang'];

			} else {
				$wants = self::parseAcceptLanguage();
				$bestMatches = array_intersect(
					$wants, $this->getAvailableLanguages()
				);
				if ( $bestMatches ) {
					$lang = current( $bestMatches );
				}
			}

			$this->setCurrentLanguage( $lang );
		}
		return $this->currentLang;
	}

	/**
	 * Get a message.
	 *
	 * @param string $key Message name
	 * @param array $params Parameters to add to the message
	 * @return Message
	 */
	public function message( $key, $params = array() ) {
		return new Message( $key, $params, $this, $this->logger );
	}

	/**
	 * Parse the Accept-Language header present in the request and return an
	 * ordered list of languages preferred by the user-agent.
	 *
	 * @return array List of preferred languages
	 */
	public static function parseAcceptLanguage() {
		if ( !isset( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ) {
			return array();
		}

		$weighted = array();

		// Strip any whitespace in the header value
		$hdr = preg_replace( '/\s+/', '', $_SERVER['HTTP_ACCEPT_LANGUAGE'] );
		// Split on commas
		$parts = explode( ',', $hdr );
		foreach ( $parts as $idx => $part ) {
			if ( strpos( $part, ';q=' ) ) {
				// Extract relative weight from component
				list( $lang, $weight ) = explode( ';q=', $part );
				$weight = (float)$weight;

			} else {
				$lang = $part;
				$weight = 1;
			}

			if ( $lang != '*' && $weight > 0 ) {
				// Decorate the weight with the original position to make sort
				// stable
				$weighted[strtolower( $lang )] = array( $weight, -$idx );
			}
		}

		arsort( $weighted );
		return array_keys( $weighted );
	}
}


<?php namespace PhpPackages\Container;

use ReflectionClass;

class Container
{

    /**
     * The container bindings.
     *
     * @var array
     */
    protected $bindings = [];

    /**
     * Binds given value into the container.
     *
     * @param string $binding
     * @param string|object $value
     * @return void
     */
    public function bind($binding, $value)
    {
        $callback = function() use($value) {
            return $this->make($value);
        };

        $callback->bindTo($this);

        $this->bindings[$binding] = $callback;
    }

    /**
     * Resolves the given class' dependencies.
     *
     * @param string|mixed $class
     * @param array $dependencies
     * @throws Exceptions\ClassDoesNotExistException
     * @throws Exceptions\ClassIsNotInstantiableException
     * @throws Exceptions\ResolutionException
     * @return mixed
     */
    public function make($class, array $dependencies = [])
    {
        if ($class instanceof Raw) {
            return $class->getValue();
        }

        if ( ! is_string($class)) {
            return $class;
        }

        if (array_key_exists($class, $this->bindings)) {
            return $this->bindings[$class]();
        }

        if ( ! class_exists($class)) {
            throw new Exceptions\ClassDoesNotExistException($class);
        }

        $reflector = new ReflectionClass($class);

        $isInstantiable =
            is_null($reflector->getConstructor()) ?: $reflector->getConstructor()->isPublic();

        if ($reflector->isAbstract() or ! $isInstantiable) {
            throw new Exceptions\ClassIsNotInstantiableException($class);
        }

        if (count($dependencies) > 0) {
            return $reflector->newInstanceArgs(array_map([$this, "make"], $dependencies));
        }

        if ( ! $resolved = $this->attemptToResolve($reflector)) {
            throw new Exceptions\ResolutionException($class);
        }

        return $resolved;
    }

    /**
     * Attempts to resolve ALL dependencies (in the constructor AND property annotations).
     *
     * @param ReflectionClass $reflector
     * @return boolean|object
     */
    protected function attemptToResolve(ReflectionClass $reflector)
    {
        $dependencies = [];

        foreach ((new TypeHint($reflector))->read() as $parameter) {
            if ( ! $parameter["isClass"]) {
                if ( ! $parameter["hasDefaultValue"]) {
                    return false;
                }

                $dependencies[] = $parameter["defaultValue"];
            } else {
                $dependencies[] = $this->make($parameter["value"]);
            }
        }

        return $this->inject($reflector->newInstanceArgs($dependencies));
    }

    /**
     * Looks for @shouldBeInjected flags in properties' annotations and injects @var values.
     *
     * @param object $instance
     * @return object
     */
    public function inject($instance)
    {
        $reflector = new ReflectionClass($instance);

        foreach ($reflector->getProperties() as $property) {
            /**
             * @var \ReflectionProperty $property
             */
            $block = new DocBlock($property);

            if ( ! $block->hasFlag("shouldBeInjected")) {
                continue;
            }

            if ( ! is_null($class = $block->getValue("var"))) {
                $property->setAccessible(true);
                $property->setValue($instance, $this->make($class));
            }
        }

        return $instance;
    }
}


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

use InvalidArgumentException;

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

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

  /**
   * Ensures the URL passed in is valid
   *
   * @throws  InvalidArgumentException  If the value is not a valid URL
   *
   * @param  string  $url  The value to validate
   *
   * @return  void
   */
  private function validate(string $url): void {
    if(filter_var($url, FILTER_VALIDATE_URL) === false) {
      throw new InvalidArgumentException('Expected URL, but got [' . var_export($url, true) . '] instead');
    }
  }

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

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

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


<?php
/**
 * These are a couple classes that link the dataobject classes to Silverstripe
 * They should generally be subclassed for arrangements, etc.
 * @author Mark GUinn
 */

class ViewableWrapper extends ViewableData
{
    /**
     * if using static publishing, this is the variable name
     */
    protected $varName;

    /**
     * should the __get method make properties "live" in static published documents?
     * var name must be set in order for this to work and the variable it refers
     * to should somehow be set up in getStaticInit() - e.g from the session or a
     * database call or something.
     * can also be an array of which properties are "live"
     */
    protected $liveVars = true;

    /**
     * normally live vars are escaped using htmlentities automatically, but any
     * in this list will be outputted as-is
     */
    protected $liveVarsUnescaped = array();

    /**
     * sets up the object
     * @param object|array $srcdata
     */
    public function __construct($src=false)
    {
        if (is_object($src)) {
            $src->class = get_class($src);
            $this->failover = $src;
        } elseif (is_array($src)) {
            $this->failover = new ArrayData($src);
        }

        parent::__construct();
    }

    /**
     * returns the source object
     */
    public function getRawObject()
    {
        return $this->failover;
    }

    /**
     * Insures that any array or object is wrapped properly
     */
    public function __get($field)
    {
        $val = $this->wrapObject(parent::__get($field));

        if (isset($this->varName) && is_object($val) && $val instanceof ViewableWrapper) {
            $val->setVar($this->varName . '_' . $field);

            // if this variable isn't live, none of it's children should be
            if (!$this->isLiveVar($field)) {
                $val->setLiveVars(false);
            }
        }

        return $val;
    }

    /**
     * Is this variable live in published mode?
     * @param string $field
     * @return bool
     */
    public function isLiveVar($fieldName)
    {
        return $this->liveVars && (!is_array($this->liveVars) || in_array($fieldName, $this->liveVars));
    }

    /**
     * If we're publishing, returns proper php
     */
    public function obj($fieldName, $arguments = null, $forceReturnedObject = true, $cache = false, $cacheName = null)
    {
        $value = parent::obj($fieldName, $arguments, $forceReturnedObject, $cache, $cacheName);

        // if we're publishing and this variable is qualified, output php code instead
        if (
            $this->failover
            && $this->liveVars
            && isset($this->varName)
            && LivePubHelper::is_publishing()
            && $this->isLiveVar($fieldName)
        ) {
            $accessor = "get{$fieldName}";
            $php = '';

            // find out how we got the data
            if ($this->failover instanceof ArrayData) {
                $php = '$' . $this->varName . '["' . $fieldName . '"]';
            } elseif (is_callable(array($this->failover, $fieldName))) {
                // !@TODO respect arguments
                $php = '$' . $this->varName . '->' . $fieldName . '()';
            } elseif (is_callable(array($this->failover, $accessor))) {
                // !@TODO respect arguments
                $php = '$' . $this->varName . '->' . $accessor . '()';
            } elseif (isset($this->failover, $fieldName)) {
                $php = '$' . $this->varName . '->' . $fieldName;
            }

            // return the appropriate php
            if ($php) {
                if (is_object($value)) {
                    if ($value instanceof ViewableWrapper) {
                        LivePubHelper::$init_code[] = '<?php $' . $value->getVar() . ' = ' . $php . ' ?>';
                    }
                    // !@TODO: only other option is DataObjectSet - check that this is handled right
                } else {
                    $value = in_array($fieldName, $this->liveVarsUnescaped)
                        ? '<?php echo ' . $php . '; ?>'
                        : '<?php echo htmlentities(' . $php . '); ?>';
                    if ($forceReturnedObject) {
                        $value = new HTMLText($value);
                    }
                }
            }
        }

        return $value;
    }

    /**
     * if an object isn't already wrapped in Silverstripe's stuff,
     * wrap it appropriately either in a viewableWrapper or dataobject set
     */
    protected function wrapObject($obj)
    {
        if (is_object($obj)) {
            // if it's an object, just check the type and wrap if needed
            if ($obj instanceof ViewableWrapper) {
                return $obj;
            } else {
                return new ViewableWrapper($obj);
            }
        } elseif (is_array($obj)) {
            // if it's an assoc array just wrap it, otherwise make a dataobjectset
            if (ArrayLib::is_associative($obj)) {
                return new ViewableWrapper($obj);
            } else {
                $set = new ArrayList();

                foreach ($obj as $i => $item) {
                    $wrap = $this->wrapObject($item);
                    $set->push($wrap);
                }

                return $set;
            }
        } else {
            // it's a simple type, just return it
            return $obj;
        }
    }

    /**
     * returns the given field as a casted date object
     */
    public function AsDate($field)
    {
        $d = $this->$field;
        return DBField::create('Date', is_numeric($d) ? date('Y-m-d H:i:s', $d) : $d);
    }

    /**
     * returns the given field as a casted date object
     */
    public function AsCurrency($field)
    {
        return DBField::create('Currency', $this->$field);
    }

    /**
     * returns the given field as a uniformly formatted phone #
     * !todo - does this need to work differently for internationals?
     */
    public function AsPhone($field)
    {
        $str = preg_replace('/[^0-9]/', '', $this->$field);
        $out = '';

        switch (strlen($str)) {
            case 11:
            case 12:
                $str = ltrim($str, '0');
                $out .= '+' . substr($str, 0, -10) . ' ';
            case 10:
                $out .= '(' . substr($str, -10, 3) . ') ';
            case 7:
                $out .= substr($str, -7, 3) . '-' . substr($str, -4);
            break;

            default:
                $out = $str;
        }

        return $out;
    }

    public function DebugMe()
    {
        Debug::dump($this);
    }

    /**
     * Return the "casting helper" (a piece of PHP code that when evaluated creates a casted value object) for a field
     * on this object. MODIFIED TO LEAVE FAILOVER ALONE (so it doesn't have to inherit Object).
     *
     * @param string $field
     * @return string
     */
    public function castingHelper($field)
    {
        if ($this->hasMethod('db') && $fieldSpec = $this->db($field)) {
            return $fieldSpec;
        }

        $specs = Object::combined_static(get_class($this), 'casting');
        if (isset($specs[$field])) {
            return $specs[$field];
        }

        //if($this->failover) return $this->failover->castingHelper($field);
    }

    /**
     * This is called by LivePubHelper to retrieve initialization
     * code that gets added to the top of the cached page.
     */
    public function getStaticInit()
    {
        return false;
    }

    /**
     * Set the variable name used for nested wrappers
     * in published mode.
     * @param string $name
     * @return ViewableWrapper (chainable)
     */
    public function setVar($name)
    {
        $this->varName = $name;
        return $this;
    }

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

    /**
     * @param  bool|array $lv
     * @return ViewableWrapper (chainable)
     */
    public function setLiveVars($lv)
    {
        $this->liveVars = $lv;
        return $this;
    }

    /**
     * @return bool|array
     */
    public function getLiveVars()
    {
        return $this->liveVars;
    }

    /**
     * Sets which variables should NOT be escaped.
     * @NOTE this only affects published mode
     * @param  array $vars
     * @return ViewableWrapper (chainable)
     */
    public function setUnescapedVars(array $vars)
    {
        $this->liveVarsUnescaped = $vars;
        return $this;
    }

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