<?php

namespace Data\Type;

use InvalidArgumentException;

class TimeType extends Type
{
    /**
     * Check the value
     *
     * @param  mixed  $value
     * @return string
     */
    public function check($value)
    {
        if ($value instanceof StringType) {
            $value = $value->value();
        } else {
            if (is_array($value)) {
                throw new InvalidArgumentException('Invalid time, array given');
            }

            if (is_resource($value)) {
                throw new InvalidArgumentException('Invalid time, resource given');
            }

            if (is_object($value)) {
                throw new InvalidArgumentException('Invalid time, object given');
            }
        }

        if (preg_match('/^(?P<year>[0-9]{4,4})-(?P<month>[0-9]{2,2})-(?P<day>[0-9]{2,2}) (?P<hour>[0-9]{2,2}):(?P<minute>[0-9]{2,2}):(?P<second>[0-9]{2,2})$/ui', $value, $m)) {
            // month
            if ($m['month'] < 1 || $m['month'] > 12) {
                throw new InvalidArgumentException('Invalid month: ' . $m['month']);
            }

            // day
            $day_max = 31;
            if ($m['month'] === '04' || $m['month'] === '06' || $m['month'] === '09' || $m['month'] === '11') {

            } elseif ($m['month'] === '02') {
                $day_max = 28;
                if (self::checkLeapYear($m['year'])) {
                    $day_max = 29;
                }
            }

            if ($m['day'] < 1 || $m['day'] > $day_max) {
                throw new InvalidArgumentException('Invalid day: ' . $m['day']);
            }

            // hour
            if ($m['hour'] < 0 || $m['hour'] > 23) {
                throw new InvalidArgumentException('Invalid hour: ' . $m['hour']);
            }

            // minute
            if ($m['minute'] < 0 || $m['minute'] > 59) {
                throw new InvalidArgumentException('Invalid minute: ' . $m['minute']);
            }

            // second
            if ($m['second'] < 0 || $m['second'] > 59) {
                throw new InvalidArgumentException('Invalid second: ' . $m['second']);
            }

            return $value;
        }

        throw new InvalidArgumentException('Invalid time: ' . $value . ' given');
    }

    /**
     * Returns the year
     *
     * @return int|null
     */
    public function getYear()
    {
        if ($this->value !== null) {
            preg_match('/^(?P<year>[0-9]{4,4})-(?P<month>[0-9]{2,2})-(?P<day>[0-9]{2,2}) (?P<hour>[0-9]{2,2}):(?P<minute>[0-9]{2,2}):(?P<second>[0-9]{2,2})$/ui', $this->value, $m);
            return (int) $m['year'];
        }
    }

    /**
     * Returns the month
     *
     * @return int|null
     */
    public function getMonth()
    {
        if ($this->value !== null) {
            preg_match('/^(?P<year>[0-9]{4,4})-(?P<month>[0-9]{2,2})-(?P<day>[0-9]{2,2}) (?P<hour>[0-9]{2,2}):(?P<minute>[0-9]{2,2}):(?P<second>[0-9]{2,2})$/ui', $this->value, $m);
            return (int) $m['month'];
        }
    }

    /**
     * Returns the day
     *
     * @return int|null
     */
    public function getDay()
    {
        if ($this->value !== null) {
            preg_match('/^(?P<year>[0-9]{4,4})-(?P<month>[0-9]{2,2})-(?P<day>[0-9]{2,2}) (?P<hour>[0-9]{2,2}):(?P<minute>[0-9]{2,2}):(?P<second>[0-9]{2,2})$/ui', $this->value, $m);
            return (int) $m['day'];
        }
    }

    /**
     * Returns the hour
     *
     * @return int|null
     */
    public function getHour()
    {
        if ($this->value !== null) {
            preg_match('/^(?P<year>[0-9]{4,4})-(?P<month>[0-9]{2,2})-(?P<day>[0-9]{2,2}) (?P<hour>[0-9]{2,2}):(?P<minute>[0-9]{2,2}):(?P<second>[0-9]{2,2})$/ui', $this->value, $m);
            return (int) $m['hour'];
        }
    }

    /**
     * Returns the minute
     *
     * @return int|null
     */
    public function getMinute()
    {
        if ($this->value !== null) {
            preg_match('/^(?P<year>[0-9]{4,4})-(?P<month>[0-9]{2,2})-(?P<day>[0-9]{2,2}) (?P<hour>[0-9]{2,2}):(?P<minute>[0-9]{2,2}):(?P<second>[0-9]{2,2})$/ui', $this->value, $m);
            return (int) $m['minute'];
        }
    }

    /**
     * Returns the second
     *
     * @return int|null
     */
    public function getSecond()
    {
        if ($this->value !== null) {
            preg_match('/^(?P<year>[0-9]{4,4})-(?P<month>[0-9]{2,2})-(?P<day>[0-9]{2,2}) (?P<hour>[0-9]{2,2}):(?P<minute>[0-9]{2,2}):(?P<second>[0-9]{2,2})$/ui', $this->value, $m);
            return (int) $m['second'];
        }
    }

    /**
     * Returns the value in unix timestamp
     *
     * @return int|null
     */
    public function getUnixTimestamp()
    {
        if ($this->value !== null) {
            return strtotime($this->value);
        }
    }

    /**
     * True if it's a leap year
     *
     * @return bool
     */
    public function isLeapYear()
    {
        return self::checkLeapYear($this->getYear());
    }

    /**
     * True if it's a leap year
     *
     * @param  int  $year
     * @return bool
     */
    public static function checkLeapYear($year)
    {
        $year = Cast::_Int($year);

        if ($year % 4 !== 0) {
            return false;
        } elseif ($year % 100 !== 0) {
            return true;
        } elseif ($year % 400 !== 0) {
            return false;
        } elseif ($year === 0) {
            return false;
        }

        return true;
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: claudio
 * Date: 03-04-16
 * Time: 20:44
 */

namespace AscensoDigital\PerfilBundle\DataFixtures\ORM;

use AscensoDigital\PerfilBundle\Entity\Color;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager;

class LoadColorData extends Fixture
{

    /**
     * Load data fixtures with the passed EntityManager
     *
     * @param ObjectManager $manager
     */
    public function load(ObjectManager $manager)
    {
        $amarillo=$manager->getRepository('ADPerfilBundle:Color')->findOneBy(['nombre' => 'Amarillo']);
        if(!$amarillo) {
            $amarillo = new Color();
            $amarillo->setNombre('Amarillo')->setCodigo('fff647');
            $manager->persist($amarillo);
        }
        $this->addReference('clr-amarillo',$amarillo);

        $azul=$manager->getRepository('ADPerfilBundle:Color')->findOneBy(['nombre' => 'Azul']);
        if(!$azul) {
            $azul = new Color();
            $azul->setNombre('Azul')->setCodigo('0000ff');
            $manager->persist($azul);
        }
        $this->addReference('clr-azul',$azul);

        $blanco=$manager->getRepository('ADPerfilBundle:Color')->findOneBy(['nombre' => 'Blanco']);
        if(!$blanco) {
            $blanco = new Color();
            $blanco->setNombre('Blanco')->setCodigo('ffffff');
            $manager->persist($blanco);
        }
        $this->addReference('clr-blanco',$blanco);

        $cafe=$manager->getRepository('ADPerfilBundle:Color')->findOneBy(['nombre' => 'Cafe']);
        if(!$cafe) {
            $cafe = new Color();
            $cafe->setNombre('Cafe')->setCodigo('9d7050');
            $manager->persist($cafe);
        }
        $this->addReference('clr-cafe',$cafe);

        $celeste=$manager->getRepository('ADPerfilBundle:Color')->findOneBy(['nombre' => 'Celeste']);
        if(!$celeste) {
            $celeste = new Color();
            $celeste->setNombre('Celeste')->setCodigo('3875d7');
            $manager->persist($celeste);
        }
        $this->addReference('clr-celeste',$celeste);

        $cian=$manager->getRepository('ADPerfilBundle:Color')->findOneBy(['nombre' => 'Cian']);
        if(!$cian) {
            $cian = new Color();
            $cian->setNombre('Cian')->setCodigo('5ae0d9');
            $manager->persist($cian);
        }
        $this->addReference('clr-cian',$cian);

        $gris=$manager->getRepository('ADPerfilBundle:Color')->findOneBy(['nombre' => 'Gris']);
        if(!$gris) {
            $gris = new Color();
            $gris->setNombre('Gris')->setCodigo('8c8c78');
            $manager->persist($gris);
        }
        $this->addReference('clr-gris',$gris);

        $morado=$manager->getRepository('ADPerfilBundle:Color')->findOneBy(['nombre' => 'Morado']);
        if(!$morado) {
            $morado = new Color();
            $morado->setNombre('Morado')->setCodigo('7a0c5d');
            $manager->persist($morado);
        }
        $this->addReference('clr-morado',$morado);

        $naranjo=$manager->getRepository('ADPerfilBundle:Color')->findOneBy(['nombre' => 'Naranjo']);
        if(!$naranjo) {
            $naranjo = new Color();
            $naranjo->setNombre('Naranjo')->setCodigo('ff8922');
            $manager->persist($naranjo);
        }
        $this->addReference('clr-naranjo',$naranjo);

        $negro=$manager->getRepository('ADPerfilBundle:Color')->findOneBy(['nombre' => 'Negro']);
        if(!$negro) {
            $negro = new Color();
            $negro->setNombre('Negro')->setCodigo('000000');
            $manager->persist($negro);
        }
        $this->addReference('clr-negro',$negro);

        $rojo=$manager->getRepository('ADPerfilBundle:Color')->findOneBy(['nombre' => 'Rojo']);
        if(!$rojo) {
            $rojo = new Color();
            $rojo->setNombre('Rojo')->setCodigo('e8121d');
            $manager->persist($rojo);
        }
        $this->addReference('clr-rojo',$rojo);

        $rosado=$manager->getRepository('ADPerfilBundle:Color')->findOneBy(['nombre' => 'Rosado']);
        if(!$rosado) {
            $rosado = new Color();
            $rosado->setNombre('Rosado')->setCodigo('ff6be1');
            $manager->persist($rosado);
        }
        $this->addReference('clr-rosado',$rosado);

        $verde=$manager->getRepository('ADPerfilBundle:Color')->findOneBy(['nombre' => 'Verde']);
        if(!$verde) {
            $verde = new Color();
            $verde->setNombre('Verde')->setCodigo('76ff61');
            $manager->persist($verde);
        }
        $this->addReference('clr-verde',$verde);

        $violeta=$manager->getRepository('ADPerfilBundle:Color')->findOneBy(['nombre' => 'Violeta']);
        if(!$violeta) {
            $violeta = new Color();
            $violeta->setNombre('Violeta')->setCodigo('bc12e6');
            $manager->persist($violeta);
        }
        $this->addReference('clr-violeta',$violeta);

        $manager->flush();
    }
}


<?php
/**
 *
 * LICENCE
 *
 * This file is subject to the terms and conditions defined in
 * file 'LICENSE.txt', which is part of this source code package.
 *
 * @author EPOKMEDIA
 * @copyright Copyright (c) EPOKMEDIA SARL
 *
 */

namespace Epkm\MessagePackRpc;

use Epkm\MessagePackRpc\Exception\RequestErrorException;

/**
 * Class Client
 *
 * @package Epkm\MessagePackRpc
 */
class Client {

    /**
     * @var Back
     */
    protected $back = null;

    /**
     * @var string
     */
    protected $host = null;

    /**
     * @var int
     */
    protected $port = null;

    /**
     * @param string    $host
     * @param int       $port
     * @param Back\null $back
     */
    public function __construct($host, $port, $back = null)
    {
        $this->back = $back == null ? new Back() : $back;
        $this->host = $host;
        $this->port = $port;
    }

    /**
     * @param string $func
     * @param mixed  $args
     *
     * @return mixed
     * @throws Exception\RequestErrorException
     */
    public function send($func, $args)
    {
        $host    = $this->host;
        $port    = $this->port;
        $code    = 0;
        $call    = $this->back->clientCallObject($code, $func, $args);
        $send    = $this->back->clientConnection($host, $port, $call);

        $future = $this->back->clientRecvObject($send);

        $result  = $future->getResult();
        $errors  = $future->getErrors();

        if ($errors !== null) {

            if (is_array($errors)) {
                $errors = '[' . implode(', ', $errors) . ']';
            } else if (is_object($errors)) {
                if (method_exists($errors, '__toString')) {
                    $errors = $errors->__toString();
                } else {
                    $errors = print_r($errors, true);
                }
            }

            throw new RequestErrorException("{$errors}");
        }

        return $result;
    }

    /**
     * @param string $func
     * @param mixed  $args
     *
     * @return mixed
     */
    public function call($func, $args)
    {
        return $this->send($func, $args);
    }
}


<?php
/**
 * The file for an interval
 *
 * @author     Jack Clayton <clayjs0@gmail.com>
 * @copyright  2016 Jack Clayton
 * @license    MIT
 */

namespace Jstewmc\Interval;

use InvalidArgumentException;

/**
 * A numeric interval
 *
 * @since  0.1.0
 * @since  0.2.0  add support for infinity
 */
class Interval
{
    /* !Constants */

    /**
     * @var    string  the placeholder for positive infinity
     * @since  0.2.0
     */
    const INFINITY_POSITIVE = 'INF';

    /**
     * @var    string  the placeholder for negative infinity
     * @since  0.2.0
     */
    const INFINITY_NEGATIVE = '-INF';

    /* !Private properties */

    /**
     * @var    bool  a flag indicating whether or not the lower-bound is inclusive
     *     (optional; defaults to false)
     * @since  0.1.0
     */
    private $isLowerInclusive = false;

    /**
     * @var    bool  a flag indicating whether or not the upper-bound is inclusive
     *     (optional; defaults to false)
     * @since  0.1.0
     */
    private $isUpperInclusive = false;

    /**
     * @var    mixed  the interval's lower bound
     * @since  0.1.0
     */
    private $lower;

    /**
     * @var    string  the interval's separator
     * @since  0.1.0
     */
    private $separator = ', ';

    /**
     * @var    mixed  the interval's upper bound
     * @since  0.1.0
     */
    private $upper;

    /* !Magic methods */

    /**
     * Called when the interval is constructed
     *
     * @param  string|null  $string  the interval (e.g., "[0, 2]") (optional)
     * @since  0.1.0
     */
    public function __construct(string $interval = null)
    {
        if ($interval !== null) {
            $this->parse($interval);
        }
    }

    /**
     * Called when the interval is treated like a string
     *
     * @return  string
     * @since   0.1.0
     * @since   0.2.0  add support for infinity
     */
    public function __toString(): string
    {
        $string = '';

        // append the lower boundary
        $string .= $this->isLowerInclusive ? '[' : '(';

        // get the endpoints as an array
        $endpoints = [$this->lower, $this->upper];

        // loop through the endpoints
        foreach ($endpoints as &$endpoint) {
            // get the value as a string based on its value
            if ($endpoint === -INF) {
                $endpoint = self::INFINITY_NEGATIVE;
            } elseif ($endpoint === INF) {
                $endpoint = self::INFINITY_POSITIVE;
            } else {
                $endpoint = (string) $endpoint;
            }
        }

        // append the lower bound, separator, and upper bound
        $string .= implode($this->separator, $endpoints);

        // append the upper boundary
        $string .= $this->isUpperInclusive ? ']' : ')';

        return $string;
    }

    /* !Get methods */

    /**
     * Returns the interval's is-lower-inclusive flag
     *
     * @return  bool
     * @since   0.1.0
     */
    public function getIsLowerInclusive(): bool
    {
        return $this->isLowerInclusive;
    }

    /**
     * Returns the interval's is-upper-inclusive flag
     *
     * @return  bool
     * @since   0.1.0
     */
    public function getIsUpperInclusive(): bool
    {
        return $this->isUpperInclusive;
    }

    /**
     * Returns the interval's lower value
     *
     * @return  int|float
     * @since   0.1.0
     */
    public function getLower()
    {
        return $this->lower;
    }

    /**
     * Returns the interval's separator
     *
     * @return  string
     * @since   0.1.0
     */
    public function getSeparator(): string
    {
        return $this->separator;
    }

    /**
     * Returns the interval's lower bound
     *
     * @return  int|float
     * @since   0.1.0
     */
    public function getUpper()
    {
        return $this->upper;
    }

    /* !Set methods */

    /**
     * Sets the interval's is-lower-inclusive flag
     *
     * @param   bool  $isLowerInclusive
     * @return  self
     * @since   0.1.0
     */
    public function setIsLowerInclusive(bool $isLowerInclusive): self
    {
        $this->isLowerInclusive = $isLowerInclusive;

        return $this;
    }

    /**
     * Sets the interval's is-upper-inclusive flag
     *
     * @param   bool  $isUpperInclusive
     * @return  self
     * @since   0.1.0
     */
    public function setIsUpperInclusive(bool $isUpperInclusive): self
    {
        $this->isUpperInclusive = $isUpperInclusive;

        return $this;
    }

    /**
     * Sets the interval's lower value
     *
     * @param   int|float  $lower
     * @return  self
     * @throws  InvalidArgumentException  if $lower is not a number
     * @since   0.1.0
     */
    public function setLower($lower): self
    {
        // if $lower is not a number, short-circuit
        if ( ! is_numeric($lower)) {
            throw new InvalidArgumentException(
                __METHOD__ . "() expects parameter one, lower, to be a number"
            );
        }

        $this->lower = +$lower;

        return $this;
    }

    /**
     * Sets the interval's separator
     *
     * @param   string  $separator
     * @return  self
     * @since   0.1.0
     */
    public function setSeparator(string $separator): self
    {
        $this->separator = $separator;

        return $this;
    }

    /**
     * Sets the interval's upper value
     *
     * @param   int|float  $upper
     * @return  self
     * @throws  InvalidArgumentException  if $upper is not a number
     * @since   0.1.0
     */
    public function setUpper($upper): self
    {
        if ( ! is_numeric($upper)) {
            throw new InvalidArgumentException(
                __METHOD__ . "() expects parameter one, upper, to be a number"
            );
        }

        $this->upper = $upper;

        return $this;
    }

    /* !Public methods */

    /**
     * Compare a value to the interval
     *
     * If $x is below the interval, I'll return -1. If $x is above the interval, I'll
     * return 1. Otherwise, $x is inside the interval, and I'll return 0.
     *
     * @param   int|float  $x  the value to compare
     * @return  int
     */
    public function compare($x): int
    {
        // if $x is not numeric, short-circuit
        if ( ! is_numeric($x)) {
            throw new InvalidArgumentException(
                __METHOD__ . "() expects parameter one, x, to be a number"
            );
        }

        if (
            $x < $this->lower
            || ( ! $this->isLowerInclusive && $x == $this->lower)
        ) {
            return -1;
        } elseif (
            $x > $this->upper
            || ( ! $this->isUpperInclusive && $x == $this->upper)
        ) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * Returns true if the lower-bound is exclusive
     *
     * @return  bool
     * @since   0.1.0
     */
    public function isLowerExclusive(): bool
    {
        return ! $this->isLowerInclusive;
    }

    /**
     * Returns true if the lower-bound is inclusive
     *
     * @return  bool
     * @since   0.1.0
     */
    public function isLowerInclusive(): bool
    {
        return $this->isLowerInclusive;
    }

    /**
     * Returns true if the upper-bound is exclusive
     *
     * @return  bool
     * @since   0.1.0
     */
    public function isUpperExclusive(): bool
    {
        return ! $this->isUpperInclusive;
    }

    /**
     * Returns true if the upper-bound is inclusive
     *
     * @return  bool
     * @since   0.1.0
     */
    public function isUpperInclusive(): bool
    {
        return $this->isUpperInclusive;
    }

    /**
     * Parses an interval string
     *
     * @param   string  $string  the string to parse
     * @return  self
     * @throws  InvalidArgumentException  if $string is not a valid interval
     * @throws  InvalidArgumentException  if the upper is greater than lower
     * @throws  InvalidArgumentException  if the endpoints and equal but the
     *     boundaries are not equal (e.g., (1, 1])
     * @since   0.1.0
     * @since   0.2.0  add support for infinity
     */
    public function parse(string $string): self
    {
        // if the $string is not valid interval, short-circuit
        $pattern = '/^[\[\(]-?(\d*[\.]?\d+|INF), -?(\d*[\.]?\d+|INF)[\]\)]$/';
        if ( ! preg_match($pattern, $string)) {
            throw new InvalidArgumentException(
                __METHOD__ . "() expects parameter one, string, to be a valid "
                    . "interval; see the README for details"
            );
        }

        // otherwise, check the boundaries
        $this->isLowerInclusive = substr($string, 0, 1) === '[';
        $this->isUpperInclusive = substr($string, -1, 1) === ']';

        // get the endpoints
        $endpoints = explode($this->separator, substr($string, 1, -1));

        // loop through the endpoints
        foreach ($endpoints as &$endpoint) {
            // if the endpoint is negative or positive infinity, convert the value
            //     to the PHP constant; otherwise, cast the value to int or float
            //
            if ($endpoint === self::INFINITY_NEGATIVE) {
                $endpoint = -INF;
            } elseif ($endpoint === self::INFINITY_POSITIVE) {
                $endpoint = INF;
            } else {
                $endpoint = +$endpoint;
            }
        }

        // if the endpoints are out of order, short-circuit
        if ($endpoints[1] < $endpoints[0]) {
            throw new InvalidArgumentException(
                __METHOD__ . "() expects parameter one, string, to be a valid "
                    . "interval, however, the upper bound appears to be greater "
                    . "than the lower bound"
            );
        }

        // if the endpoints are equal, the boundaries must match
        if (
            $endpoints[0] == $endpoints[1]
            && $this->isLowerInclusive !== $this->isUpperInclusive
        ) {
            throw new InvalidArgumentException(
                __METHOD__ . "() expects parameter one, string, to be a valid "
                    . "interval, however, the endpoints are the same but the "
                    . "boundaries are different"
            );
        }

        // otherwise, set the endpoints
        $this->lower = $endpoints[0];
        $this->upper = $endpoints[1];

        return $this;
    }

    /**
     * Sets the is-lower-inclusive flag to false
     *
     * @return  self
     * @since   0.1.0
     */
    public function setLowerExclusive(): self
    {
        $this->isLowerInclusive = false;

        return $this;
    }

    /**
     * Sets the is-lower-inclusive flag to true
     *
     * @return  self
     * @since   0.1.0
     */
    public function setLowerInclusive(): self
    {
        $this->isLowerInclusive = true;

        return $this;
    }

    /**
     * Sets the is-upper-inclusive flag to false
     *
     * @return  self
     * @since   0.1.0
     */
    public function setUpperExclusive(): self
    {
        $this->isUpperInclusive = false;

        return $this;
    }

    /**
     * Sets the is-upper-inclusive flag to true
     *
     * @return  self
     * @since   0.1.0
     */
    public function setUpperInclusive(): self
    {
        $this->isUpperInclusive = true;

        return $this;
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: tonigurski
 * Date: 11.11.15
 * Time: 14:10.
 */
namespace MandarinMedien\MMMediaBundle\Entity;

use MandarinMedien\MMMediaBundle\Form\MediaType;
use MandarinMedien\MMMediaBundle\Model\MediaInterface;
use MandarinMedien\MMMediaBundle\Model\MediaTypeInterface;

class Media implements MediaInterface
{
    /**
     * @var int
     */
    protected $id;

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

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

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

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

    /**
     * @var \DateTime
     */
    protected $createdAt;

    /**
     * @var \DateTime
     */
    protected $updatedAt;

    /**
     * @var MediaTypeInterface
     */
    protected $mediaType;

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

    /**
     * @var array
     */
    protected $mediaTypeMetadata = array();

    public function prePersist()
    {
        $this->setCreatedAt(new \DateTime());
        $this->setUpdatedAt(new \DateTime());
    }

    public function preUpdate()
    {
        $this->setUpdatedAt(new \DateTime());
    }

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

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

    /**
     * @param string $name
     *
     * @return Media
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

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

    /**
     * @param string $description
     *
     * @return Media
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

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

    /**
     * @param string $copyright
     *
     * @return Media
     */
    public function setCopyright($copyright)
    {
        $this->copyright = $copyright;

        return $this;
    }

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

    /**
     * @param string $author
     *
     * @return Media
     */
    public function setAuthor($author)
    {
        $this->author = $author;

        return $this;
    }

    /**
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * @param \DateTime $createdAt
     *
     * @return Media
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    /**
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * @param \DateTime $updatedAt
     *
     * @return Media
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * @return MediaTypeInterface
     */
    public function getMediaType()
    {
        return $this->mediaType;
    }

    /**
     * @param MediaTypeInterface $mediaType
     *
     * @return Media
     */
    public function setMediaType(MediaTypeInterface $mediaType)
    {
        $this->mediaType = $mediaType;

        return $this;
    }

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

    /**
     * @param string $mediaTypeReference
     *
     * @return Media
     */
    public function setMediaTypeReference($mediaTypeReference)
    {
        $this->mediaTypeReference = $mediaTypeReference;

        return $this;
    }

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

    /**
     * @param array $mediaTypeMetadata
     *
     * @return Media
     */
    public function setMediaTypeMetadata(array $mediaTypeMetadata)
    {
        $this->mediaTypeMetadata = $mediaTypeMetadata;

        return $this;
    }

    /**
     * @param string $name
     * @param null   $default
     *
     * @return mixed
     */
    public function getMediaTypeMetadataValue($name, $default = null)
    {
        $metadata = $this->getMediaTypeMetadata();

        return isset($metadata[$name]) ? $metadata[$name] : $default;
    }

    /**
     * @param string $name
     * @param mixed  $value
     */
    public function setMediaTypeMetadataValue($name, $value)
    {
        $metadata = $this->getMediaTypeMetadata();
        $metadata[$name] = $value;
        $this->setMediaTypeMetadata($metadata);
    }

    /**
     * @param string $name
     */
    public function unsetMediaTypeMetadataValue($name)
    {
        $metadata = $this->getMediaTypeMetadata();
        unset($metadata[$name]);
        $this->setMediaTypeMetadata($metadata);
    }

    public function __toString()
    {
        return 'image'.$this->getId();
    }

    public function getPreview($options = null)
    {
        return $this->getMediaType()->getPreview($this, $options);
    }
}


<?php

namespace Havvg\Component\Search\Engine;

use Havvg\Component\Search\Exception\DomainException;
use Havvg\Component\Search\Exception\InvalidArgumentException;
use Havvg\Component\Search\Result\ResultCollection;
use Havvg\Component\Search\Result\ResultInterface;

class ChainEngine implements EngineInterface
{
    /**
     * @var EngineInterface[]
     */
    protected $engines;

    public function __construct(array $engines = array())
    {
        foreach ($engines as $eachEngine) {
            if (!$eachEngine instanceof EngineInterface) {
                throw new InvalidArgumentException('At least one of the given engine is invalid.');
            }
        }

        $this->engines = $engines;
    }

    /**
     * Add another search engine to the chain.
     *
     * @param EngineInterface $engine
     *
     * @return ChainEngine
     */
    public function addEngine(EngineInterface $engine)
    {
        $this->engines[] = $engine;

        return $this;
    }

    /**
     * Perform the search based on the query.
     *
     * The query may be anything, from a simple search string to a complex query structure.
     * It's based on a contract between the engine and the application.
     *
     * @param mixed $query
     *
     * @return ResultInterface[]|ResultCollection
     */
    public function search($query)
    {
        $results = new ResultCollection();

        foreach ($this->engines as $eachEngine) {
            if (!$eachEngine->supports($query)) {
                continue;
            }

            if ($more = $eachEngine->search($query)) {
                if (!is_array($more) and !$more instanceof \Traversable) {
                    throw new DomainException('The returned result set is not traversable.');
                }

                foreach ($more as $eachResult) {
                    $results->add($eachResult);
                }
            }
        }

        return $results;
    }

    /**
     * Check whether this engines supports the given query type.
     *
     * The chain engine supports the query, if at least one chained engine supports it.
     *
     * @param mixed $query
     *
     * @return bool
     */
    public function supports($query)
    {
        foreach ($this->engines as $eachEngine) {
            if ($eachEngine->supports($query)) {
                return true;
            }
        }

        return false;
    }
}


<?php

/**
 * This file is part of RawPHP - a PHP Framework.
 *
 * Copyright (c) 2014 RawPHP.org
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 * PHP version 5.3
 *
 * @category  PHP
 * @package   RawPHP\RawRouter
 * @author    Tom Kaczocha <tom@rawphp.org>
 * @copyright 2014 Tom Kaczocha
 * @license   http://rawphp.org/license.txt MIT
 * @link      http://rawphp.org/
 */

namespace RawPHP\RawRouter;

use RawPHP\RawRouter\Contract\IAction;

/**
 * This class represents a controllers action as controller/action route.
 *
 * @category  PHP
 * @package   RawPHP\RawRouter
 * @author    Tom Kaczocha <tom@rawphp.org>
 * @copyright 2014 Tom Kaczocha
 * @license   http://rawphp.org/license.txt MIT
 * @link      http://rawphp.org/
 */
class Action implements IAction
{
    private $_name;
    private $_params;

    /**
     * Action constructor.
     *
     * @param string $name   action name
     * @param array  $params action parameters
     */
    public function __construct( $name, $params = NULL )
    {
        if ( FALSE === strstr( $name, 'Action' ) )
        {
            $name = $name . 'Action';
        }

        $this->_name = str_replace( '.php', '', $name );

        $this->_init( $params );
    }

    /**
     * Initialises the action.
     *
     * @param array $params configuration array
     */
    private function _init( $params )
    {
        if ( NULL !== $params && 0 < count( $params ) )
        {
            foreach ( $params as $key => $value )
            {
                $this->_params[ ] = $value;
            }
        }
    }

    /**
     * Checks if this action has any parameters.
     *
     * @return bool TRUE if parameters exist, else FALSE
     */
    public function hasParams()
    {
        $result = ( 0 < count( $this->_params ) );

        return $result;
    }

    /**
     * Returns the action parameters.
     *
     * @return array the parameters (if any)
     */
    public function getParams()
    {
        return $this->_params;
    }

    /**
     * Returns the name of the action.
     *
     * @return string the action name
     */
    public function getName()
    {
        return $this->_name;
    }
}


<?php

// be safe and sane.  use strictmode if available via composer.
$autoload_file = __DIR__ . '/vendor/autoload.php';
if( file_exists( $autoload_file )) {
    require_once($autoload_file);
    \strictmode\initializer::init();
}

/***
 * A class to print text in formatted tables.
 */
class texttable {

    /**
     * Formats a fixed-width text table, with borders.
     *
     * @param $rows  array of rows.  each row contains table cells.
     * @param $headertype  keys | firstrow | none/null
     * @param $footertype  keys | lastrow | none/null
     * @param $empty_row_string  String to use when there is no data, or null.
     */
    static public function table( $rows, $headertype = 'keys', $footertype = 'none', $empty_row_string = 'No Data' ) {

        if( !@count( $rows ) ) {

            if( $empty_row_string !== null ) {
                $rows = [ [ $empty_row_string ] ];
            }
            else {
                return '';
            }
        }

        $header = $footer = null;
        if( $headertype == 'keys' ) {
            $header = array_keys( static::obj_arr( $rows[0] ) );
        }
        else if( $headertype == 'firstrow' ) {
            $header = static::obj_arr( array_shift( $rows ) );
        }
        if( $footertype == 'keys' && count( $rows ) ) {
            $footer = array_keys( static::obj_arr( $rows[count($rows) - 1] ) );
        }
        else if( $footertype == 'lastrow' && count( $rows ) ) {
            $footer = static::obj_arr( array_pop( $rows ) );
        }

        $col_widths = array();

        if( $header ) {
            static::calc_row_col_widths( $col_widths, $header );
        }
        if( $footer ) {
            static::calc_row_col_widths( $col_widths, $footer );
        }
        foreach( $rows as $row ) {
            $row = static::obj_arr( $row );
            static::calc_row_col_widths( $col_widths, $row );
        }

        $buf = '';
        $buf .= static::print_divider_row( $col_widths, 'top' );
        if( $header ) {
            $buf .= static::print_header($col_widths, $header );
        }
        foreach( $rows as $row ) {
            $row = static::obj_arr( $row );
            $buf .= static::print_row( $col_widths, $row );
        }
        $buf .= static::print_divider_row( $col_widths, 'bottom' );
        if( $footer ) {
            $buf .= static::print_footer($col_widths, $footer );
        }

        return $buf;
    }

    static protected function print_footer($col_widths, $footer) {
        $buf  = static::print_row( $col_widths, $footer );
        $buf .= static::print_divider_row( $col_widths, 'footer' );
        return $buf;
    }

    static protected function print_header($col_widths, $header) {
        $buf  = static::print_row( $col_widths, $header );
        $buf .= static::print_divider_row( $col_widths, 'header' );
        return $buf;
    }

    static protected function print_divider_row( $col_widths, $position ) {
        $buf = '+';
        foreach( $col_widths as $width ) {
            $buf .= '-' . str_pad( '-', $width, '-' ) . "-+";
        }
        $buf .= "\n";
        return $buf;
    }

    static protected function print_row( $col_widths, $row ) {
        $buf = '|';
        $idx = 0;
        foreach( $row as $val ) {
            $pad_type = is_numeric( $val ) ? STR_PAD_LEFT : STR_PAD_RIGHT;
            $buf .= ' ' . str_pad( $val, $col_widths[$idx], ' ', $pad_type ) . " |";
            $idx ++;
        }
        return $buf . "\n";
    }

    static protected function calc_row_col_widths( &$col_widths, $row ) {
        $idx = 0;
        foreach( $row as $val ) {
            $len = strlen( $val );
            if( $len > @$col_widths[$idx] ) {
                $col_widths[$idx] = $len;
            }
            $idx ++;
        }
    }

    static protected function obj_arr( $t ) {
       return is_object( $t ) ? get_object_vars( $t ) : $t;
    }
}


<?php
/**
 * AnimeDb package.
 *
 * @author    Peter Gribanov <info@peter-gribanov.ru>
 * @copyright Copyright (c) 2014, Peter Gribanov
 * @license   http://opensource.org/licenses/MIT
 */

namespace AnimeDb\Bundle\CacheTimeKeeperBundle\Service\Driver;

class Dummy extends BaseDriver
{
    /**
     * @var array
     */
    protected $times = [];

    /**
     * @param string $key
     *
     * @return \DateTime|null
     */
    public function get($key)
    {
        if (isset($this->times[$key])) {
            return clone $this->times[$key];
        }

        return;
    }

    /**
     * @param string $key
     * @param \DateTime $time
     *
     * @return bool
     */
    public function set($key, \DateTime $time)
    {
        $this->times[$key] = clone $time;

        return true;
    }

    /**
     * @param string $key
     *
     * @return bool
     */
    public function remove($key)
    {
        if (isset($this->times[$key])) {
            unset($this->times[$key]);

            return true;
        }

        return false;
    }
}


<?php
/**
 * Phossa Project
 *
 * PHP version 5.4
 *
 * @category  Library
 * @package   Phossa\Query
 * @author    Hong Zhang <phossa@126.com>
 * @copyright 2015 phossa.com
 * @license   http://mit-license.org/ MIT License
 * @link      http://www.phossa.com/
 */
/*# declare(strict_types=1); */

namespace Phossa\Query\Clause;

/**
 * DeleteRecordTrait
 *
 * @package Phossa\Query
 * @author  Hong Zhang <phossa@126.com>
 * @see     DeleteRecordInterface
 * @version 1.0.0
 * @since   1.0.0 added
 */
trait DeleteRecordTrait
{
    /**
     * @var    array
     * @access protected
     */
    protected $clause_records = [];

    /**
     * {@inheritDoc}
     */
    public function record($table)
    {
        $this->clause_records = is_array($table) ? $table : [$table];
        return $this;
    }

    /**
     * Build table to delete
     *
     * @return array
     * @access protected
     */
    protected function buildRecord()/*# : array */
    {
        $res = [];
        foreach ($this->clause_records as $tbl) {
            $res[] = $this->quote($tbl) . '.*';
        }
        if (!empty($res)) {
            return [join(', ', $res)];
        } else {
            return [];
        }
    }

    /* utilities from UtilityTrait */
    abstract protected function quote(/*# string */ $str)/*# : string */;
}


<?php

namespace BluePsyduck\Common\Data;

use DateTime;

/**
 * A container class wrapping around a data array offering casting methods.
 *
 * @author BluePsyduck <bluepsyduck@gmx.com>
 * @license http://opensource.org/licenses/GPL-3.0 GPL v3
 */
class DataContainer
{
    /**
     * The data array of the container.
     * @var array
     */
    protected $data = [];

    /**
     * Initializes the data container.
     * @param array $data
     */
    public function __construct($data)
    {
        if (is_array($data)) {
            $this->data = $data;
        }
    }

    /**
     * Returns the data array to work with.
     * @return array
     */
    public function getData(): array
    {
        return $this->data;
    }

    /**
     * Returns a value from the data container.
     * @param string|string[]
     * @param mixed $default
     * @return mixed
     */
    public function get($keys, $default = null)
    {
        $result = $this->data;
        foreach (is_array($keys) ? $keys : [$keys] as $key) {
            if (is_array($result) && isset($result[$key])) {
                $result = $result[$key];
            } else {
                $result = $default;
                break;
            }
        }
        return $result;
    }

    /**
     * Returns a boolean value from the data container.
     * @param string|string[] $keys
     * @param bool $default
     * @return bool
     */
    public function getBoolean($keys, bool $default = false): bool
    {
        return (bool)$this->get($keys, $default);
    }

    /**
     * Returns an integer value from the data container.
     * @param string|string[] $keys
     * @param int $default
     * @return int
     */
    public function getInteger($keys, int $default = 0): int
    {
        return (int)$this->get($keys, $default);
    }

    /**
     * Returns a floating point number from the data container.
     * @param string|string[] $keys
     * @param float $default
     * @return float
     */
    public function getFloat($keys, float $default = 0.): float
    {
        return (float)$this->get($keys, $default);
    }

    /**
     * Returns a string from the data container.
     * @param string|string[] $keys
     * @param string $default
     * @return string
     */
    public function getString($keys, string $default = ''): string
    {
        return trim((string)$this->get($keys, $default));
    }

    /**
     * Returns a DateTime instance from the data container. A string value is interpreted as date string, an integer
     * value is interpreted as UNIX timestamp.
     * @param string|string[] $keys
     * @param DateTime|null $default
     * @return DateTime|null
     */
    public function getDateTime($keys, DateTime $default = null)
    {
        $value = $this->getString($keys);
        if (empty($value)) {
            $result = $default;
        } elseif ($value === (string)(int)$value) {
            $result = new DateTime();
            $result->setTimestamp((int)$value);
        } else {
            $result = new DateTime($value);
        }
        return $result;
    }

    /**
     * Returns an object from the data container. The result is always a new data container.
     * @param string|string[] $keys
     * @return DataContainer
     */
    public function getObject($keys): DataContainer
    {
        return $this->createObject($this->get($keys));
    }

    /**
     * Returns an array of values from the data containers.
     * @param string|string[] $keys
     * @param array $default
     * @return array
     */
    public function getArray($keys, array $default = []): array
    {
        $result = $this->get($keys, $default);
        if (!is_array($result)) {
            $result = $default;
        }
        return $result;
    }

    /**
     * Returns an array of objects from the data container. All values of the resulting array are casted to new
     * data container instances.
     * @param string|string[] $keys
     * @return array|DataContainer[]
     */
    public function getObjectArray($keys): array
    {
        return array_map(function ($value) {
            return $this->createObject($value);
        }, $this->getArray($keys));
    }

    /**
     * Creates a new instance with the specified data.
     * @param mixed $data
     * @return DataContainer
     */
    protected function createObject($data): DataContainer
    {
        return new static($data);
    }
}


<?php

namespace Miky\Bundle\UserBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use FOS\MessageBundle\Model\ParticipantInterface;
use Miky\Bundle\AdBundle\Entity\Ad;

use Miky\Bundle\CommentBundle\Model\CommentInterface;
use Miky\Component\Media\Model\MediaInterface;
use Miky\Bundle\UserBundle\Model\Employee as BaseEmployee;
use Miky\Component\Core\Model\CommonModelTrait;
use Miky\Component\Resource\Model\ResourceInterface;

/**
 * Employee
 */
class Employee extends BaseEmployee  implements CommentInterface, ResourceInterface
{
    Use CommonModelTrait;

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

    /**
     * @var Ad[]
     */
    protected $adsValidation;

    /**
     * @var MediaInterface
     */
    private $profileImage;

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

    /**
     * Add adsValidation
     *
     * @param \Miky\Bundle\AdBundle\Entity\Ad $adsValidation
     *
     * @return Employee
     */
    public function addAdsValidation(\Miky\Bundle\AdBundle\Entity\Ad $adsValidation)
    {
        $this->adsValidation[] = $adsValidation;

        return $this;
    }

    /**
     * Remove adsValidation
     *
     * @param \Miky\Bundle\AdBundle\Entity\Ad $adsValidation
     */
    public function removeAdsValidation(\Miky\Bundle\AdBundle\Entity\Ad $adsValidation)
    {
        $this->adsValidation->removeElement($adsValidation);
    }

    /**
     * Get adsValidation
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getAdsValidation()
    {
        return $this->adsValidation;
    }

    /**
     * @return MediaInterface
     */
    public function getProfileImage()
    {
        return $this->profileImage;
    }

    /**
     * @param MediaInterface $profileImage
     */
    public function setProfileImage($profileImage)
    {
        $this->profileImage = $profileImage;
    }

}


<?php
declare(strict_types=1);
/**
 * Caridea
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 * @copyright 2015-2017 Appertly
 * @copyright 2017-2018 LibreWorks contributors
 * @license   Apache-2.0
 */
namespace Caridea\Http;

use Psr\Http\Message\ResponseInterface as Response;
use Caridea\Http\Pagination;

/**
 * A trait that can be used by any class that needs to output typical JSON.
 */
trait JsonHelper
{
    /**
     * Send something as JSON.
     *
     * @param \Psr\Http\Message\ResponseInterface $response  The response
     * @param mixed $payload  The object to serialize
     * @return \Psr\Http\Message\ResponseInterface  The JSON response
     */
    protected function sendJson(Response $response, $payload): Response
    {
        $response->getBody()->write(json_encode($payload));
        return $response->withHeader('Content-Type', 'application/json');
    }

    /**
     * Sends a Content-Range header for pagination.
     *
     * @param \Psr\Http\Message\ResponseInterface $response  The response
     * @param iterable $items  The items to serialize
     * @param \Caridea\Http\Pagination|null $pagination  The pagination object
     * @param int|null $total  The total number of records, if `$items` is a subset
     * @return \Psr\Http\Message\ResponseInterface  The JSON response
     */
    protected function sendItems(Response $response, iterable $items, ?Pagination $pagination = null, ?int $total = null): Response
    {
        $items = is_array($items) ? $items : ($items instanceof \Traversable ? iterator_to_array($items, false) : []);
        $total = $total ?? count($items);
        $start = $pagination === null ? 0 : $pagination->getOffset();
        $max = $pagination === null ? 0 : $pagination->getMax();
        // make sure $end is no higher than $total and isn't negative
        $end = max(min((PHP_INT_MAX - $max < $start ? PHP_INT_MAX : $start + $max), $total) - 1, 0);
        return $this->sendJson(
            $response->withHeader('Content-Range', "items $start-$end/$total"),
            $items
        );
    }

    /**
     * Send notice that an entity was created.
     *
     * @param \Psr\Http\Message\ResponseInterface $response  The response
     * @param string $type  The entity type
     * @param array<mixed> $ids  The entity ids
     * @param array<string,mixed> $extra  Any extra data to serialize
     * @return \Psr\Http\Message\ResponseInterface  The JSON response
     */
    protected function sendCreated(Response $response, string $type, array $ids, array $extra = []): Response
    {
        return $this->sendVerb('created', $response, $type, $ids, $extra)
            ->withStatus(201, "Created");
    }

    /**
     * Send notice that objects were deleted.
     *
     * @param \Psr\Http\Message\ResponseInterface $response  The response
     * @param string $type  The entity type
     * @param array<mixed> $ids  The entity ids
     * @param array<string,mixed> $extra  Any extra data to serialize
     * @return \Psr\Http\Message\ResponseInterface  The JSON response
     */
    protected function sendDeleted(Response $response, string $type, array $ids, array $extra = []): Response
    {
        return $this->sendVerb('deleted', $response, $type, $ids, $extra);
    }

    /**
     * Send notice that objects were updated.
     *
     * @param \Psr\Http\Message\ResponseInterface $response  The response
     * @param string $type  The entity type
     * @param array<mixed> $ids  The entity ids
     * @param array<string,mixed> $extra  Any extra data to serialize
     * @return \Psr\Http\Message\ResponseInterface  The JSON response
     */
    protected function sendUpdated(Response $response, string $type, array $ids, array $extra = []): Response
    {
        return $this->sendVerb('updated', $response, $type, $ids, $extra);
    }

    /**
     * Sends a generic notice that objects have been operated on.
     *
     * @param string $verb  The verb
     * @param \Psr\Http\Message\ResponseInterface $response  The response
     * @param string $type  The entity type
     * @param array<mixed> $ids  The entity ids
     * @param array<string,mixed> $extra  Any extra data to serialize
     * @return \Psr\Http\Message\ResponseInterface  The JSON response
     */
    protected function sendVerb(string $verb, Response $response, string $type, array $ids, array $extra = []): Response
    {
        $send = array_merge([], $extra);
        $send['success'] = true;
        $send['message'] = "Objects $verb successfully";
        $send['objects'] = array_map(function ($id) use ($type) {
            return ['type' => $type, 'id' => $id];
        }, $ids);
        return $this->sendJson($response, $send);
    }
}


<?php
/**
 * Phossa Project
 *
 * PHP version 5.4
 *
 * @category  Library
 * @package   Phossa\Query
 * @author    Hong Zhang <phossa@126.com>
 * @copyright 2015 phossa.com
 * @license   http://mit-license.org/ MIT License
 * @link      http://www.phossa.com/
 */
/*# declare(strict_types=1); */

namespace Phossa\Query\Clause;

/**
 * FunctionTrait
 *
 * @package Phossa\Query
 * @author  Hong Zhang <phossa@126.com>
 * @version 1.0.0
 * @since   1.0.0 added
 */
trait FunctionTrait
{
    use ColTrait;

    /**
     * {@inheritDoc}
     */
    public function func(
        /*# string */ $function,
        /*# string */ $col,
        /*# string */ $alias = ''
    ) {
        $rawMode = $this->isRaw($col);
        if ('' === $alias) {
            $this->clause_column[] = [$rawMode, $col, $function];
        } else {
            $this->clause_column[(string) $alias] = [$rawMode, $col, $function];
        }
        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function count(
        /*# string */ $col,
        /*# string */ $alias = ''
    ) {
        return $this->func('COUNT(%s)', $col, $alias);
    }

    /**
     * {@inheritDoc}
     */
    public function min(/*# string */ $col, /*# string */ $alias = '')
    {
        return $this->func('MIN(%s)', $col, $alias);
    }

    /**
     * {@inheritDoc}
     */
    public function max(/*# string */ $col, /*# string */ $alias = '')
    {
        return $this->func('MAX(%s)', $col, $alias);
    }

    /**
     * {@inheritDoc}
     */
    public function avg(/*# string */ $col, /*# string */ $alias = '')
    {
        return $this->func('AVG(%s)', $col, $alias);
    }

    /**
     * {@inheritDoc}
     */
    public function sum(/*# string */ $col, /*# string */ $alias = '')
    {
        return $this->func('SUM(%s)', $col, $alias);
    }

    /**
     * {@inheritDoc}
     */
    public function sumDistinct(/*# string */ $col, /*# string */ $alias = '')
    {
        return $this->func('SUM(DISTINCT %s)', $col, $alias);
    }

    /* utilities from UtilityTrait */
    abstract protected function isRaw(/*# string */ $string)/*# : bool */;
}


<?php

/**
 * @author      José Lorente <jose.lorente.martin@gmail.com>
 * @license     The MIT License (MIT)
 * @copyright   José Lorente
 * @version     1.0
 */

namespace jlorente\location\validators;

use jlorente\location\db\State;
use Yii;
use yii\validators\Validator;

/**
 * Validator to check the existence of a state id in the database.
 *
 * @author José Lorente <jose.lorente.martin@gmail.com>
 */
class StateValidator extends Validator
{

    /**
     * If setted, the validator with fill the country attribute with the
     * country_id of the validated region.
     *
     * @var string
     */
    public $countryAttribute;

    /**
     * @inheritdoc
     */
    public function validateAttribute($model, $attribute)
    {
        parent::validateAttribute($model, $attribute);
        if ($model->$attribute !== null) {
            $state = State::findOne($model->$attribute);
            if ($state === null) {
                $this->addError($attribute, Yii::t('location', 'State with id {[id]} doesn\'t exist', [
                            'id' => $model->$attribute
                ]));
                return false;
            }
            if (empty($this->countryAttribute) === false) {
                $model->{$this->countryAttribute} = $state->country_id;
            }
        }
        return true;
    }

    /**
     * @inheritdoc
     *
     * Checks if the given region id exists.
     */
    protected function validateValue($value)
    {
        if (State::find()->andWhere(['id' => $value])->exists() === false) {
            return Yii::t('location', 'State with id {[id]} doesn\'t exist', [
                        'id' => $value
            ]);
        }
    }

}


<?php
/*
 * Copyright (c) 2014 @trashtoy
 * https://github.com/trashtoy/
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
 * Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
/**
 * PHP class file.
 * @auhtor trashtoy
 * @since  2.0.0
 */
namespace Peach\DT;

use Peach\Util\ArrayMap;
use Peach\DT\SimpleFormat\Pattern;
use Peach\DT\SimpleFormat\Numbers;
use Peach\DT\SimpleFormat\Raw;

/**
 * Java の
 * {@link http://docs.oracle.com/javase/jp/7/api/java/text/SimpleDateFormat.html SimpleDateFormat}
 * と同じような使い勝手で, ユーザー定義の書式を扱うことができるクラスです.
 * 日付・時刻のパターンは {@link www.php.net/manual/function.date.php date()} の一部を採用しています.
 *
 * - Y: 年 (4桁固定)
 * - m: 月 (2桁固定)
 * - n: 月 (1～2桁)
 * - d: 日 (2桁固定)
 * - j: 日 (1～2桁)
 * - H: 時 (2桁固定)
 * - G: 時 (1～2桁)
 * - i: 分 (2桁固定)
 * - s: 秒 (2桁固定)
 *
 * 以下は, このクラス独自の拡張パターンです.
 *
 * - f: 分 (1～2桁)
 * - b: 秒 (1～2桁)
 * - E: 曜日 (後述)
 *
 * "2012年5月21日(月)" のように曜日を含む書式の入出力を行う場合は,
 * コンストラクタの第 2 引数に曜日文字列の一覧を指定してください.
 * 以下に例を示します.
 * <code>
 * $format = new SimpleFormat("Y年n月j日(E)", array("日", "月", "火", "水", "木", "金", "土"));
 * </code>
 * 第 2 引数を省略した場合はデフォルト値として array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")
 * が適用されます.
 *
 * パターンを繋げて記述する場合は (例: "Ymd_His" など)
 * 必ず固定長のパターンを使用してください.
 * 可変長 (n, j, G など) のパターンは常に最長一致でマッチングするため,
 * 繋げて記述した際にパースに失敗する可能性があります.
 *
 * このクラスは, 月の文字列表記 (例えば "Jan", "Feb" など) のためのパターンをサポートしません.
 * そのようなフォーマットが必要となった場合は, 独自の Format クラスを定義する必要があります.
 *
 * パースまたは書式化を行う際, 情報が足りない場合はデフォルト値が指定されます.
 * 年・月・日については現在の日付, 時・分・秒については 0 が適用されます.
 * 具体的には, 以下のような状況が相当します.
 *
 * 1. パースする際, オブジェクトを構成するために必要な情報をパターン文字列が網羅していなかった.
 *    (例: "m/d" というパターンをパースした場合,
 *   「年」の情報がパターン文字列に含まれていないため, 現在の年が適用されます)
 * 2. 時間オブジェクトを書式化する際に, パターン文字列に含まれるフィールドを
 *    そのオブジェクトが持っていなかった.
 *    (例: "Y/m/d H:i:s" というパターンで Date オブジェクトを書式化した場合,
 *    Date は時刻の情報を持たないため, 時刻部分は 00:00:00 となります.)
 *
 * PHP の date() 関数の実装と同様に,
 * バックスラッシュをつけることでパターン文字列が展開されるのを抑制することができます.
 *
 * このクラスはイミュータブルです. 一つのオブジェクトを複数の箇所で使いまわすことが出来ます.
 */
class SimpleFormat implements Format
{
    /**
     * parse または format に使うパターン文字列です.
     * @var string
     */
    private $format;

    /**
     * 曜日文字列の一覧を表す, 長さ 7 の配列です.
     * @var array
     */
    private $dayList;

    /**
     * Pattern オブジェクトの配列です.
     * キーが "Y", "n" などのパターン文字, 値がその文字に該当する
     * Pattern オブジェクトとなります.
     *
     * @var array
     */
    private $patternList;

    /**
     * パターン文字列を分解した結果をあらわします.
     *
     * @var array
     */
    private $context;

    /**
     * 指定されたパターン文字列で SimpleFormat を初期化します.
     *
     * @param string $pattern パターン文字列
     * @param array  $dayList 曜日文字列の配列. デフォルトは array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")
     */
    public function __construct($pattern, array $dayList = array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"))
    {
        $format            = strval($pattern);
        $this->format      = $format;
        $this->dayList     = $this->initDayList($dayList);
        $this->patternList = $this->initPatternList($this->dayList);
        $this->context     = $this->createContext($format);
    }

    /**
     * 曜日文字列を初期化します.
     * もしも配列の長さが 7 より大きかった場合, 8 個目以降の要素は無視されます.
     *
     * @param  array $dayList 引数
     * @return array          曜日文字列の配列
     * @throws \InvalidArgumentException 配列の長さが 7 未満であるか, または空文字列が含まれている場合
     */
    private function initDayList(array $dayList)
    {
        $values = array_slice(array_values($dayList), 0, 7);
        $count  = count($values);
        if ($count !== 7) {
            throw new \InvalidArgumentException("Invalid array count({$count}). Expected: 7");
        }
        for ($i = 0; $i < 7; $i++) {
            $value = $values[$i];
            if (!strlen($value)) {
                throw new \InvalidArgumentException("Daystring is empty at index {$i}");
            }
        }
        return $values;
    }

    /**
     * パターン文字の一覧を作成します.
     * @param  array $dayList 曜日文字列の配列
     * @return array          Pattern オブジェクトの配列
     */
    private function initPatternList(array $dayList)
    {
        $patternList      = $this->getDefaultPatternList();
        $patternList["E"] = new Raw($dayList);
        return $patternList;
    }

    /**
     * このオブジェクトのパターン文字列を返します.
     * @return string パターン文字列
     */
    public function getFormat()
    {
        return $this->format;
    }

    /**
     * 指定された文字列を解析し, Date に変換します.
     * @param  string $format 解析対象の文字列
     * @return Date           解析結果
     */
    public function parseDate($format)
    {
        $d = Date::now();
        return $d->setAll($this->interpret($format));
    }

    /**
     * 指定された文字列を解析し, Datetime に変換します.
     * @param  string $format 解析対象の文字列
     * @return Datetime       解析結果
     */
    public function parseDatetime($format)
    {
        $d = Date::now();
        return $d->toDatetime()->setAll($this->interpret($format));
    }

    /**
     * 指定された文字列を解析し, Timestamp に変換します.
     * @param  string $format 解析対象の文字列
     * @return Date           解析結果
     */
    public function parseTimestamp($format)
    {
        $d = Date::now();
        return $d->toTimestamp()->setAll($this->interpret($format));
    }

    /**
     * 指定された Date オブジェクトを書式化します.
     * @param  Date $d 書式化対象の時間オブジェクト
     * @return string  このフォーマットによる文字列表現
     */
    public function formatDate(Date $d)
    {
        return $this->formatTimestamp($d->toTimestamp());
    }

    /**
     * 指定された Datetime オブジェクトを書式化します.
     * @param  Datetime $d 書式化対象の時間オブジェクト
     * @return string      このフォーマットによる文字列表現
     */
    public function formatDatetime(Datetime $d)
    {
        return $this->formatTimestamp($d->toTimestamp());
    }

    /**
     * 指定された Timestamp オブジェクトを書式化します.
     * @param  Timestamp $d 書式化対象の時間オブジェクト
     * @return string       このフォーマットによる文字列表現
     */
    public function formatTimestamp(Timestamp $d)
    {
        $patternList = $this->patternList;
        $result      = "";
        foreach ($this->context as $part) {
            $buf = array_key_exists($part, $patternList) ? $this->formatKey($d, $part) : stripslashes($part);
            $result .= $buf;
        }
        return $result;
    }

    /**
     * パターン一覧を返します.
     * キーが変換文字, 値がその文字に対応する Pattern オブジェクトとなります.
     *
     * @return array
     * @codeCoverageIgnore
     */
    private function getDefaultPatternList()
    {
        static $patterns = null;
        if (!isset($patterns)) {
            $fixed4   = "\\d{4}";
            $fixed2   = "\\d{2}";
            $var2     = "[1-5][0-9]|[0-9]";
            $varM     = "1[0-2]|[1-9]";
            $varD     = "3[0-1]|[1-2][0-9]|[0-9]";
            $varH     = "2[0-4]|1[0-9]|[0-9]";
            $patterns = array(
                "Y" => new Numbers("year",   $fixed4),
                "m" => new Numbers("month",  $fixed2),
                "n" => new Numbers("month",  $varM),
                "d" => new Numbers("date",   $fixed2),
                "j" => new Numbers("date",   $varD),
                "H" => new Numbers("hour",   $fixed2),
                "G" => new Numbers("hour",   $varH),
                "i" => new Numbers("minute", $fixed2),
                "f" => new Numbers("minute", $var2),
                "s" => new Numbers("second", $fixed2),
                "b" => new Numbers("second", $var2),
            );
        }
        return $patterns;
    }

    /**
     * 指定された文字列に相当する Pattern オブジェクトを返します.
     *
     * @param  string $part
     * @return Pattern
     * @codeCoverageIgnore
     */
    private function getPatternByPart($part)
    {
        $patterns = $this->patternList;
        return array_key_exists($part, $patterns) ? $patterns[$part] : new Raw(array(stripslashes($part)));
    }

    /**
     * 指定されたパターン文字を, 対応するフィールドの値に変換します.
     *
     * @param  Time   $d   変換対象の時間オブジェクト
     * @param  string $key パターン文字 ("Y", "m", "d" など)
     * @return int         変換結果
     * @throws \Exception  不正なパターン文字が指定された場合
     */
    private function formatKey(Time $d, $key)
    {
        $year  = $d->get("year");
        $month = $d->get("month");
        $date  = $d->get("date");
        $hour  = $d->get("hour");
        $min   = $d->get("minute");
        $sec   = $d->get("second");

        switch ($key) {
            case "Y":
                return str_pad($year,  4, "0", STR_PAD_LEFT);
            case "m":
                return str_pad($month, 2, "0", STR_PAD_LEFT);
            case "n":
                return $month;
            case "d":
                return str_pad($date,  2, "0", STR_PAD_LEFT);
            case "j":
                return $date;
            case "H":
                return str_pad($hour,  2, "0", STR_PAD_LEFT);
            case "G":
                return $hour;
            case "i":
                return str_pad($min,   2, "0", STR_PAD_LEFT);
            case "f":
                return $min;
            case "s":
                return str_pad($sec,   2, "0", STR_PAD_LEFT);
            case "b":
                return $sec;
            case "E":
                return $this->dayList[$d->getDay()];
        }

        // @codeCoverageIgnoreStart
        throw new \Exception("Illegal pattern: " . $key);
        // @codeCoverageIgnoreEnd
    }

    /**
     * 指定されたパターン文字列 (例えば "Y/m/d" など) を構文解析します.
     *
     * @param  string $format パターン文字列
     * @return array          解析結果
     */
    private function createContext($format)
    {
        $patternList = $this->patternList;
        $result      = array();
        $current     = "";
        $escaped     = false;
        for ($i = 0, $length = strlen($format); $i < $length; $i ++) {
            $chr = substr($format, $i, 1);
            if ($escaped) {
                $current .= $chr;
                $escaped = false;
            } else if ($chr === "\\") {
                $current .= $chr;
                $escaped = true;
            } else if (array_key_exists($chr, $patternList)) {
                if (strlen($current)) {
                    $result[] = $current;
                    $current = "";
                }
                $result[] = $chr;
            } else {
                $current .= $chr;
            }
        }
        if (strlen($current)) {
            $result[] = $current;
        }
        return $result;
    }

    /**
     * 指定されたテキストを構文解析します.
     *
     * @param  string $text 解析対象の文字列
     * @return ArrayMap     構文解析した結果
     */
    private function interpret($text)
    {
        $input       = $text;
        $result      = new ArrayMap();
        $matched     = null;
        foreach ($this->context as $part) {
            $pattern = $this->getPatternByPart($part);
            $matched = $pattern->match($input);
            if ($matched === null) {
                throw $this->createFormatException($input, $this->format);
            }
            $pattern->apply($result, $matched);
            $input = substr($input, strlen($matched));
        }
        return $result;
    }

    /**
     * 文字列を時間オブジェクトに変換する際に, 不正な文字列が指定されたことをあらわす例外を生成します.
     *
     * @param  string $format   指定された文字列
     * @param  string $expected 想定されるパターン文字列
     * @return \InvalidArgumentException
     */
    private function createFormatException($format, $expected)
    {
        return new \InvalidArgumentException("Illegal format({$format}). Expected: {$expected}");
    }
}


<?php
/**
 * Phossa Project
 *
 * PHP version 5.4
 *
 * @category  Library
 * @package   Phossa\Query
 * @author    Hong Zhang <phossa@126.com>
 * @copyright 2015 phossa.com
 * @license   http://mit-license.org/ MIT License
 * @link      http://www.phossa.com/
 */
/*# declare(strict_types=1); */

namespace Phossa\Query\Clause;

/**
 * TableOptionTrait
 *
 * @package Phossa\Query
 * @author  Hong Zhang <phossa@126.com>
 * @see     TableOptionInterface
 * @version 1.0.0
 * @since   1.0.0 added
 */
trait TableOptionTrait
{
    /**
     * table options
     *
     * @var    array
     * @access protected
     */
    protected $tbl_option = [];

    /**
     * {@inheritDoc}
     */
    public function tblOption(/*# string */ $string)
    {
        $this->tbl_option[] = $string;
        return $this;
    }

    /**
     * Build table options
     *
     * @return array
     * @access protected
     */
    protected function buildTblOpt()/*# : array */
    {
        $result = [];

        foreach ($this->tbl_option as $opt) {
            $result[] = $opt;
        }
        if (empty($result)) {
            $result[] = '';
        }

        return $result;
    }
}


<?php

namespace Smrtr;

/**
 * Class HaltoRouter
 *
 * This is a fork of https://github.com/dannyvankooten/AltoRouter with hostname matching built in
 * and basepath functionality stripped out.
 *
 * @package Smrtr
 * @author Joe Green
 */
class HaltoRouter
{
    /**
     * @var array
     */
    protected $routes = array();

    /**
     * @var array
     */
    protected $namedRoutes = array();

    /**
     * @var array
     */
    protected $httpHostGroups = array();

    /**
     * Add a hostname to a hostgroup (creates the hostgroup if it doesn't exist).
     *
     * @param string $hostname
     * @param string $hostGroup
     *
     * @return $this
     *
     * @throws HaltoRouterException
     */
    public function addHostname($hostname, $hostGroup)
    {
        if (!is_string($hostGroup)) {
            throw new HaltoRouterException("Invalid hostgroup name");
        }

        if (!is_string($hostname)) {
            throw new HaltoRouterException("Invalid hostname");
        }

        if (!array_key_exists($hostGroup, $this->httpHostGroups)) {
            $this->httpHostGroups[$hostGroup] = array();
        }

        if (!in_array($hostname, $this->httpHostGroups[$hostGroup])) {
            $this->httpHostGroups[$hostGroup][] = $hostname;
        }

        return $this;
    }

    /**
     * Add an array of hostnames to a hostgroup (creates the hostgroup if it doesn't exist).
     *
     * @param array $hostnames
     * @param string $hostGroup
     *
     * @return $this
     *
     * @throws HaltoRouterException
     */
    public function addHostnames(array $hostnames, $hostGroup)
    {
        if (!is_string($hostGroup)) {
            throw new HaltoRouterException("Invalid hostgroup name");
        }

        if (!is_array($hostnames)) {
            throw new HaltoRouterException("Array of hostnames expected");
        }

        if (!array_key_exists($hostGroup, $this->httpHostGroups)) {
            $this->httpHostGroups[$hostGroup] = array();
        }

        foreach ($hostnames as $hostname) {
            if (!is_string($hostname)) {
                continue;
            }
            if (!in_array($hostname, $this->httpHostGroups[$hostGroup])) {
                $this->httpHostGroups[$hostGroup][] = $hostname;
            }
        }

        return $this;
    }

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

    /**
     * Add a route mapping to the router.
     *
     * @param string $method One, or a pipe-separated list, of Http Methods (GET|POST|PUT|DELETE)
     * @param string $route The route. Custom regex starts with @. You can use pre-set regex filters, like [i:id]
     * @param mixed  $target The target where this route should point to. Can be anything.
     * @param string $name Optional name of the route. Supply if you want to reverse route this url in your application.
     * @param string $hostGroup Optional hostGroup bound to route - the route will only match requests on these hosts.
     * @param bool   $prepend Optional
     *
     * @return $this
     *
     * @throws HaltoRouterException
     */
    public function map($method, $route, $target, $name = null, $hostGroup = null, $prepend = false)
    {
        if (!$hostGroup) {
            $hostGroup = null;
        }

        if ($prepend) {
            array_unshift($this->routes, array($method, $route, $target, $name, $hostGroup));
        } else {
            $this->routes[] = array($method, $route, $target, $name, $hostGroup);
        }

        if ($name) {
            if (array_key_exists($name, $this->namedRoutes)) {
                throw new HaltoRouterException("Can not redeclare route $name");
            }

            $this->namedRoutes[$name] = array($route, $hostGroup);
        }

        return $this;
    }

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

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

    /**
     * Match a given Request against stored routes.
     *
     * @param string $requestUrl
     * @param string $requestMethod
     * @param string $requestHost
     * @param bool   $looseMatching
     *
     * @return array|boolean Array with route information on success, false on failure (no match).
     */
    public function match($requestUrl, $requestMethod, $requestHost, $looseMatching = false)
    {
        $params = array();
        $validGroups = $this->getValidHostGroups($requestHost);

        foreach ($this->routes as $handler) {
            list($method, $_route, $target, $name, $hostGroup) = $handler;
            if (null !== $hostGroup) {
                $hostGroups = explode('|', $hostGroup);
                if (!count(array_intersect($hostGroups, $validGroups))) {
                    continue;
                }
            }

            $methods = explode('|', $method);
            $method_match = false;
            foreach ($methods as $method) {
                if (strcasecmp($requestMethod, $method) === 0) {
                    $method_match = true;
                    break;
                }
            }
            if (!$method_match) {
                continue;
            }

            if ($looseMatching) {
                if (substr($_route, -1) === '$') {
                   if (substr($_route, strlen($_route) - 2, 1) === '/') {
                       $_route = sprintf('%s?$', substr($_route, 0, strlen($_route) - 1));
                   } elseif (substr($_route, -2) !== '/?') {
                       $_route = sprintf('%s/?$', substr($_route, 0, strlen($_route) - 1));
                   }
                } elseif (substr($_route, -1) === '/') {
                    $_route = sprintf('%s?', $_route);
                } elseif (substr($_route, -2) !== '/?') {
                    $_route = sprintf('%s/?', $_route);
                }
            }

            if ($_route === '*') {
                $match = true;
            } elseif (isset($_route[0]) && $_route[0] === '@') {
                $match = preg_match('`' . substr($_route, 1) . '`', $requestUrl, $params);
            } else {
                $route = null;
                $regex = false;
                $j = 0;
                $n = isset($_route[0]) ? $_route[0] : null;
                $i = 0;
                while (true) {
                    if (!isset($_route[$i])) {
                        break;
                    } elseif (false === $regex) {
                        $c = $n;
                        $regex = $c === '[' || $c === '(' || $c === '.';
                        if (false === $regex && false !== isset($_route[$i+1])) {
                            $n = $_route[$i + 1];
                            $regex = $n === '?' || $n === '+' || $n === '*' || $n === '{';
                        }
                        if (false === $regex && $c !== '/' && (!isset($requestUrl[$j]) || $c !== $requestUrl[$j])) {
                            continue 2;
                        }
                        $j++;
                    }
                    $route .= $_route[$i++];
                }
                $regex = $this->compileRoute($route);
                $match = preg_match($regex, $requestUrl, $params);
            }

            if ($match == true || $match > 0) {

                if ($params) {
                    foreach ($params as $key => $value) {
                        if (is_numeric($key)) {
                            unset($params[$key]);
                        } elseif ('controller' == $key) {
                            $controller = preg_replace('#([-]+)#', ' ', urldecode($value));
                            $controller = str_replace(' ', '', ucwords($controller));
                            unset($params[$key]);
                        } elseif ('action' == $key) {
                            $action = preg_replace('#([-]+)#', ' ', urldecode($value));
                            $action = lcfirst(str_replace(' ', '', ucwords($action)));
                            unset($params[$key]);
                        } else {
                            $params[$key] = urldecode($value);
                        }
                    }
                }

                if (isset($controller) || isset($action)) {
                    $targets = explode('@', $target, 2);
                    $C = isset($targets[0]) ? $targets[0] : 'Index';
                    $A = isset($targets[1]) ? $targets[1] : 'index';
                    $target =
                        (isset($controller) ? str_replace('@', '', $controller) : $C)
                        .'@'
                        .(isset($action) ? str_replace('@', '', $action) : $A);
                }

                return array(
                    'target' => $target,
                    'params' => $params,
                    'name' => $name
                );
            }
        }

        return false;
    }

    /**
     * @param string $requestHost
     *
     * @return array
     */
    protected function getValidHostGroups($requestHost)
    {
        $validGroups = array();

        foreach ($this->httpHostGroups as $group => $hostnames) {
            if (in_array($requestHost, $hostnames)) {
                $validGroups[] = $group;
            }
        }

        return $validGroups;
    }

    /**
     * Reversed routing
     *
     * Generate the URL for a named route. Replace regexes with supplied parameters.
     *
     * @param string $routeName The name of the route.
     * @param array  $params Associative array of parameters to replace placeholders with.
     * @param string $hostname Optional; specify a valid hostname or one will be detected automatically if possible.
     * @param string $protocol Specify a protocol including "://" if you wish
     * @param int    $port Optional; specify a port to use in the generated URL
     *
     * @return string The URL of the route with named parameters in place.
     *
     * @throws HaltoRouterException
     */
    public function generate($routeName, array $params = array(), $hostname = null, $protocol = '//', $port = null)
    {
        // Check if named route exists
        if(!isset($this->namedRoutes[$routeName])) {
            throw new HaltoRouterException("Route '{$routeName}' does not exist.");
        }

        // Replace named parameters
        $hostGroup = $this->namedRoutes[$routeName][1];
        $route = $this->namedRoutes[$routeName][0];
        $url = $route;

        if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) {

            foreach($matches as $match) {
                list($block, $pre, $type, $param, $optional) = $match;

                if ($pre) {
                    $block = substr($block, 1);
                }

                if(isset($params[$param])) {
                    $url = str_replace($block, $params[$param], $url);
                } elseif ($optional) {
                    $url = str_replace($pre . $block, '', $url);
                }
            }

        }

        // Try to include the hostname and protocol
        $hasHostPart = false;
        if (is_string($hostGroup) && array_key_exists($hostGroup, $this->httpHostGroups)) {

            $hasHostPart = true;

            if (is_string($hostname) && in_array($hostname, $this->httpHostGroups[$hostGroup])) {
                $hostPart = rtrim($hostname, '/');
            } else {
                $hostPart = $this->httpHostGroups[$hostGroup][0];
            }

            if (is_int($port)) {
                $hostPart .= ':' . $port;
            }

            $url = $hostPart . '/' . ltrim($url, '/');
        }

        if ($hasHostPart) {
            $url = $protocol . $url;
        }

        return $url;
    }

    /**
     * Compile the regex for a given route
     */
    private function compileRoute($route)
    {
        if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) {

            $match_types = array(
                'i'  => '[0-9]++',
                'a'  => '[0-9A-Za-z]++',
                'h'  => '[0-9A-Fa-f]++',
                '*'  => '.+?',
                '**' => '.++',
                ''   => '[^/\.]++'
            );

            foreach ($matches as $match) {
                list($block, $pre, $type, $param, $optional) = $match;

                if (isset($match_types[$type])) {
                    $type = $match_types[$type];
                }
                if ($pre === '.') {
                    $pre = '\.';
                }

                //Older versions of PCRE require the 'P' in (?P<named>)
                $pattern = '(?:'
                        . ($pre !== '' ? $pre : null)
                        . '('
                        . ($param !== '' ? "?P<$param>" : null)
                        . $type
                        . '))'
                        . ($optional !== '' ? '?' : null);

                $route = str_replace($block, $pattern, $route);
            }

        }
        return "`^$route$`";
    }
}


<?php

namespace Orchid\Log\Tables;

use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Orchid\Log\Contracts\Utilities\LogLevels as LogLevelsContract;

class StatsTable extends AbstractTable
{
    /**
     * Make a stats table instance.
     *
     * @param array                                     $data
     * @param \Orchid\Log\Contracts\Utilities\LogLevels $levels
     * @param string|null                               $locale
     *
     * @return \Orchid\Log\Tables\StatsTable
     */
    public static function make(array $data, LogLevelsContract $levels, $locale = null)
    {
        return new self($data, $levels, $locale);
    }

    /**
     * Get json totals data.
     *
     * @param string|null $locale
     *
     * @return string
     */
    public function totalsJson($locale = null)
    {
        return $this->totals($locale)->toJson(JSON_PRETTY_PRINT);
    }

    /**
     * Get totals.
     *
     * @param string|null $locale
     *
     * @return \Illuminate\Support\Collection
     */
    public function totals($locale = null)
    {
        $this->setLocale($locale);

        $totals = Collection::make();

        foreach (Arr::except($this->footer(), 'all') as $level => $count) {
            $totals->put($level, [
                'label'     => trans('dashboard::logs.'.$level),
                'value'     => $count,
                'color'     => $this->color($level),
                'highlight' => $this->color($level),
            ]);
        }

        return $totals;
    }

    /**
     * Prepare table header.
     *
     * @param array $data
     *
     * @return array
     */
    protected function prepareHeader(array $data)
    {
        return array_merge_recursive(
            [
                'date' => trans('dashboard::logs.date'),
                'all'  => trans('dashboard::logs.all'),
            ],
            $this->levels->names($this->locale)
        );
    }

    /**
     * Prepare table rows.
     *
     * @param array $data
     *
     * @return array
     */
    protected function prepareRows(array $data)
    {
        $rows = [];

        foreach ($data as $date => $levels) {
            $rows[$date] = array_merge(compact('date'), $levels);
        }

        return $rows;
    }

    /**
     * Prepare table footer.
     *
     * @param array $data
     *
     * @return array
     */
    protected function prepareFooter(array $data)
    {
        $footer = [];

        foreach ($data as $date => $levels) {
            foreach ($levels as $level => $count) {
                if (!isset($footer[$level])) {
                    $footer[$level] = 0;
                }

                $footer[$level] += $count;
            }
        }

        return $footer;
    }
}


<?php

namespace Data\Type;

use InvalidArgumentException;

class BoolType extends Type
{
    /**
     * Check the value
     *
     * @param  mixed $value
     * @return bool
     */
    protected function check($value)
    {
        if ($value === false || $value === 0 || $value === 0.0 || $value === '0') {
            return false;
        }

        if ($value === true || $value === 1 || $value === 1.0 || $value === '1') {
            return true;
        }

        if ($value instanceof BoolType) {
            return $value->value();
        }

        if ($value instanceof Type) {
            $value = $value->value();
        } else {
            if (is_array($value)) {
                throw new InvalidArgumentException('Invalid bool, array given');
            }

            if (is_resource($value)) {
                throw new InvalidArgumentException('Invalid bool, resource given');
            }

            if (is_object($value)) {
                throw new InvalidArgumentException('Invalid bool, object given');
            }
        }

        if ($value === 0 || $value === 0.0 || $value === '0') {
            return false;
        }

        if ($value === 1 || $value === 1.0 || $value === '1') {
            return true;
        }

        throw new InvalidArgumentException('Invalid bool: ' . $value);
    }
}


<?php
/**
 * php 文件缓存类
 */
namespace niklaslu;

class FileCache{

    protected $filePath;

    public function __construct($filePath = '')
    {
        $filePath = $filePath ? $filePath : dirname(dirname(__FILE__)).'/cache';
        $this->filePath = $filePath;
    }
    /**
     * 获得缓存数据
     * @param $key 缓存名称
     * @return mixed
     */
    public function get($key)
    {
        $fileName = $this->getFileName($key);
        return $this->getFileData($fileName);
    }
    /**
     * 设置缓存
     * @param $key  缓存名称
     * @param $value    缓存值
     * @param $expire   有效时间
     * @return mixed
     */
    public function set($key, $value, $expire = 0)
    {
        $fileName = $this->getFileName($key);
        if (is_file($fileName)) {
            unlink($fileName);
        }
        $data = ['data' => $value, 'expire' => $expire];
        if (file_put_contents($fileName, json_encode($data))) {
            return true;
        }
        return false;
    }
    /**
     * 是否存在某个缓存
     * @param $key  缓存名称
     * @return mixed
     */
    public function isHave($key)
    {
        if (! is_null($this->get($key))) {
            return true;
        }
        return false;
    }
    /**
     * 删除缓存
     * @param $key  缓存名称
     * @return mixed
     */
    public function delete($key)
    {
        $fileName = $this->getFileName($key);
        if (is_file($fileName)) {
            unlink($fileName);
            return true;
        }
        return false;
    }
    /**
     * 清空所有缓存
     * @return mixed
     */
    public function flush()
    {
        $list = glob($this->filePath . '*');
        foreach ($list as $file) {
            unlink($file);
        }
        return true;
    }
    /**
     * 获得文件名称
     * @param $key
     * @return string
     */
    private function getFileName($key)
    {
        return $this->filePath . md5($key);
    }
    /**
     * 获得文件内容
     * @param $fileName
     */
    private function getFileData($fileName)
    {
        if (! is_file($fileName)) {
            return null;
        }
        $createTime = filectime($fileName);
        $data = json_decode(file_get_contents($fileName), true);
        //判断是否过期
        if ($data['expire'] != '0' && ($data['expire'] + $createTime) < time()) {
            unlink($fileName);
            return null;
        }
        return $data['data'];
    }

}


<?php
/*
 * WellCommerce Open-Source E-Commerce Platform
 *
 * This file is part of the WellCommerce package.
 *
 * (c) Adam Piotrowski <adam@wellcommerce.org>
 *
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed with this source code.
 */

namespace WellCommerce\Bundle\ProductBundle\DataSet\Front;

use Doctrine\ORM\Query\Expr;
use Doctrine\ORM\QueryBuilder;
use WellCommerce\Bundle\CategoryBundle\Entity\Category;
use WellCommerce\Bundle\CoreBundle\DataSet\AbstractDataSet;
use WellCommerce\Bundle\CurrencyBundle\Entity\CurrencyRate;
use WellCommerce\Bundle\ProducerBundle\Entity\Producer;
use WellCommerce\Bundle\ProducerBundle\Entity\ProducerTranslation;
use WellCommerce\Bundle\ProductBundle\Entity\Product;
use WellCommerce\Bundle\ProductBundle\Entity\ProductTranslation;
use WellCommerce\Component\DataSet\Cache\CacheOptions;
use WellCommerce\Component\DataSet\Configurator\DataSetConfiguratorInterface;

/**
 * Class ProductDataSet
 *
 * @author Adam Piotrowski <adam@wellcommerce.org>
 */
class ProductDataSet extends AbstractDataSet
{
    /**
     * {@inheritdoc}
     */
    public function configureOptions(DataSetConfiguratorInterface $configurator)
    {
        $configurator->setColumns([
            'id'                 => 'product.id',
            'sku'                => 'product.sku',
            'enabled'            => 'product.enabled',
            'name'               => 'product_translation.name',
            'shortDescription'   => 'product_translation.shortDescription',
            'description'        => 'product_translation.description',
            'route'              => 'IDENTITY(product_translation.route)',
            'weight'             => 'product.weight',
            'netPrice'           => 'product.sellPrice.netAmount',
            'price'              => 'product.sellPrice.grossAmount',
            'discountedPrice'    => 'product.sellPrice.discountedGrossAmount',
            'discountedNetPrice' => 'product.sellPrice.discountedNetAmount',
            'isDiscountValid'    => 'IF_ELSE(:date BETWEEN IF_NULL(product.sellPrice.validFrom, :date) AND IF_NULL(product.sellPrice.validTo, :date) AND product.sellPrice.discountedGrossAmount > 0, 1, 0)',
            'finalPrice'         => 'IF_ELSE(:date BETWEEN IF_NULL(product.sellPrice.validFrom, :date) AND IF_NULL(product.sellPrice.validTo, :date) AND product.sellPrice.discountedGrossAmount > 0, product.sellPrice.discountedGrossAmount, product.sellPrice.grossAmount) * currency_rate.exchangeRate',
            'currency'           => 'product.sellPrice.currency',
            'tax'                => 'sell_tax.value',
            'stock'              => 'product.stock',
            'producerId'         => 'IDENTITY(product.producer)',
            'producerName'       => 'producers_translation.name',
            'category'           => 'categories.id',
            'filteredCategory'   => 'filtered_categories.id',
            'categoryName'       => 'categories_translation.name',
            'categoryRoute'      => 'IDENTITY(categories_translation.route)',
            'shop'               => 'product_shops.id',
            'photo'              => 'photos.path',
            'status'             => 'IDENTITY(distinction.status)',
            'variantOption'      => 'IDENTITY(variant_option.attributeValue)',
            'distinctions'       => 'product.id',
            'hierarchy'          => 'product.hierarchy',
            'isStatusValid'      => 'IF_ELSE(:date BETWEEN IF_NULL(distinction.validFrom, :date) AND IF_NULL(distinction.validTo, :date), 1, 0)',
        ]);

        $configurator->setColumnTransformers([
            'route'         => $this->manager->createTransformer('route'),
            'categoryRoute' => $this->manager->createTransformer('route'),
            'distinctions'  => $this->manager->createTransformer('distinctions'),
        ]);

        $configurator->setCacheOptions(new CacheOptions(true, 3600, [
            Product::class,
            ProductTranslation::class,
            Producer::class,
            ProducerTranslation::class,
            Category::class,
        ]));
    }

    protected function createQueryBuilder(): QueryBuilder
    {
        $queryBuilder = $this->repository->getQueryBuilder();
        $queryBuilder->groupBy('product.id');
        $queryBuilder->leftJoin('product.translations', 'product_translation');
        $queryBuilder->leftJoin('product.categories', 'categories');
        $queryBuilder->leftJoin('product.categories', 'filtered_categories');
        $queryBuilder->leftJoin('product.producer', 'producers');
        $queryBuilder->leftJoin('product.sellPriceTax', 'sell_tax');
        $queryBuilder->leftJoin('categories.translations', 'categories_translation');
        $queryBuilder->leftJoin('producers.translations', 'producers_translation');
        $queryBuilder->leftJoin('product.productPhotos', 'gallery', Expr\Join::WITH, 'gallery.mainPhoto = :mainPhoto');
        $queryBuilder->leftJoin('gallery.photo', 'photos');
        $queryBuilder->leftJoin('product.distinctions', 'distinction', Expr\Join::WITH, 'distinction.status = :status');
        $queryBuilder->leftJoin('product.shops', 'product_shops');
        $queryBuilder->leftJoin('product.variants', 'variant', Expr\Join::WITH, 'variant.enabled = :variantEnabled');
        $queryBuilder->leftJoin('variant.options', 'variant_option');
        $queryBuilder->leftJoin(
            CurrencyRate::class,
            'currency_rate',
            Expr\Join::WITH,
            'currency_rate.currencyFrom = product.sellPrice.currency AND currency_rate.currencyTo = :targetCurrency'
        );
        $queryBuilder->where($queryBuilder->expr()->eq('product_shops.id', $this->getShopStorage()->getCurrentShopIdentifier()));
        $queryBuilder->andWhere($queryBuilder->expr()->eq('product.enabled', true));
        $queryBuilder->setParameter('mainPhoto', 1);
        $queryBuilder->setParameter('status', 0);
        $queryBuilder->setParameter('variantEnabled', 1);
        $queryBuilder->setParameter('targetCurrency', $this->getRequestHelper()->getCurrentCurrency());
        $queryBuilder->setParameter('date', (new \DateTime())->setTime(0, 0, 1));

        return $queryBuilder;
    }
}