<?php

namespace Reaction\Db;

/**
 * SchemaBuilderTrait contains shortcut methods to create instances of [[ColumnSchemaBuilder]].
 *
 * These can be used in database migrations to define database schema types using a PHP interface.
 * This is useful to define a schema in a DBMS independent way so that the application may run on
 * different DBMS the same way.
 *
 * For example you may use the following code inside your migration files:
 *
 * ```php
 * $this->createTable('example_table', [
 *   'id' => $this->primaryKey(),
 *   'name' => $this->string(64)->notNull(),
 *   'type' => $this->integer()->notNull()->defaultValue(10),
 *   'description' => $this->text(),
 *   'rule_name' => $this->string(64),
 *   'data' => $this->text(),
 *   'created_at' => $this->datetime()->notNull(),
 *   'updated_at' => $this->datetime(),
 * ]);
 * ```
 */
trait SchemaBuilderTrait
{
    /**
     * @return DatabaseInterface the database connection to be used for schema building.
     */
    abstract protected function getDb();

    /**
     * Creates a primary key column.
     * @param int $length column size or precision definition.
     * This parameter will be ignored if not supported by the DBMS.
     * @return ColumnSchemaBuilder the column instance which can be further customized.
     */
    public function primaryKey($length = null)
    {
        return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_PK, $length);
    }

    /**
     * Creates a big primary key column.
     * @param int $length column size or precision definition.
     * This parameter will be ignored if not supported by the DBMS.
     * @return ColumnSchemaBuilder the column instance which can be further customized.
     */
    public function bigPrimaryKey($length = null)
    {
        return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_BIGPK, $length);
    }

    /**
     * Creates a char column.
     * @param int $length column size definition i.e. the maximum string length.
     * This parameter will be ignored if not supported by the DBMS.
     * @return ColumnSchemaBuilder the column instance which can be further customized.
     */
    public function char($length = null)
    {
        return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_CHAR, $length);
    }

    /**
     * Creates a string column.
     * @param int $length column size definition i.e. the maximum string length.
     * This parameter will be ignored if not supported by the DBMS.
     * @return ColumnSchemaBuilder the column instance which can be further customized.
     */
    public function string($length = null)
    {
        return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_STRING, $length);
    }

    /**
     * Creates a text column.
     * @return ColumnSchemaBuilder the column instance which can be further customized.
     */
    public function text()
    {
        return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_TEXT);
    }

    /**
     * Creates a tinyint column. If tinyint is not supported by the DBMS, smallint will be used.
     * @param int $length column size or precision definition.
     * This parameter will be ignored if not supported by the DBMS.
     * @return ColumnSchemaBuilder the column instance which can be further customized.
     */
    public function tinyInteger($length = null)
    {
        return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_TINYINT, $length);
    }

    /**
     * Creates a smallint column.
     * @param int $length column size or precision definition.
     * This parameter will be ignored if not supported by the DBMS.
     * @return ColumnSchemaBuilder the column instance which can be further customized.
     */
    public function smallInteger($length = null)
    {
        return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_SMALLINT, $length);
    }

    /**
     * Creates an integer column.
     * @param int $length column size or precision definition.
     * This parameter will be ignored if not supported by the DBMS.
     * @return ColumnSchemaBuilder the column instance which can be further customized.
     */
    public function integer($length = null)
    {
        return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_INTEGER, $length);
    }

    /**
     * Creates a bigint column.
     * @param int $length column size or precision definition.
     * This parameter will be ignored if not supported by the DBMS.
     * @return ColumnSchemaBuilder the column instance which can be further customized.
     */
    public function bigInteger($length = null)
    {
        return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_BIGINT, $length);
    }

    /**
     * Creates a float column.
     * @param int $precision column value precision. First parameter passed to the column type, e.g. FLOAT(precision).
     * This parameter will be ignored if not supported by the DBMS.
     * @return ColumnSchemaBuilder the column instance which can be further customized.
     */
    public function float($precision = null)
    {
        return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_FLOAT, $precision);
    }

    /**
     * Creates a double column.
     * @param int $precision column value precision. First parameter passed to the column type, e.g. DOUBLE(precision).
     * This parameter will be ignored if not supported by the DBMS.
     * @return ColumnSchemaBuilder the column instance which can be further customized.
     */
    public function double($precision = null)
    {
        return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_DOUBLE, $precision);
    }

    /**
     * Creates a decimal column.
     * @param int $precision column value precision, which is usually the total number of digits.
     * First parameter passed to the column type, e.g. DECIMAL(precision, scale).
     * This parameter will be ignored if not supported by the DBMS.
     * @param int $scale column value scale, which is usually the number of digits after the decimal point.
     * Second parameter passed to the column type, e.g. DECIMAL(precision, scale).
     * This parameter will be ignored if not supported by the DBMS.
     * @return ColumnSchemaBuilder the column instance which can be further customized.
     */
    public function decimal($precision = null, $scale = null)
    {
        $length = [];
        if ($precision !== null) {
            $length[] = $precision;
        }
        if ($scale !== null) {
            $length[] = $scale;
        }

        return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_DECIMAL, $length);
    }

    /**
     * Creates a datetime column.
     * @param int $precision column value precision. First parameter passed to the column type, e.g. DATETIME(precision).
     * This parameter will be ignored if not supported by the DBMS.
     * @return ColumnSchemaBuilder the column instance which can be further customized.
     */
    public function dateTime($precision = null)
    {
        return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_DATETIME, $precision);
    }

    /**
     * Creates a timestamp column.
     * @param int $precision column value precision. First parameter passed to the column type, e.g. TIMESTAMP(precision).
     * This parameter will be ignored if not supported by the DBMS.
     * @return ColumnSchemaBuilder the column instance which can be further customized.
     */
    public function timestamp($precision = null)
    {
        return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_TIMESTAMP, $precision);
    }

    /**
     * Creates a time column.
     * @param int $precision column value precision. First parameter passed to the column type, e.g. TIME(precision).
     * This parameter will be ignored if not supported by the DBMS.
     * @return ColumnSchemaBuilder the column instance which can be further customized.
     */
    public function time($precision = null)
    {
        return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_TIME, $precision);
    }

    /**
     * Creates a date column.
     * @return ColumnSchemaBuilder the column instance which can be further customized.
     */
    public function date()
    {
        return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_DATE);
    }

    /**
     * Creates a binary column.
     * @param int $length column size or precision definition.
     * This parameter will be ignored if not supported by the DBMS.
     * @return ColumnSchemaBuilder the column instance which can be further customized.
     */
    public function binary($length = null)
    {
        return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_BINARY, $length);
    }

    /**
     * Creates a boolean column.
     * @return ColumnSchemaBuilder the column instance which can be further customized.
     */
    public function boolean()
    {
        return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_BOOLEAN);
    }

    /**
     * Creates a money column.
     * @param int $precision column value precision, which is usually the total number of digits.
     * First parameter passed to the column type, e.g. DECIMAL(precision, scale).
     * This parameter will be ignored if not supported by the DBMS.
     * @param int $scale column value scale, which is usually the number of digits after the decimal point.
     * Second parameter passed to the column type, e.g. DECIMAL(precision, scale).
     * This parameter will be ignored if not supported by the DBMS.
     * @return ColumnSchemaBuilder the column instance which can be further customized.
     */
    public function money($precision = null, $scale = null)
    {
        $length = [];
        if ($precision !== null) {
            $length[] = $precision;
        }
        if ($scale !== null) {
            $length[] = $scale;
        }

        return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_MONEY, $length);
    }

    /**
     * Creates a JSON column.
     * @return ColumnSchemaBuilder the column instance which can be further customized.
     * @throws \Reaction\Exceptions\Exception
     */
    public function json()
    {
        /*
         * TODO Remove in Yii 2.1
         *
         * Disabled due to bug in MySQL extension
         * @link https://bugs.php.net/bug.php?id=70384
         */
        if (version_compare(PHP_VERSION, '5.6', '<') && $this->getDb()->getDriverName() === 'mysql') {
            throw new \Reaction\Exceptions\Exception('JSON column type is not supported in PHP < 5.6');
        }

        return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_JSON);
    }
}


<?php

/**
 * This file is part of RawContainer library.
 *
 * Copyright (c) 2014 Tom Kaczocha
 *
 * This Source Code is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, you can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * PHP version 5.4
 *
 * @category  PHP
 * @package   RawPHP\RawContainer
 * @author    Taylor Otwell <taylorotwell@gmail.com>
 * @author    Tom Kaczocha <tom@crazydev.org>
 * @copyright 2014 Tom Kaczocha
 * @license   http://rawphp.org/licenses/mpl.txt MPL
 * @link      http://rawphp.org/
 */

namespace RawPHP\RawContainer;

use ArrayAccess;
use Closure;
use Exception;
use InvalidArgumentException;
use RawPHP\RawContainer\Contract\IBindingsBuilder;
use RawPHP\RawContainer\Contract\IContainer;
use RawPHP\RawContainer\Exception\BindingResolutionException;
use RawPHP\RawSupport\Util;
use ReflectionClass;
use ReflectionFunction;
use ReflectionMethod;
use ReflectionParameter;

/**
 * Class Container
 *
 * @package RawPHP\RawContainer
 */
class Container implements ArrayAccess, IContainer
{
    /** @var static */
    protected static $instance;
    /** @var array */
    protected $resolved = [ ];
    /** @var array */
    protected $bindings = [ ];
    /** @var array */
    protected $instances = [ ];
    /** @var array */
    protected $aliases = [ ];
    /** @var array */
    protected $buildStack = [ ];
    /** @var array */
    protected $contextual = [ ];
    /** @var array */
    protected $reboundCallbacks = [ ];
    /** @var array */
    protected $resolvingCallbacks = [ ];
    /** @var array */
    protected $globalResolvingCallbacks = [ ];
    /** @var array */
    protected $globalAfterResolvingCallbacks = [ ];

    /**
     * Define a contextual binding.
     *
     * @param  string $concrete
     *
     * @return IBindingsBuilder
     */
    public function when( $concrete )
    {
        return new BindingsBuilder( $this, $concrete );
    }

    /**
     * Determine if the given type has been bound.
     *
     * @param  string $abstract
     *
     * @return bool
     */
    public function bound( $abstract )
    {
        return isset( $this->bindings[ $abstract ] ) || isset( $this->instances[ $abstract ] );
    }

    /**
     * Determine if the given type has been resolved.
     *
     * @param  string $abstract
     *
     * @return bool
     */
    public function resolved( $abstract )
    {
        return isset( $this->resolved[ $abstract ] ) || isset( $this->instances[ $abstract ] );
    }

    /**
     * Determine if a given string is an alias.
     *
     * @param  string $name
     *
     * @return bool
     */
    public function isAlias( $name )
    {
        return isset( $this->aliases[ $name ] );
    }

    /**
     * Register a binding with the container.
     *
     * @param  string|array        $abstract
     * @param  Closure|string|null $concrete
     * @param  bool                $shared
     *
     * @return IContainer
     */
    public function bind( $abstract, $concrete = NULL, $shared = FALSE )
    {
        if ( is_array( $abstract ) )
        {
            list( $abstract, $alias ) = $this->extractAlias( $abstract );

            $this->alias( $abstract, $alias );
        }

        $this->dropStaleInstances( $abstract );

        if ( is_null( $concrete ) )
        {
            $concrete = $abstract;
        }

        if ( !$concrete instanceof Closure )
        {
            $concrete = $this->getClosure( $abstract, $concrete );
        }

        $this->bindings[ $abstract ] = compact( 'concrete', 'shared' );

        if ( $this->resolved( $abstract ) )
        {
            $this->rebound( $abstract );
        }

        return $this;
    }

    /**
     * Add a contextual binding to the container.
     *
     * @param  string         $concrete
     * @param  string         $abstract
     * @param  Closure|string $implementation
     *
     * @return IContainer
     */
    public function addContextualBindings( $concrete, $abstract, $implementation )
    {
        $this->contextual[ $concrete ][ $abstract ] = $implementation;

        return $this;
    }

    /**
     * Register a binding if it hasn't already been registered.
     *
     * @param  string              $abstract
     * @param  Closure|string|null $concrete
     * @param  bool                $shared
     *
     * @return IContainer
     */
    public function bindIf( $abstract, $concrete = NULL, $shared = FALSE )
    {
        if ( !$this->bound( $abstract ) )
        {
            $this->bind( $abstract, $concrete, $shared );
        }

        return $this;
    }

    /**
     * Register a shared binding in the container.
     *
     * @param  string              $abstract
     * @param  Closure|string|null $concrete
     *
     * @return IContainer
     */
    public function singleton( $abstract, $concrete = NULL )
    {
        $this->bind( $abstract, $concrete, TRUE );

        return $this;
    }

    /**
     * Wrap a Closure such that it is shared.
     *
     * @param  Closure $closure
     *
     * @return Closure
     */
    public function share( Closure $closure )
    {
        return function ( $container ) use ( $closure )
        {
            static $object;

            if ( is_null( $object ) )
            {
                $object = $closure( $container );
            }

            return $object;
        };
    }

    /**
     * Bind a shared Closure into the container.
     *
     * @param  string  $abstract
     * @param  Closure $closure
     *
     * @return IContainer
     */
    public function bindShared( $abstract, Closure $closure )
    {
        $this->bind( $abstract, $this->share( $closure ), TRUE );

        return $this;
    }

    /**
     * "Extend" an type in the container.
     *
     * @param  string  $abstract
     * @param  Closure $closure
     *
     * @return IContainer
     *
     * @throws InvalidArgumentException
     */
    public function extend( $abstract, Closure $closure )
    {
        if ( !isset( $this->bindings[ $abstract ] ) )
        {
            throw new InvalidArgumentException( sprintf( 'Type %s is not bound', $abstract ) );
        }

        if ( isset( $this->instances[ $abstract ] ) )
        {
            $this->instances[ $abstract ] = $closure( $this->instances[ $abstract ], $this );

            $this->rebound( $abstract );
        }
        else
        {
            $extender = $this->getExtender( $abstract, $closure );

            $this->bind( $abstract, $extender, $this->isShared( $abstract ) );
        }

        return $this;
    }

    /**
     * Register an existing instance as shared in the container.
     *
     * @param  string $abstract
     * @param  mixed  $instance
     *
     * @return IContainer
     */
    public function instance( $abstract, $instance )
    {
        if ( is_array( $abstract ) )
        {
            list( $abstract, $alias ) = $this->extractAlias( $abstract );

            $this->alias( $abstract, $alias );
        }

        unset( $this->aliases[ $abstract ] );

        $bound = $this->bound( $abstract );

        $this->instances[ $abstract ] = $instance;

        if ( $bound )
        {
            $this->rebound( $abstract );
        }

        return $this;
    }

    /**
     * Alias a type to a different name.
     *
     * @param  string $class
     * @param  string $alias
     *
     * @return IContainer
     */
    public function alias( $class, $alias )
    {
        $this->aliases[ $alias ] = $class;

        return $this;
    }

    /**
     * Bind a new callback to an abstract's rebind event.
     *
     * @param  string  $abstract
     * @param  Closure $callback
     *
     * @return mixed
     */
    public function rebinding( $abstract, Closure $callback )
    {
        $this->reboundCallbacks[ $abstract ][ ] = $callback;

        if ( $this->bound( $abstract ) )
        {
            return $this->make( $abstract );
        }

        return $this;
    }

    /**
     * Refresh an instance on the given target and method.
     *
     * @param  string $abstract
     * @param  mixed  $target
     * @param  string $method
     *
     * @return mixed
     */
    public function refresh( $abstract, $target, $method )
    {
        return $this->rebinding( $abstract, function ( $app, $instance ) use ( $target, $method )
        {
            $target->{$method}( $instance );
        }
        );
    }

    /**
     * Call the given Closure / class@method and inject its dependencies.
     *
     * @param  callable|string $callback
     * @param  array           $parameters
     * @param  string|null     $defaultMethod
     *
     * @return mixed
     */
    public function call( $callback, array $parameters = [ ], $defaultMethod = NULL )
    {
        if ( is_string( $callback ) )
        {
            return $this->callClass( $callback, $parameters, $defaultMethod );
        }

        $dependencies = $this->getMethodDependencies( $callback, $parameters );

        return call_user_func_array( $callback, $dependencies );
    }

    /**
     * Resolve the given type from the container.
     *
     * @param  string $abstract
     * @param  array  $parameters
     *
     * @return mixed
     */
    public function make( $abstract, $parameters = [ ] )
    {
        $abstract = $this->getAlias( $abstract );

        if ( isset( $this->instances[ $abstract ] ) )
        {
            return $this->instances[ $abstract ];
        }

        $concrete = $this->getConcrete( $abstract );

        if ( $this->isBuildable( $concrete, $abstract ) )
        {
            $object = $this->build( $concrete, $parameters );
        }
        else
        {
            $object = $this->make( $concrete, $parameters );
        }

        if ( $this->isShared( $abstract ) )
        {
            $this->instances[ $abstract ] = $object;
        }

        $this->fireResolvingCallbacks( $abstract, $object );

        $this->resolved[ $abstract ] = TRUE;

        return $object;
    }

    /**
     * Instantiate a concrete instance of the given type.
     *
     * @param  string $concrete
     * @param  array  $parameters
     *
     * @return mixed
     *
     * @throws BindingResolutionException
     */
    public function build( $concrete, $parameters = [ ] )
    {
        if ( $concrete instanceof Closure )
        {
            return $concrete( $this, $parameters );
        }

        $reflector = new ReflectionClass( $concrete );

        if ( !$reflector->isInstantiable() )
        {
            throw new BindingResolutionException( sprintf( 'Target %s is not instantiable.', $concrete ) );
        }

        $this->buildStack[ ] = $concrete;

        $constructor = $reflector->getConstructor();

        if ( is_null( $constructor ) )
        {
            array_pop( $this->buildStack );

            return new $concrete;
        }

        $dependencies = $constructor->getParameters();

        $parameters = $this->keyParametersByArgument( $dependencies, $parameters );

        $instances = $this->getDependencies( $dependencies, $parameters );

        array_pop( $this->buildStack );

        return $reflector->newInstance( $instances );
    }

    /**
     * Register a new resolving callback.
     *
     * @param  string  $abstract
     * @param  Closure $callback
     *
     * @return IContainer
     */
    public function resolving( $abstract, Closure $callback )
    {
        $this->resolvingCallbacks[ $abstract ][ ] = $callback;

        return $this;
    }

    /**
     * Register a new resolving callback for all types.
     *
     * @param  Closure $callback
     *
     * @return IContainer
     */
    public function resolvingAny( Closure $callback )
    {
        $this->globalResolvingCallbacks[ ] = $callback;

        return $this;
    }

    /**
     * Determine if a given type is shared.
     *
     * @param  string $abstract
     *
     * @return bool
     */
    public function isShared( $abstract )
    {
        if ( isset( $this->bindings[ $abstract ][ 'shared' ] ) )
        {
            $shared = $this->bindings[ $abstract ][ 'shared' ];
        }
        else
        {
            $shared = FALSE;
        }

        return isset( $this->instances[ $abstract ] ) || TRUE === $shared;
    }

    /**
     * Get the container's bindings.
     *
     * @return array
     */
    public function getBindings()
    {
        return $this->bindings;
    }

    /**
     * Remove a resolved instance from the instance cache.
     *
     * @param  string $abstract
     *
     * @return IContainer
     */
    public function forgetInstance( $abstract )
    {
        unset( $this->instances[ $abstract ] );

        return $this;
    }

    /**
     * Clear all of the instances from the container.
     */
    public function forgetInstances()
    {
        $this->instances = [ ];

        return $this;
    }

    /**
     * Flush the container of all bindings and resolved instances.
     */
    public function flush()
    {
        $this->aliases   = [ ];
        $this->resolved  = [ ];
        $this->bindings  = [ ];
        $this->instances = [ ];
    }

    /**
     * Determine if a given offset exists.
     *
     * @param  string $key
     *
     * @return bool
     */
    public function offsetExists( $key )
    {
        return isset( $this->bindings[ $key ] );
    }

    /**
     * Get the value at a given offset.
     *
     * @param  string $key
     *
     * @return mixed
     */
    public function offsetGet( $key )
    {
        return $this->make( $key );
    }

    /**
     * Set the value at a given offset.
     *
     * @param  string $key
     * @param  mixed  $value
     *
     * @return IContainer
     */
    public function offsetSet( $key, $value )
    {
        if ( !$value instanceof Closure )
        {
            $value = function () use ( $value )
            {
                return $value;
            };
        }

        $this->bind( $key, $value );

        return $this;
    }

    /**
     * Unset the value at a given offset.
     *
     * @param  string $key
     *
     * @return IContainer
     */
    public function offsetUnset( $key )
    {
        unset( $this->bindings[ $key ], $this->instances[ $key ] );
    }

    /**
     * Set the globally available instance of the container.
     *
     * @return static
     */
    public static function getInstance()
    {
        return static::$instance;
    }

    /**
     * Set the shared instance of the container.
     *
     * @param  IContainer $container
     *
     * @return IContainer
     */
    public static function setInstance( IContainer $container )
    {
        static::$instance = $container;
    }

    /**
     * Extract the type and alias from a given definition.
     *
     * @param array $definition
     *
     * @return array
     */
    protected function extractAlias( array $definition )
    {
        return [ key( $definition ), current( $definition ) ];
    }

    /**
     * Drop all of the stale instances and aliases.
     *
     * @param $abstract
     */
    protected function dropStaleInstances( $abstract )
    {
        unset( $this->instances[ $abstract ], $this->aliases[ $abstract ] );
    }

    /**
     * Get a Closure to be used when building a type.
     *
     * @param string $abstract
     * @param string $concrete
     *
     * @return Closure
     */
    protected function getClosure( $abstract, $concrete )
    {
        return function ( $c, $parameters = [ ] ) use ( $abstract, $concrete )
        {
            $method = ( $abstract == $concrete ) ? 'build' : 'make';

            return $c->$method( $concrete, $parameters );
        };
    }

    /**
     * Fire the 'rebound' callbacks for the given abstract type.
     *
     * @param string $abstract
     */
    protected function rebound( $abstract )
    {
        $instance = $this->make( $abstract );

        foreach ( $this->getReboundCallbacks( $abstract ) as $callback )
        {
            call_user_func( $callback, $this, $instance );
        }
    }

    /**
     * Get the rebound callbacks for a given type.
     *
     * @param string $abstract
     *
     * @return array
     */
    protected function getReboundCallbacks( $abstract )
    {
        if ( isset( $this->reboundCallbacks[ $abstract ] ) )
        {
            return $this->reboundCallbacks[ $abstract ];
        }

        return [ ];
    }

    /**
     * Get an extender Closure for resolving a type.
     *
     * @param string   $abstract
     * @param callable $closure
     *
     * @return Closure
     */
    protected function getExtender( $abstract, Closure $closure )
    {
        $resolver = $this->bindings[ $abstract ][ 'concrete' ];

        return function ( $container ) use ( $resolver, $closure )
        {
            return $closure( $resolver( $container ), $container );
        };
    }

    /**
     * Call a string reference to a class using Class@method syntax.
     *
     * @param string $target
     * @param array  $parameters
     * @param string $defaultMethod
     *
     * @return mixed
     */
    protected function callClass( $target, array $parameters = [ ], $defaultMethod = NULL )
    {
        $segments = explode( '@', $target );

        $method = count( $segments ) === 2 ? $segments[ 1 ] : $defaultMethod;

        if ( is_null( $method ) )
        {
            throw new InvalidArgumentException( 'Method not provided.' );
        }

        return $this->call( [ $this->make( $segments[ 0 ] ), $method ], $parameters );
    }

    /**
     * Get all dependencies for a given call method.
     *
     * @param mixed $callback
     * @param array $parameters
     *
     * @return array
     */
    protected function getMethodDependencies( $callback, $parameters = [ ] )
    {
        $dependencies = [ ];

        foreach ( $this->getCallReflector( $callback )->getParameters() as $key => $parameter )
        {
            $this->addDependencyForCallParameter( $parameter, $parameters, $dependencies );
        }

        return array_merge( $dependencies, $parameters );
    }

    /**
     * Get the proper reflection instance for the given callback.
     *
     * @param mixed $callback
     *
     * @return ReflectionFunction|ReflectionMethod
     */
    protected function getCallReflector( $callback )
    {
        if ( is_array( $callback ) )
        {
            return new ReflectionMethod( $callback[ 0 ], $callback[ 1 ] );
        }

        return new ReflectionFunction( $callback );
    }

    /**
     * Get the dependency for the given call parameter.
     *
     * @param ReflectionParameter $parameter
     * @param array               $parameters
     * @param array               $dependencies
     */
    protected function addDependencyForCallParameter( ReflectionParameter $parameter, array &$parameters, array &$dependencies )
    {
        if ( array_key_exists( $parameter->name, $parameters ) )
        {
            $dependencies[ ] = $parameters[ $parameter->name ];
        }
        elseif ( $parameter->getClass() )
        {
            $dependencies[ ] = $this->make( $parameter->getClass()->name );
        }
        elseif ( $parameter->isDefaultValueAvailable() )
        {
            $dependencies[ ] = $parameter->getDefaultValue();
        }
    }

    /**
     * Get the alias for an abstract if available.
     *
     * @param string $abstract
     *
     * @return string
     */
    protected function getAlias( $abstract )
    {
        return isset( $this->aliases[ $abstract ] ) ? $this->aliases[ $abstract ] : $abstract;
    }

    /**
     * Get the concrete type for a given abstract.
     *
     * @param $abstract
     *
     * @return string
     */
    protected function getConcrete( $abstract )
    {
        if ( !is_null( $concrete = $this->getContextualConcrete( $abstract ) ) )
        {
            return $concrete;
        }

        if ( !isset( $this->bindings[ $abstract ] ) )
        {
            if ( $this->missingLeadingSlash( $abstract ) && isset( $this->bindings[ '\\' . $abstract ] ) )
            {
                $abstract = '\\' . $abstract;
            }

            return $abstract;
        }

        return $this->bindings[ $abstract ][ 'concrete' ];
    }

    /**
     * Get the contextual concrete binding for the given abstract.
     *
     * @param string $abstract
     *
     * @return string
     */
    public function getContextualConcrete( $abstract )
    {
        if ( isset( $this->contextual[ Util::last( $this->buildStack ) ][ $abstract ] ) )
        {
            return $this->contextual[ Util::last( $this->buildStack ) ][ $abstract ];
        }

        return NULL;
    }

    /**
     * Determine if the given abstract has a leading slash.
     *
     * @param string $abstract
     *
     * @return bool
     */
    protected function missingLeadingSlash( $abstract )
    {
        return is_string( $abstract ) && strpos( $abstract, '\\' ) !== 0;
    }

    /**
     * Determine if the given concrete is buildable.
     *
     * @param mixed  $concrete
     * @param string $abstract
     *
     * @return bool
     */
    protected function isBuildable( $concrete, $abstract )
    {
        return $concrete === $abstract || $concrete instanceof Closure;
    }

    /**
     * Fire all of the resolving callbacks.
     *
     * @param string $abstract
     * @param mixed  $object
     */
    protected function fireResolvingCallbacks( $abstract, $object )
    {
        if ( isset( $this->resolvingCallbacks[ $abstract ] ) )
        {
            $this->fireCallbackArray( $object, $this->resolvingCallbacks[ $abstract ] );
        }

        $this->fireCallbackArray( $object, $this->globalResolvingCallbacks );

        $this->fireCallbackArray( $object, $this->globalAfterResolvingCallbacks );
    }

    /**
     * Fire an array of callbacks with an object.
     *
     * @param mixed $object
     * @param array $callbacks
     */
    protected function fireCallbackArray( $object, array $callbacks )
    {
        foreach ( $callbacks as $callback )
        {
            $callback( $object, $this );
        }
    }

    /**
     * If extra parameters are passed by numeric ID, rekey them by argument name.
     *
     * @param array $dependencies
     * @param array $parameters
     *
     * @return array
     */
    protected function keyParametersByArgument( array $dependencies, array $parameters )
    {
        foreach ( $parameters as $key => $value )
        {
            unset( $parameters[ $key ] );

            $parameters[ $dependencies[ $key ]->name ] = $value;
        }

        return $parameters;
    }

    /**
     * Resolve all the dependencies from the ReflectionParameters.
     *
     * @param array $parameters
     * @param array $primitives
     *
     * @return array
     *
     * @throws BindingResolutionException
     * @throws Exception
     */
    protected function getDependencies( array $parameters, array $primitives = [ ] )
    {
        $dependencies = [ ];

        /** @var ReflectionParameter $parameter */
        foreach ( $parameters as $parameter )
        {
            $dependency = $parameter->getClass();

            if ( array_key_exists( $parameter->name, $primitives ) )
            {
                $dependencies[ ] = $primitives[ $parameter->name ];
            }
            elseif ( is_null( $dependency ) )
            {
                $dependencies[ ] = $this->resolveNonClass( $parameter );
            }
            else
            {
                $dependencies[ ] = $this->resolveClass( $parameter );
            }
        }

        return ( array ) $dependencies;
    }

    /**
     * Resolve a non-class hinted dependency.
     *
     * @param ReflectionParameter $parameter
     *
     * @return mixed
     *
     * @throws BindingResolutionException
     */
    protected function resolveNonClass( ReflectionParameter $parameter )
    {
        if ( $parameter->isDefaultValueAvailable() )
        {
            return $parameter->getDefaultValue();
        }

        throw new BindingResolutionException( sprintf( 'Unresolvable dependency resolving %s in class %s.',
                                                       $parameter->name, $parameter->getDeclaringClass()->name
                                              )
        );
    }

    /**
     * Resolve a class based dependency from the container.
     *
     * @param ReflectionParameter $parameter
     *
     * @return mixed
     *
     * @throws BindingResolutionException
     * @throws Exception
     */
    protected function resolveClass( ReflectionParameter $parameter )
    {
        try
        {
            return $this->make( $parameter->getClass()->name );
        }
        catch ( BindingResolutionException $e )
        {
            if ( $parameter->isOptional() )
            {
                return $parameter->getDefaultValue();
            }

            throw $e;
        }
    }
}


<?php

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

namespace Valkyrja\Http\Middleware;

use Valkyrja\Application;
use Valkyrja\Http\Request;
use Valkyrja\Http\Response;

/**
 * Trait MiddlewareAwareTrait.
 *
 * @author Melech Mizrachi
 */
trait MiddlewareAwareTrait
{
    /**
     * The collection of middleware.
     *
     * @var string[]
     */
    protected static $middleware = [];

    /**
     * The collection of middleware groups.
     *
     * @var array[]
     */
    protected static $middlewareGroups = [];

    /**
     * Determine if a middleware is a group of middleware.
     *
     * @param string $middleware The middleware to check
     *
     * @return bool
     */
    public function isMiddlewareGroup(string $middleware): bool
    {
        return isset(self::$middlewareGroups[$middleware]);
    }

    /**
     * Get a middleware group.
     *
     * @param string $middleware The middleware group
     *
     * @return string[]
     */
    public function getMiddlewareGroup(string $middleware): array
    {
        return self::$middlewareGroups[$middleware];
    }

    /**
     * Dispatch middleware.
     *
     * @param Request $request    The request
     * @param array   $middleware [optional] The middleware to dispatch
     *
     * @return mixed
     */
    public function requestMiddleware(Request $request, array $middleware = null)
    {
        // Set the middleware to any middleware passed or the base middleware
        $middleware = $middleware ?? self::$middleware;

        $modifiedRequest = $request;

        // Get the application
        $app = $this->getApplication();

        // Iterate through the middleware
        foreach ($middleware as $item) {
            // If the middleware is a group
            if ($this->isMiddlewareGroup($item)) {
                // Recurse into that middleware group
                $this->requestMiddleware(
                    $request,
                    $this->getMiddlewareGroup($item)
                );

                continue;
            }

            /* @var \Valkyrja\Http\Middleware\Middleware $item */
            $modifiedRequest = $item::before($request);

            if ($modifiedRequest instanceof Response) {
                return $modifiedRequest;
            }

            // Set the returned request in the container
            $app->container()->singleton(Request::class, $modifiedRequest);
        }

        return $modifiedRequest;
    }

    /**
     * Dispatch after request processed middleware.
     *
     * @param Request  $request    The request
     * @param Response $response   The response
     * @param array    $middleware [optional] The middleware to dispatch
     *
     * @return mixed
     */
    public function responseMiddleware(Request $request, Response $response, array $middleware = null)
    {
        // Set the middleware to any middleware passed or the base middleware
        $middleware = $middleware ?? self::$middleware;

        // Get the application
        $app = $this->getApplication();

        // Iterate through the middleware
        foreach ($middleware as $item) {
            // If the middleware is a group
            if ($this->isMiddlewareGroup($item)) {
                // Recurse into that middleware group
                $this->responseMiddleware(
                    $request,
                    $response,
                    $this->getMiddlewareGroup($item)
                );

                continue;
            }

            /* @var \Valkyrja\Http\Middleware\Middleware $item */
            $response = $item::after($request, $response);

            // Set the returned response in the container
            $app->container()->singleton(Response::class, $response);
        }

        return $response;
    }

    /**
     * Dispatch terminable middleware.
     *
     * @param Request  $request    The request
     * @param Response $response   The response
     * @param array    $middleware [optional] The middleware to dispatch
     *
     * @return void
     */
    public function terminableMiddleware(Request $request, Response $response, array $middleware = null): void
    {
        // Set the middleware to any middleware passed or the base middleware
        $middleware = $middleware ?? self::$middleware;

        // Iterate through the middleware
        foreach ($middleware as $item) {
            // If the middleware is a group
            if ($this->isMiddlewareGroup($item)) {
                // Recurse into that middleware group
                $this->terminableMiddleware(
                    $request,
                    $response,
                    $this->getMiddlewareGroup($item)
                );

                continue;
            }

            /* @var \Valkyrja\Http\Middleware\Middleware $item */
            $item::terminate($request, $response);
        }
    }

    /**
     * Get the application.
     *
     * @return \Valkyrja\Application
     */
    abstract protected function getApplication(): Application;
}


<?php
/**
* @package     jelix-modules
* @subpackage  jelix
* @author      Sylvain de Vathaire
* @contributor Laurent Jouanneau
* @copyright   2008 Sylvain de Vathaire, 2012 Laurent Jouanneau
* @licence     http://www.gnu.org/licenses/gpl.html GNU General Public Licence, see LICENCE file
*/

/**
 * @package    jelix-modules
 * @subpackage jelix
 */
class WSDLCtrl extends jController {

   /**
    * Display the web service documentation for the requested service
    */
    public function index() {
        $rep = $this->getResponse('html', true);

        $webservices = jWSDL::getSoapControllers();

        if(sizeof($webservices) != 0){
            $service = $this->param('service');

            if (empty($service)) {
                $module = $webservices[0]['module'];
                $controller = $webservices[0]['class'];
            }else{
                if(!strpos($service, '~')===FALSE){
                    list($module, $controller) =  explode('~',$service);
                }
                if (empty($module) || empty($controller)) {
                    throw new JException("jsoap~errors.service.param.invalid");
                }
            }

            //Used for documentation of data structures classes
            $className = $this->param('className');

            $wsdl = new jWSDL($module, $controller);
            $doc = $wsdl->doc($className);
            $doc['menu'] = $webservices;
            $rep->body->assign("doc", $doc);
            $rep->title = "Documentation - ".$controller;
        }else{
            $rep->title = "Documentation -  Web services";
        }
        $rep->bodyTpl = 'jsoap~soap_doc';
        return $rep;
    }

    /**
    * Return the WSDL file for a soap web service
    */
    public function wsdl() {

        $rep = $this->getResponse('xml');
        $rep->sendXMLHeader = FALSE;

        $service = $this->param('service');

        if (empty($service)) {
            throw new jException("jsoap~errors.service.param.required");
        }

        if(!strpos($service, '~')===FALSE){
            list($module, $controller) =  explode('~',$service);
        }
        if (empty($module) || empty($controller)) {
            throw new jException("jsoap~errors.service.param.invalid");
        }

        $wsdl = new jWSDL($module, $controller);
        $rep->content = $wsdl->getWSDLFile();

        return $rep;
    }
}
?>


<?php

namespace mmxca\LoggingHelper;

/**
 * Description of LoggingHelper
 *
 * @author David Hoffman
 */
class LoggingHelper {

    /**
     * @var string, Log Directory Name
     */
    private $path = '/tmp/logs/';

    /**
     * @void, Default Constructor, Sets the timezone and path of the log files.
     */
    public function __construct() {
        date_default_timezone_set('America/New_York');
        $this->path = dirname(__FILE__) . $this->path;
    }

    /**
     *  @void
     * 	Creates the log
     *
     *  @param string $message the message which is written into the log.
     *
     *  @description:
     * 	1. Checks if directory exists, if not, create one and call this method again.
     * 	2. Checks if log already exists.
     * 	3. If not, new log gets created. Log is written into the logs folder.
     * 	4. Logname is current date(Year - Month - Day).
     * 	5. If log exists, edit method called.
     * 	6. Edit method modifies the current log.
     */
    public function write($message) {
        $date = new DateTime();
        $log = $this->path . $date->format('Y-m-d') . ".txt";

        if (is_dir($this->path)) {
            if (!file_exists($log)) {
                $fh = fopen($log, 'a+') or die("Fatal Error !");
                $logcontent = "Time : " . $date->format('H:i:s') . "\r\n" . $message . "\r\n";
                fwrite($fh, $logcontent);
                fclose($fh);
            } else {
                $this->edit($log, $date, $message);
            }
        } else {
            if (mkdir($this->path, 0777) === true) {
                $this->write($message);
            }
        }
    }

    /**
     *  @void
     *  Gets called if log already exists.
     *  Modifies current log and adds the message to the log.
     *
     *  @param string $log
     *  @param DateTimeObject $date
     *  @param string $message
     */
    private function edit($log, $date, $message) {
        $logcontent = "Time : " . $date->format('H:i:s') . "\r\n" . $message . "\r\n\r\n";
        $logcontent = $logcontent . file_get_contents($log);
        file_put_contents($log, $logcontent);
    }

}


<?php

namespace Think\Template;

use Think\BaseException;
use Think\Template;

/**
 * 标签库TagLib解析基类
 * @property-write array $tags 标签定义
 * @see \Think\Template\TagLib\Cx
 * @see \Think\Template\TagLib\Html
 */
class TagLib
{

    /**
     * @var array $tags 标签定义
     */
    protected $tags = [];

    /**
     * 标签库标签列表
     * @var array $tagList

     */
//        protected $tagList = [];

    /**
     * 标签库分析数组
     * @var array $parse

     */
//        protected $parse = [];

    /**
     * 标签库是否有效
     * @var bool $valid
     * @deprecated

     */
//        protected $valid = false;

    /**
     * 当前模板对象
     * @var \Think\Template

     */
    protected $tpl;

    protected $comparison = [
        ' nheq ' => ' !== ',
        ' heq '  => ' === ',
        ' neq '  => ' != ',
        ' eq '   => ' == ',
        ' egt '  => ' >= ',
        ' gt '   => ' > ',
        ' elt '  => ' <= ',
        ' lt '   => ' < ',
    ];

    /**

     */
    public function __construct()
    {
        $this->tpl = new Template;
    }

    /**
     * TagLib标签属性分析 返回标签属性数组
     * @access   public
     *
     * @param string $attr
     * @param string $tag
     * @return array
     * @throws BaseException
     */
    public function parseXmlAttr($attr = '', $tag = '')
    {
        //XML解析安全过滤
        $attr = str_replace('&', '___', $attr);
        $xml = '<tpl><tag '.$attr.' /></tpl>';
        $xml = \simplexml_load_string($xml);
        if (!$xml) {
            throw new BaseException(L('_XML_TAG_ERROR_').' : '.$attr);
        }
        /** @noinspection PhpUndefinedFieldInspection */
        $xml = (array)($xml->tag->attributes());
        if (isset($xml['@attributes'])) {
            $array = array_change_key_case($xml['@attributes']);
            if ($array) {
                $tag = strtolower($tag);
                if (!isset($this->tags[$tag])) {
                    // 检测是否存在别名定义
                    foreach ($this->tags as $val) {
                        if (isset($val['alias']) && in_array($tag, explode(',', $val['alias']))) {
                            $item = $val;
                            break;
                        }
                    }
                } else {
                    $item = $this->tags[$tag];
                }
                $attrs = explode(',', $item['attr']);
                if (isset($item['must'])) {
                    $must = explode(',', $item['must']);
                } else {
                    $must = [];
                }
                foreach ($attrs as $name) {
                    if (isset($array[$name])) {
                        $array[$name] = str_replace('___', '&', $array[$name]);
                    } elseif (false !== array_search($name, $must)) {
                        throw new BaseException(L('_PARAM_ERROR_').':'.$name);
                    }
                }

                return $array;
            }
        } else {
            return [];
        }
    }

    /**
     * 解析条件表达式

     *
     * @param string $condition 表达式标签内容
     *
     * @return array
     */
    public function parseCondition($condition)
    {
        $condition = str_ireplace(array_keys($this->comparison), array_values($this->comparison), $condition);
        $condition = preg_replace('/\$(\w+):(\w+)\s/is', '$\\1->\\2 ', $condition);
        return preg_replace('/\$(\w+)\.(\w+)\s/is', '$\\1["\\2"] ', $condition);
    }

    /**
     * 自动识别构建变量

     *
     * @param string $name 变量描述
     *
     * @return string
     */
    public function autoBuildVar($name)
    {
        if (strpos($name, '.')) {
            $vars = explode('.', $name);
            $var = array_shift($vars);
            $name = '$'.$var;
            foreach ($vars as $key => $val) {
                if (0 === strpos($val, '$')) {
                    $name .= '["{'.$val.'}"]';
                } else {
                    $name .= '["'.$val.'"]';
                }
            }
        } elseif (!defined($name)) {
            $name = '$'.$name;
        }

        return $name;
    }

    /**
     * 获取标签定义
     * @return array
     */
    public function getTags()
    {
        return $this->tags;
    }
}


<?php

namespace Jelix\Minify;

class MinifySetup {

    static function getConfigPaths() {
        $paths = array(
                    'base'   => __DIR__.'/config.php',
                );
        if (file_exists(\jApp::appConfigPath('minifyGroupsConfig.php'))) {
            $paths['groups'] = \jApp::appConfigPath('minifyGroupsConfig.php');
        }
        return $paths;
    }

    /**
     * set default parameters for Minify
     */
    static function initOptions() {
        global $min_allowDebugFlag;
        global $min_errorLogger;
        global $min_enableBuilder;
        global $min_cachePath;
        global $min_documentRoot;
        global $min_cacheFileLocking;
        global $min_symlinks;
        global $min_serveOptions;
        global $min_uploaderHoursBehind;
        global $min_customConfigPaths;

        if (!isset($min_allowDebugFlag))
            $min_allowDebugFlag = false;

        if (!isset($min_errorLogger)) {
            $min_errorLogger = false;
        }

        $min_enableBuilder = false;

        $min_cachePath = \jApp::tempPath('minify/');
        if (!file_exists($min_cachePath)) {
            mkdir($min_cachePath, 0775);
        }

        if (!isset($min_documentRoot)) {
            $min_documentRoot = self::getDocumentRoot();
        }

        if (!isset($min_cacheFileLocking)) {
            $min_cacheFileLocking = true;
        }

        if (!isset($min_serveOptions['bubbleCssImports'])) {
            $min_serveOptions['bubbleCssImports'] = false;
        }

        if (!isset($min_serveOptions['maxAge'])) {
            $min_serveOptions['maxAge'] = 1800;
        }

        $min_serveOptions['minApp']['groupsOnly'] = false;

        if (!isset($min_serveOptions['minApp']['maxFiles'])) {
            $min_serveOptions['minApp']['maxFiles'] = 10;
        }

        if (!isset($min_symlinks)) {
            $min_symlinks = array();
        }

        if (!isset($min_uploaderHoursBehind)) {
            $min_uploaderHoursBehind = 0;
        }

        if (!isset($min_customConfigPaths)) {
            $min_customConfigPaths = array(
                'groups' => \jApp::configPath('minifyGroupsConfig.php')
            );
        }

        ini_set('zlib.output_compression', '0');
    }

    static function getDocumentRoot() {
        if (isset($_SERVER['DOCUMENT_ROOT']))
            return $_SERVER['DOCUMENT_ROOT'];

        $config = parse_ini_file(\jApp::mainConfigFile());

        $urlengine = $config['urlengine'];

        if($urlengine['scriptNameServerVariable'] == '') {
            $urlengine['scriptNameServerVariable'] = \jConfigCompiler::findServerName('.php');
        }
        $urlScript = $_SERVER[$urlengine['scriptNameServerVariable']];
        $lastslash = strrpos ($urlScript, '/');

        $urlScriptPath = substr ($urlScript, 0, $lastslash ).'/';

        $basepath = $urlengine['basePath'];
        if ($basepath == '') {
            // for beginners or simple site, we "guess" the base path
            $basepath = $urlScriptPath;
        }
        elseif ($basepath != '/') {
            if($basepath[0] != '/') $basepath='/'.$basepath;
            if(substr($basepath,-1) != '/') $basepath.='/';

            if(strpos($urlScriptPath, $basepath) !== 0){
                throw new \Exception('Jelix Error: basePath ('.$basepath.') in config file doesn\'t correspond to current base path. You should setup it to '.$urlengine['urlScriptPath']);
            }
        }

        if ($basepath == '/')
            return \jApp::wwwPath();

        if(strpos(\jApp::wwwPath(), $basepath) === false){
            return \jApp::wwwPath();
        }

        return substr(\jApp::wwwPath(), 0, - (strlen($basepath)));
    }
}


<?php
namespace Core\DateTime;

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

    const SEC_PER_DAY = 60 * 60 * 24;

    const SEC_PER_HOUR = 60 * 60;

    /**
     * Converts a date and time string into timestamp
     *
     * @param string $date
     * @param string $time
     *
     * @return number
     */
    public function toTimestamp(string $date, string $time = ''): int
    {
        if (empty($time)) {
            $time = '00:00:01';
        }

        // create unix_timestamp
        return strtotime($date . ' ' . $time);
    }

    /**
     * Converts a timestamp into many date infos
     *
     * @param int $timestamp
     *            The timestamp to convert
     * @param string $dateformat
     *            The dateformat (Default: 'Y-m-d')
     * @param string $timeformat
     *            The timeformat (Default: 'H:i')
     *
     * @return array
     */
    public function fromTimestamp(int $timestamp, string $dateformat = 'Y-m-d', string $timeformat = 'H:i'): array
    {
        return [
            'stamp' => $timestamp,
            'date' => date($dateformat, $timestamp),
            'time' => date($timeformat, $timestamp),
            'week' => date('W', $timestamp),
            'day' => date('d', $timestamp),
            'month' => date('m', $timestamp),
            'hour' => date('H', $timestamp),
            'minute' => date('i', $timestamp)
        ];
    }

    /**
     * Converts a date into another format
     *
     * @param string $date
     * @param string $format
     *
     * @return string
     */
    public function dateConversion(string $date, string $format = 'Y-m-d'): string
    {
        return date($format, strtotime($date));
    }

    /**
     * Calculates time left from an timestamp in the future
     *
     * @param int $timestamp
     * @param bool $left
     *
     * @return string
     */
    public function timeLeft(int $timestamp, bool $Left = true): string
    {
        $diff = $bLeft == true ? time() - $timestamp : $timestamp;

        $showdiff = [
            "y" => 0,
            "m" => 0,
            "w" => 0,
            "d" => 0,
            "h" => 0,
            "min" => 0
        ];

        while ($diff >= 31536000) {
            // 1 year = 31536000 seconds
            $diff -= 31536000;
            $showdiff['y'] ++;
        }
        while ($diff >= 2419200) {
            // 1 day = 2592000 seconds
            $diff -= 2419200;
            $showdiff['m'] ++;
        }
        while ($diff >= 648000) {
            // 1 week = 604800 seconds
            $diff -= 648000;
            $showdiff['w'] ++;
        }

        while ($diff >= 86400) {
            // 1 day = 86400 seconds
            $diff -= 86400;
            $showdiff['d'] ++;
        }

        while ($diff >= 3600) {
            // 1 hour = 3600 seconds
            $diff -= 3600;
            $showdiff['h'] ++;
        }

        while ($diff >= 60) {
            // 1 minute = 60 seconds
            $diff -= 60;
            $showdiff['min'] ++;
        }

        return $showdiff;
    }
}


<?php

namespace Flowcode\DashboardBundle\Controller;

use Flowcode\DashboardBundle\Event\ListPluginsEvent;
use Flowcode\DashboardBundle\Event\ShowMenuEvent;
use Flowcode\DashboardBundle\Event\ShowMenuSubscriber;
use Flowcode\DashboardBundle\Listener\ShowMenuListener;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

/**
 * Dashboard Class.
 *
 * @Route("/admin/plugin")
 */
class PluginController extends Controller
{

    /**
     * Main Dashboard.
     *
     * @Route("/", name="admin_plugin")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $plugins = array();
        $listPluginsEvent = new ListPluginsEvent($plugins);

        $dispatcher = $this->get('event_dispatcher');
        $dispatcher->dispatch(ListPluginsEvent::NAME, $listPluginsEvent);

        return array(
            "plugins" => $listPluginsEvent->getPluginDescriptors(),
        );
    }

}


<?php namespace WhiteFrame\View;

use Illuminate\Support\ServiceProvider;
use WhiteFrame\Support\Application;
use WhiteFrame\Support\Environment;
use WhiteFrame\Support\Framework;

/**
 * Class ViewServiceProvider
 * @package WhiteFrame\View
 */
class ViewServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Register the service provider.
     */
    public function register()
    {
        Framework::registerPackage('view');

        $this->app->singleton('white-frame.view.view', function ($app) {
            return new \WhiteFrame\View\View();
        });

        Application::alias('WhiteFrame\View', 'WhiteFrame\View\ViewFacade');
    }

    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        view()->composer('*', function (\Illuminate\View\View $view) {
            foreach(\WhiteFrame\View::getNested($view->getName()) as $name => $datas) {
                $view->nest('nested.' . $name, $name, $datas);
            }
        });
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return [];
    }
}


<?php

namespace OlajosCs\Repository;

use OlajosCs\Repository\Contracts\ModelInterface;
use OlajosCs\Repository\Exceptions\MagicMethodCalledException;
use OlajosCs\Repository\Exceptions\ValidationException;

/**
 * Class Model
 *
 * Defines an abstract parent for the model
 */
abstract class Model implements ModelInterface
{
    /**
     * @var array The original state, as it was read from the database
     */
    protected $originalState = [];

    /**
     * Validate the model
     *
     * @return void
     * @throws ValidationException
     */
    abstract public function validate();

    /**
     * Create a new Model object
     */
    public function __construct()
    {
        $this->originalState = $this->getPropertiesForIsModified();
    }

    /**
     * Return the name of the properties, which are not important when checking model properties change.
     * These properties are usually the necessary properties for the Model/Repository workflow.
     *
     * @return array
     */
    protected function getAdditionalProperties()
    {
        return ['originalState', 'additionalProperties'];
    }

    /**
     * Return the saveable (basic) properties of the model
     *
     * @return array
     */
    public function getSaveableProperties()
    {
        $array = $this->getProperties();
        unset(
            $array[static::getIdField()]
        );

        return $array;
    }

    /**
     * Return whether the model has an ID or not
     *
     * @return bool
     */
    public function exists()
    {
        return (bool)$this->{static::getIdField()};
    }

    /**
     * Return whether the model has been modified since the construct or not
     *
     * @return bool
     */
    public function isModified()
    {
        return $this->originalState != $this->getPropertiesForIsModified();
    }

    /**
     * Return properties to isModified check
     *
     * @return array
     */
    protected function getPropertiesForIsModified()
    {
        return $this->getSaveableProperties();
    }

    /**
     * Return whether the model is valid or not
     *
     * @return bool
     */
    public function isValid()
    {
        try {
            $this->validate();
        } catch (ValidationException $e) {
            return false;
        }

        return true;
    }

    /**
     * Return the ID of the model
     *
     * @return mixed
     */
    public function getId()
    {
        return $this->{static::getIdField()};
    }

    /**
     * Set the ID of the model
     *
     * @param mixed $id
     *
     * @return $this
     */
    public function setId($id)
    {
        $this->{static::getIdField()} = $id;

        return $this;
    }

    /**
     * Return the basic properties of the model as an array
     *
     * @return array
     */
    public function getProperties()
    {
        $properties = get_object_vars($this);
        foreach ($this->getAdditionalProperties() as $notImportantProperty) {
            unset($properties[$notImportantProperty]);
        }

        return $properties;
    }

    /**
     * Returns the model with basic properties to json_encode
     *
     * @return array
     */
    public function jsonSerialize()
    {
        return $this->getProperties();
    }

    /**
     * Magic get
     *
     * @param string $property
     *
     * @return mixed
     * @throws MagicMethodCalledException
     */
    public function __get($property)
    {
        throw new MagicMethodCalledException(
            sprintf(
                'Magic __get was called with %s property on %s class',
                $property,
                static::class
            )
        );
    }

    /**
     * Magic set
     *
     * @param string $property
     * @param mixed  $value
     *
     * @return void
     * @throws MagicMethodCalledException
     */
    public function __set($property, $value)
    {
        throw new MagicMethodCalledException(
            sprintf(
                'Magic __set was called with %s property on %s class',
                $property,
                static::class
            )
        );
    }

    /**
     * Magic isset
     *
     * @param string $property
     *
     * @return void
     * @throws MagicMethodCalledException
     */
    public function __isset($property)
    {
        throw new MagicMethodCalledException(
            sprintf(
                'Magic __isset was called with %s property on %s class',
                $property,
                static::class
            )
        );
    }
}


<?php

/**
 * Jin Framework
 * Diatem
 */

namespace Jin2\Form\Validators;

use Jin2\Language\Translation;

/**
 * Validateur : teste si une valeur est un email valide
 */
class IsEmail extends AbstractValidator
{

  /**
   * Implémente la fonction AbstractValidator::getType()
   *
   * @return string
   */
  public static function getType()
  {
    return 'isemail';
  }

  /**
   * Teste la validité
   *
   * @param mixed $value Valeur à tester
   * @return boolean
   */
  public function isValid($value)
  {
    parent::resetErrors();
    if (!is_null($value) && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
      parent::addError(Translation::get('validatorerror_isemail'));
      return false;
    }
    return true;
  }

}


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

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

    /**
     * Elements
     *
     * The elements array
     *
     * @var array
     */
    protected $elements;

    /**
     * Id
     *
     * The cache id
     *
     * @var string
     */
    protected $id;

    /**
     * Timestamp offset
     *
     * The cache timestamp
     * offset
     *
     * @var integer
     */
    protected $timestampOffset;

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

    /**
     * Get id
     *
     * Return the current
     * cache id
     *
     * @return string
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Get
     *
     * Get an element
     *
     * @param string $key - the element key
     *
     * @return CacheElement - the element
     */
    public function get($key)
    {
        if ($this->has($key)) {
            return $this->elements[$key];
        } else {
            return null;
        }
    }

    /**
     * Create
     *
     * Create an element. Note
     * this method do not override
     * an existing element.
     *
     * @param string $key     - the element key
     * @param string $content - the element content
     *
     * @return CacheCollection - the current instance
     */
    public function create($key, $content)
    {
        if (! $this->has($key)) {
            $this->elements[$key] = new CacheElement($key);
            $this->elements[$key]->setContent($content);
        }
        return $this;
    }

    /**
     * Has
     *
     * Check if the element
     * exist
     *
     * @param string $key - the element key
     */
    public function has($key)
    {
        return isset($this->elements[$key]);
    }

    /**
     * Remove
     *
     * Remove an element
     *
     * @param string $key - the element key to remove
     *
     * @return CacheCollection - the current instance
     */
    public function rem($key)
    {
        if ($this->has($key)) {
            unset($this->elements[$key]);
        }

        return $this;
    }

    /**
     * Get timestamp offset
     *
     * Return the cache timestamp
     * offset
     *
     * @return number
     */
    public function getTimestampOffset()
    {
        return $this->timestampOffset;
    }

    /**
     * Set timestamp offset
     *
     * Set the cache timestamp
     * offset
     *
     * @param integer $timestampOffset - the timestamp offset
     *
     * @return CacheCollection - the current instance
     */
    public function setTimestampOffset($timestampOffset)
    {
        $this->timestampOffset = $timestampOffset;
        return $this;
    }

    /**
     * Serialize
     *
     * Serialize the current
     * instance
     *
     * @see Serializable::serialize()
     */
    public function serialize()
    {
        $dateTime = new \DateTime();
        $dateTime->setTimestamp($dateTime->getTimestamp() + $this->timestampOffset);

        foreach ($this->elements as $element) {
            if ($element instanceof CacheElement) {
                $element->setTimeOver($dateTime);
            }
        }

        return serialize(array(
            "id" => $this->id,
            "elements" => $this->elements
        ));
    }

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

        $this->id = $tmp['id'];

        $dateTime = new \DateTime();

        foreach ($tmp['elements'] as $element) {
            if ($element instanceof CacheElement){
                if ($element->getTimeOver() >= $dateTime) {
                    $this->elements[$element->getKey()] = $element;
                }
            }
        }
    }
}


<?php

namespace Kcs\FunctionMock\Prediction;

use Kcs\FunctionMock\Exception\Call\UnexpectedCallsCountException;
use Kcs\FunctionMock\FunctionProphecy;
use Prophecy\Argument\ArgumentsWildcard;
use Prophecy\Argument\Token\AnyValuesToken;
use Prophecy\Call\Call;
use Prophecy\Util\StringUtil;

class CallTimesPrediction implements PredictionInterface
{
    private $times;
    private $util;

    /**
     * Initializes prediction.
     *
     * @param int        $times
     * @param StringUtil $util
     */
    public function __construct($times, StringUtil $util = null)
    {
        $this->times = intval($times);
        $this->util = $util ?: new StringUtil();
    }

    /**
     * Tests that there was exact amount of calls made.
     *
     * @param Call[]         $calls
     * @param FunctionProphecy $prophecy
     *
     * @throws UnexpectedCallsCountException
     */
    public function check(array $calls, FunctionProphecy $prophecy)
    {
        if ($this->times == count($calls)) {
            return;
        }

        $methodCalls = $prophecy->getNamespace()->findCalls(
            $prophecy->getName(),
            new ArgumentsWildcard([new AnyValuesToken()])
        );

        if (count($calls)) {
            $message = sprintf(
                "Expected exactly %d calls that match:\n".
                "  %s(%s)\n".
                "but %d were made:\n%s",

                $this->times,
                $prophecy->getName(),
                $prophecy->getArgumentsWildcard(),
                count($calls),
                $this->util->stringifyCalls($calls)
            );
        } elseif (count($methodCalls)) {
            $message = sprintf(
                "Expected exactly %d calls that match:\n".
                "  %s(%s)\n".
                "but none were made.\n".
                "Recorded `%s(...)` calls:\n%s",

                $this->times,
                $prophecy->getName(),
                $prophecy->getArgumentsWildcard(),
                $prophecy->getName(),
                $this->util->stringifyCalls($methodCalls)
            );
        } else {
            $message = sprintf(
                "Expected exactly %d calls that match:\n".
                "  %s(%s)\n".
                'but none were made.',

                $this->times,
                $prophecy->getName(),
                $prophecy->getArgumentsWildcard()
            );
        }

        throw new UnexpectedCallsCountException($message);
    }
}


<?php

declare(strict_types=1);

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

namespace Teknoo\States\LifeCycle\Scenario;

use Symfony\Component\Yaml\Parser;

/**
 * Class ScenarioYamlBuilder
 * Another implementation of scenario builder to allow developper to create scenarii from YAML files
 * about stated class instances.
 * A scenario can accept several conditions : each condition must be validated to execute the scenario. *.
 *
 * @copyright   Copyright (c) 2009-2017 Richard Déloge (richarddeloge@gmail.com)
 *
 * @link        http://teknoo.software/states Project website
 *
 * @license     http://teknoo.software/license/mit         MIT License
 * @author      Richard Déloge <richarddeloge@gmail.com>
 */
class ScenarioYamlBuilder extends ScenarioBuilder
{
    /**
     * YAML parser to read the scenario.
     *
     * @var Parser
     */
    private $yamlParser;

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

    /**
     * @var array
     */
    private $parameters = [];

    /**
     * To list options, in yaml, correspondence with builder's methods.
     *
     * @var array
     */
    private $yamlOptionsMap = [
        'when' => 'when',
        'class' => 'towardStatedClass',
        'notIn' => 'ifNotInState',
        'in' => 'ifInState',
        'incoming' => 'onIncomingState',
        'outgoing' => 'onOutgoingState',
        'run' => 'run',
    ];

    /**
     * @param Parser $yamlParser
     *
     * @return self
     */
    public function setYamlParser(Parser $yamlParser): ScenarioYamlBuilder
    {
        $this->yamlParser = $yamlParser;

        return $this;
    }

    /**
     * @param string $yamlContent
     *
     * @return array
     */
    private function parseYaml(string $yamlContent): array
    {
        return $this->yamlParser->parse($yamlContent);
    }

    /**
     * To parse options, detect parameters and replace them by parameter.
     *
     * @param $optionValues
     */
    private function parseParameter(&$optionValues)
    {
        if (!\is_callable($optionValues) && !empty($optionValues)) {
            if (\is_array($optionValues) && '$' === $optionValues[0][0]) {
                if (isset($this->parameters[$optionValues[0]])) {
                    $optionValues[0] = $this->parameters[$optionValues[0]];
                }
            } elseif (\is_string($optionValues) && '$' === $optionValues[0]) {
                if (isset($this->parameters[$optionValues])) {
                    $optionValues = $this->parameters[$optionValues];
                }
            }
        }
    }

    /**
     * @param array $scenario
     *
     * @return ScenarioYamlBuilder
     */
    private function configureBuilder(array $scenario): ScenarioYamlBuilder
    {
        foreach ($scenario as &$options) {
            foreach ($options as $optionName => $optionValues) {
                if (isset($this->yamlOptionsMap[$optionName])) {
                    $methodName = $this->yamlOptionsMap[$optionName];
                    if ('run' != $methodName) {
                        foreach ((array) $optionValues as $optionValue) {
                            $this->{$methodName}($optionValue);
                        }
                    } else {
                        if (!\is_callable($optionValues)) {
                            $this->parseParameter($optionValues);
                        }

                        $this->run($optionValues);
                    }
                } else {
                    throw new \RuntimeException('Unknow option '.$optionName);
                }
            }
        }

        return $this;
    }

    /**
     * To register a parameter to use during yaml parsing.
     *
     * @param string $parameterName
     * @param $object
     *
     * @return ScenarioYamlBuilder
     */
    public function setParameter(string $parameterName, $object): ScenarioYamlBuilder
    {
        $this->parameters['$'.$parameterName] = $object;

        return $this;
    }

    /**
     * To transform a yaml scenario to native scenario.
     *
     * @param string $scenario
     *
     * @return ScenarioYamlBuilder
     */
    public function loadScenario(string $scenario): ScenarioYamlBuilder
    {
        $this->yamlScenario = $scenario;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function build(ScenarioInterface $scenario): ScenarioInterface
    {
        $this->configureBuilder(
            $this->parseYaml(
                $this->yamlScenario
            )
        );

        return parent::build($scenario);
    }
}


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

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

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

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

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

			$domain = new ObjectDomain($this->getServiceContainer());
			$serializer = Object::getSerializer();

			$fields = $serializer->getFields();
			$attribs = [];

			foreach ($fields as $field) {
				if ($post->has($field)) {
					$attribs[$field] = $post->get($field);
				}
			}

			$attribs['fixed'] = $post->has('fixed');

			$payload = $domain->update($object->getId(), ['attributes' => $attribs]);
			if ($payload instanceof NotValid) {
				$payload = new NotValid(array_merge($data, $payload->get()));
			}
		}

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


<?php

namespace Jobles\Core;

abstract class AbstractCollection implements \IteratorAggregate, \Countable
{

    /**
     * @var mixed
     */
    protected $class;

    /**
     * @var array
     */
    private $data = [];

    /**
     * @var int
     */
    private $size = 0;

    /**
     * @param $object
     */
    public function add($object)
    {
        $this->validateObjectInstance($object);
        $this->data[] = $object;
        $this->size++;
    }

    /**
     * @param int $position
     *
     * @return mixed
     * @throws \LengthException
     */
    public function pick(int $position)
    {
        if (isset($this->data[$position])) {
            return $this->data[$position];
        }

        throw new \LengthException('Invalid index position: ' . $position);
    }

    /**
     * @return int
     */
    public function count() : int
    {
        return $this->size;
    }

    /**
     * @return Iterator
     */
    public function getIterator() : Iterator
    {
        return new Iterator($this);
    }

    /**
     * @param mixed $object
     */
    private function validateObjectInstance($object)
    {
        if (!$object instanceof $this->class) {
            throw new \InvalidArgumentException('Object is not an instance of ' . $this->class);
        }
    }
}


<?php
/**
 * DefaultApi
 * PHP version 5
 *
 * @category Class
 * @package  Swagger\Client
 * @author   http://github.com/swagger-api/swagger-codegen
 * @license  http://www.apache.org/licenses/LICENSE-2.0 Apache License v2
 * @link     https://github.com/swagger-api/swagger-codegen
 */

/**
 * shoutout-sdk
 *
 * shoutout sdk
 *
 * OpenAPI spec version: 7.9.0
 * Contact: info@getshoutout.com
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 *
 * 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.
 */

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */

namespace Swagger\Client\Api;

use \Swagger\Client\ApiClient;
use \Swagger\Client\ApiException;
use \Swagger\Client\Configuration;
use \Swagger\Client\ObjectSerializer;

/**
 * DefaultApi Class Doc Comment
 *
 * @category Class
 * @package  Swagger\Client
 * @author   http://github.com/swagger-api/swagger-codegen
 * @license  http://www.apache.org/licenses/LICENSE-2.0 Apache License v2
 * @link     https://github.com/swagger-api/swagger-codegen
 */
class DefaultApi
{
    /**
     * API Client
     *
     * @var \Swagger\Client\ApiClient instance of the ApiClient
     */
    protected $apiClient;

    /**
     * Constructor
     *
     * @param \Swagger\Client\ApiClient|null $apiClient The api client to use
     */
    public function __construct(\Swagger\Client\ApiClient $apiClient = null)
    {
        if ($apiClient === null) {
            $apiClient = new ApiClient();
            $apiClient->getConfig()->setHost('https://api.getshoutout.com/coreservice');
        }

        $this->apiClient = $apiClient;
        $this->customHost = "https://api.getshoutout.com/coreservice";
    }

    /**
     * Get API client
     *
     * @return \Swagger\Client\ApiClient get the API client
     */
    public function getApiClient()
    {
        return $this->apiClient;
    }

    /**
     * Set the API client
     *
     * @param \Swagger\Client\ApiClient $apiClient set the API client
     *
     * @return DefaultApi
     */
    public function setApiClient(\Swagger\Client\ApiClient $apiClient)
    {
        $this->apiClient = $apiClient;
        return $this;
    }

    /**
     * Operation activitiesPost
     *
     *
     *
     * @param string $authorization  (required)
     * @param array $activity  (required)
     * @throws \Swagger\Client\ApiException on non-2xx response
     * @return \Swagger\Client\Model\Response
     */
    public function activitiesPost($authorization, $activity)
    {
        list($response) = $this->activitiesPostWithHttpInfo($authorization, $activity);
        return $response;
    }

    /**
     * Operation activitiesPostWithHttpInfo
     *
     *
     *
     * @param string $authorization  (required)
     * @param array $activity  (required)
     * @throws \Swagger\Client\ApiException on non-2xx response
     * @return array of \Swagger\Client\Model\Response, HTTP status code, HTTP response headers (array of strings)
     */
    public function activitiesPostWithHttpInfo($authorization, $activity)
    {
        // verify the required parameter 'authorization' is set
        if ($authorization === null) {
            throw new \InvalidArgumentException('Missing the required parameter $authorization when calling activitiesPost');
        }
        // verify the required parameter 'activity' is set
        if ($activity === null) {
            throw new \InvalidArgumentException('Missing the required parameter $activity when calling activitiesPost');
        }
        // parse inputs
        $resourcePath = "/activities";
        $httpBody = '';
        $queryParams = [];
        $headerParams = [];
        $formParams = [];
        $_header_accept = $this->apiClient->selectHeaderAccept(['application/json']);
        if (!is_null($_header_accept)) {
            $headerParams['Accept'] = $_header_accept;
        }
        $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json']);

        // header params
        if ($authorization !== null) {
            $headerParams['Authorization'] = $this->apiClient->getSerializer()->toHeaderValue($authorization);
        }
        // default format to json
        $resourcePath = str_replace("{format}", "json", $resourcePath);

        // body params
        $_tempBody = null;
        if (isset($activity)) {
            $_tempBody = $activity;
        }

        // for model (json/xml)
        if (isset($_tempBody)) {
            $httpBody = $_tempBody; // $_tempBody is the method argument, if present
        } elseif (count($formParams) > 0) {
            $httpBody = $formParams; // for HTTP post (form)
        }
        // this endpoint requires API key authentication
        $apiKey = $this->apiClient->getApiKeyWithPrefix('Authorization');
        if (strlen($apiKey) !== 0) {
            $headerParams['Authorization'] = $apiKey;
        }
        // make the API Call
        try {
            list($response, $statusCode, $httpHeader) = $this->apiClient->callApi(
                $resourcePath,
                'POST',
                $queryParams,
                $httpBody,
                $headerParams,
                '\Swagger\Client\Model\Response',
                '/activities'
            );

            return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Response', $httpHeader), $statusCode, $httpHeader];
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Response', $e->getResponseHeaders());
                    $e->setResponseObject($data);
                    break;
            }

            throw $e;
        }
    }

    /**
     * Operation contactsPost
     *
     *
     *
     * @param string $authorization  (required)
     * @param array $contacts  (required)
     * @throws \Swagger\Client\ApiException on non-2xx response
     * @return \Swagger\Client\Model\Response
     */
    public function contactsPost($authorization, $contacts)
    {
        list($response) = $this->contactsPostWithHttpInfo($authorization, $contacts);
        return $response;
    }

    /**
     * Operation contactsPostWithHttpInfo
     *
     *
     *
     * @param string $authorization  (required)
     * @param array $contacts  (required)
     * @throws \Swagger\Client\ApiException on non-2xx response
     * @return array of \Swagger\Client\Model\Response, HTTP status code, HTTP response headers (array of strings)
     */
    public function contactsPostWithHttpInfo($authorization, $contacts)
    {
        // verify the required parameter 'authorization' is set
        if ($authorization === null) {
            throw new \InvalidArgumentException('Missing the required parameter $authorization when calling contactsPost');
        }
        // verify the required parameter 'contacts' is set
        if ($contacts === null) {
            throw new \InvalidArgumentException('Missing the required parameter $contacts when calling contactsPost');
        }
        // parse inputs
        $resourcePath = "/contacts";
        $httpBody = '';
        $queryParams = [];
        $headerParams = [];
        $formParams = [];
        $_header_accept = $this->apiClient->selectHeaderAccept(['application/json']);
        if (!is_null($_header_accept)) {
            $headerParams['Accept'] = $_header_accept;
        }
        $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json']);

        // header params
        if ($authorization !== null) {
            $headerParams['Authorization'] = $this->apiClient->getSerializer()->toHeaderValue($authorization);
        }
        // default format to json
        $resourcePath = str_replace("{format}", "json", $resourcePath);

        // body params
        $_tempBody = null;
        if (isset($contacts)) {
            $_tempBody = $contacts;
        }

        // for model (json/xml)
        if (isset($_tempBody)) {
            $httpBody = $_tempBody; // $_tempBody is the method argument, if present
        } elseif (count($formParams) > 0) {
            $httpBody = $formParams; // for HTTP post (form)
        }
        // this endpoint requires API key authentication
        $apiKey = $this->apiClient->getApiKeyWithPrefix('Authorization');
        if (strlen($apiKey) !== 0) {
            $headerParams['Authorization'] = $apiKey;
        }
        // make the API Call
        try {
            list($response, $statusCode, $httpHeader) = $this->apiClient->callApi(
                $resourcePath,
                'POST',
                $queryParams,
                $httpBody,
                $headerParams,
                '\Swagger\Client\Model\Response',
                '/contacts'
            );

            return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Response', $httpHeader), $statusCode, $httpHeader];
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Response', $e->getResponseHeaders());
                    $e->setResponseObject($data);
                    break;
            }

            throw $e;
        }
    }

    /**
     * Operation messagesPost
     *
     *
     *
     * @param string $authorization  (required)
     * @param \Swagger\Client\Model\Message $message  (required)
     * @throws \Swagger\Client\ApiException on non-2xx response
     * @return \Swagger\Client\Model\MessageResponse
     */
    public function messagesPost($authorization, $message)
    {
        list($response) = $this->messagesPostWithHttpInfo($authorization, $message);
        return $response;
    }

    /**
     * Operation messagesPostWithHttpInfo
     *
     *
     *
     * @param string $authorization  (required)
     * @param \Swagger\Client\Model\Message $message  (required)
     * @throws \Swagger\Client\ApiException on non-2xx response
     * @return array of \Swagger\Client\Model\MessageResponse, HTTP status code, HTTP response headers (array of strings)
     */
    public function messagesPostWithHttpInfo($authorization, $message)
    {
        // verify the required parameter 'authorization' is set
        if ($authorization === null) {
            throw new \InvalidArgumentException('Missing the required parameter $authorization when calling messagesPost');
        }
        // verify the required parameter 'message' is set
        if ($message === null) {
            throw new \InvalidArgumentException('Missing the required parameter $message when calling messagesPost');
        }
        // parse inputs
        $resourcePath = "/messages";
        $httpBody = '';
        $queryParams = [];
        $headerParams = [];
        $formParams = [];
        $_header_accept = $this->apiClient->selectHeaderAccept([]);
        if (!is_null($_header_accept)) {
            $headerParams['Accept'] = $_header_accept;
        }
        $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]);

        // header params
        if ($authorization !== null) {
            $headerParams['Authorization'] = $this->apiClient->getSerializer()->toHeaderValue($authorization);
        }
        // default format to json
        $resourcePath = str_replace("{format}", "json", $resourcePath);

        // body params
        $_tempBody = null;
        if (isset($message)) {
            $_tempBody = $message;
        }

        // for model (json/xml)
        if (isset($_tempBody)) {
            $httpBody = $_tempBody; // $_tempBody is the method argument, if present
        } elseif (count($formParams) > 0) {
            $httpBody = $formParams; // for HTTP post (form)
        }
        // this endpoint requires API key authentication
        $apiKey = $this->apiClient->getApiKeyWithPrefix('Authorization');
        if (strlen($apiKey) !== 0) {
            $headerParams['Authorization'] = $apiKey;
        }
        // make the API Call
        try {
            list($response, $statusCode, $httpHeader) = $this->apiClient->callApi(
                $resourcePath,
                'POST',
                $queryParams,
                $httpBody,
                $headerParams,
                '\Swagger\Client\Model\MessageResponse',
                '/messages',
                $this->customHost
            );

            return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\MessageResponse', $httpHeader), $statusCode, $httpHeader];
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\MessageResponse', $e->getResponseHeaders());
                    $e->setResponseObject($data);
                    break;
            }

            throw $e;
        }
    }
}


<?php

namespace KsUtils\StrFilter;

/**
 * Filter for stripping trailing whitespaces
 */
class Trim implements \KsUtils\StrFilter
{
    /**
     * Strips all trailing whitespaces
     * @param  string|array $str Source string
     * @return string       Fiiltered string
     */
    public function filter($str)
    {
        if (is_null($str)) {
            return null;
        }

        if (is_array($str)) {
            foreach ($str as $k => $v) {
                $str[$k] = trim($v);
            }

            return $str;
        }

        return trim($str);
    }
}


<?php

namespace Ekyna\Bundle\CoreBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class DateRange
 * @package Ekyna\Bundle\CoreBundle\Form\Type
 * @author Étienne Dauvergne <contact@ekyna.com>
 * TODO see http://eonasdan.github.io/bootstrap-datetimepicker/#linked-pickers
 */
class DateRange extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $format = $options['time'] ? 'dd/MM/yyyy HH:mm' : 'dd/MM/yyyy';

        $builder
            ->add('startDate', 'datetime', [
                'label' => 'ekyna_core.field.start_date',
                'format' => $format,
            ])
            ->add('endDate', 'datetime', [
                'label' => 'ekyna_core.field.end_date',
                'format' => $format,
            ])
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver
            ->setDefaults([
                'time'         => true,
                'inherit_data' => true,
            ])
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'ekyna_date_range';
    }
}


<?php
/**
 * @package axy\evil
 * @author Oleg Grigoriev <go.vasac@gmail.com>
 */

namespace axy\evil;

/**
 * Evil functions
 */
class Evil
{
    /**
     * Executes a PHP-code
     *
     * @param string $code
     * @return mixed
     * @throws \Exception
     * @SuppressWarnings(PHPMD.EvalExpression)
     */
    public static function execCode($code)
    {
        return eval($code);
    }

    /**
     * Terminates the current script
     *
     * @param int $status [optional]
     * @SuppressWarnings(PHPMD.ExitExpression)
     */
    public static function stop($status = null)
    {
        exit($status);
    }

    /**
     * Outputs debug breakpoint and terminates the current script
     *
     * @param mixed $message
     * @param bool $line [optional]
     * @param bool $file [optional]
     * @param int $status [optional]
     */
    public static function breakpoint($message, $line = false, $file = false, $status = null)
    {
        if (!is_scalar($message)) {
            $message = print_r($message, 1);
        }
        $message = self::appendFL($message, $line, $file);
        if (php_sapi_name() === 'cli') {
            $message .= PHP_EOL;
        } else {
            $message = '<pre>'.htmlspecialchars($message, ENT_COMPAT, 'UTF-8').'</pre>';
        }
        self::out($message);
        self::stop($status);
    }

    /**
     * Outputs a message to the stdout
     *
     * @param string $message
     */
    public static function out($message)
    {
        echo $message;
    }

    /**
     * @param string $message
     * @param bool $line
     * @param bool $file
     * @return string
     */
    private static function appendFL($message, $line, $file)
    {
        if (!($line || $file)) {
            return $message;
        }
        $back = debug_backtrace();
        if ((!$back) || (!isset($back[1]))) {
            return $message;
        }
        $back = $back[1];
        $prefix = [];
        if ($file) {
            $prefix[] = $back['file'];
        }
        if ($line) {
            $prefix[] = $back['line'];
        }
        return implode(':', $prefix).': '.$message;
    }
}