<?php

namespace Oxygen\Data\Migrations;

use Doctrine\ORM\QueryBuilder;
use Exception;
use Illuminate\Database\Migrations\MigrationRepositoryInterface;

class DoctrineMigrationRepository implements MigrationRepositoryInterface {

    /**
     * The entity manager
     *
     * @var \Doctrine\ORM\EntityManagerInterface
     */
    protected $entities;

    /**
     * The schema tool
     *
     * @var \Doctrine\ORM\Tools\SchemaTool
     */
    protected $schema;

    /**
     * The metadata factory
     *
     * @var \Doctrine\ORM\Mapping\ClassMetadataFactory
     */
    protected $metadata;

    /**
     * Create a new database migration repository instance.
     *
     * @param callable $entitiesCallback
     * @param callable $schemaCallback
     * @param callable $metadataCallback
     */
    public function __construct(callable $entitiesCallback, callable $schemaCallback, callable $metadataCallback) {
        $this->entitiesCallback = $entitiesCallback;
        $this->schemaCallback = $schemaCallback;
        $this->metadataCallback = $metadataCallback;
    }

    /**
     * Get the ran migrations.
     *
     * @return array
     */
    public function getRan() {
        $migrations = $this->query()
            ->getQuery()->getResult();

        $return = [];

        foreach($migrations as $migration) {
            $return[] = $migration['migration'];
        }

        return $return;
    }

    /**
     * Get the last migration batch.
     *
     * @return array
     */
    public function getLast() {
        return $this->query()
            ->where('o.batch = :lastBatch')
            ->setParameter('lastBatch', $this->getLastBatchNumber())
            ->orderBy('o.migration', 'desc')->getQuery()->getResult();
    }
    /**
     * Log that a migration was run.
     *
     * @param  string  $file
     * @param  int     $batch
     * @return void
     */
    public function log($file, $batch) {
        $migration = new Migration($file, $batch);
        $this->getEntities()->persist($migration);
        $this->getEntities()->flush();
    }
    /**
     * Remove a migration from the log.
     *
     * @param  object  $migration
     * @return void
     */
    public function delete($migration) {
        $this->getEntities()->createQueryBuilder()
            ->delete('Mitch\LaravelDoctrine\Migrations\Migration', 'o')
            ->andWhere('o.migration = :migration')
            ->setParameter('migration', $migration->migration)
            ->getQuery()
            ->execute();
    }

    /**
     * Get the next migration batch number.
     *
     * @return int
     */
    public function getNextBatchNumber() {
        return $this->getLastBatchNumber() + 1;
    }
    /**
     * Get the last migration batch number.
     *
     * @return int
     */
    public function getLastBatchNumber() {
        $result = $this->getEntities()->createQueryBuilder()
            ->select('o, MAX(o.batch) as max_batch')
            ->from('Mitch\LaravelDoctrine\Migrations\Migration', 'o')
            ->getQuery()->getResult()[0]['max_batch'];

        return $result ?: 0;
    }

    /**
     * Create the migration repository data store.
     *
     * @return void
     */
    public function createRepository() {
        $this->getSchemaTool()->updateSchema($this->getMetadata()->getAllMetadata());
    }

    /**
     * Determine if the migration repository exists.
     *
     * @return bool
     */
    public function repositoryExists() {
        $schema = $this->getEntities()->getConnection()->getSchemaManager();
        $tables = array_filter($schema->listTables(), function($value) {
            return $value->getName() === 'migrations';
        });

        return !empty($tables);
    }

    /**
     * Get a query builder for the migration table.
     *
     * @return QueryBuilder
     */
    protected function query() {
        return $this->getEntities()->createQueryBuilder()
              ->select('o')
              ->from('Mitch\LaravelDoctrine\Migrations\Migration', 'o');
    }

    /**
     * Set the information source to gather data.
     *
     * @param  string $name
     * @throws \Exception
     * @return void
     */
    public function setSource($name) {
        // not implemented
    }

    protected function getEntities() {
        if($this->entities == null) {
            $callable = $this->entitiesCallback;
            $this->entities = $callable();
        }
        return $this->entities;
    }

    protected function getSchemaTool() {
        if($this->schema == null) {
            $callable = $this->schemaCallback;
            $this->schema = $callable();
        }
        return $this->schema;
    }

    protected function getMetadata() {
        if($this->metadata == null) {
            $callable = $this->metadataCallback;
            $this->metadata = $callable();
        }
        return $this->metadata;
    }

}


<?php

namespace Colorium\Http;

class Response
{

    /** @var int */
    public $code = 200;

    /** @var string */
    public $format = 'text/plain';

    /** @var string */
    public $charset = 'utf-8';

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

    /** @var string */
    public $content;

    /** @var bool */
    public $raw = false;

    /**
     * New Response
     *
     * @param string $content
     * @param int $code
     * @param array $headers
     */
    public function __construct($content = null, $code = 200, array $headers = [])
    {
        $this->content = $content;
        $this->code = $code;

        foreach($headers as $header  =>  $value) {
            $this->header($header, $value);
        }
    }

    /**
     * Set header
     *
     * @param string $name
     * @param string $value
     * @param bool $replace
     *
     * @return $this
     */
    public function header($name, $value, $replace = true)
    {
        $name = strtolower($name);
        if(isset($this->headers[$name]) and !$replace) {
            if(is_array($this->headers[$name])) {
                array_push($this->headers[$name], $value);
            }
            else {
                $this->headers[$name] = [
                    $this->headers[$name],
                    $value
                ];
            }
        }
        else {
            $this->headers[$name] = $value;
        }

        return $this;
    }

    /**
     * Set cookie
     *
     * @param string $name
     * @param string $value
     * @param int $expires
     *
     * @return $this
     */
    public function cookie($name, $value, $expires = 0)
    {
        $cookie = urlencode($name);

        // has value
        if($value) {
            $cookie .= '=' . urlencode($value) . ';';
            $cookie .= ' expires=' . gmdate("D, d-M-Y H:i:s T", time() - 31536001) . ';';
        }
        // delete cookie
        else {
            $cookie .= '=deleted;';
            if($expires) {
                $cookie .= ' expires=' . gmdate("D, d-M-Y H:i:s T", time() - $expires);
            }
        }

        return $this->header('Set-Cookie', $cookie, false);
    }

    /**
     * Add no-cache headers
     *
     * @return $this
     */
    public function noCache()
    {
        $this->header('Cache-Control', 'no-cache, must-revalidate');
        $this->header('Expires', 'Sat, 26 Jul 1997 05:00:00 GMT');

        return $this;
    }

    /**
     * Response already sent ?
     *
     * @return bool
     */
    public function sent()
    {
        return headers_sent();
    }

    /**
     * Send response
     *
     * @return string
     */
    public function send()
    {
        // send headers
        if(!$this->sent()) {

            // set content type
            if(!isset($this->headers['Content-Type'])) {
                $header = 'Content-Type: ' . $this->format;
                if($this->charset) {
                    $header .= '; charset=' . $this->charset;
                }
                header($header);
            }

            // set http code
            header('HTTP/1.1 ' . $this->code . ' ' . Status::message($this->code), true, $this->code);

            // compile header
            foreach($this->headers as $name => $value) {
                if(is_array($value)) {
                    foreach($value as $subvalue) {
                        header($name . ': ' . $subvalue);
                    }
                }
                else {
                    header($name . ': ' . $value);
                }
            }
        }

        // send content
        echo (string)$this->content;

        return $this->sent();
    }

    /**
     * Raw response
     *
     * @param string $content
     * @param int $code
     * @param array $headers
     * @return Response
     */
    public static function create($content = null, $code = 200, array $headers = [])
    {
        return new Response($content, $code, $headers);
    }

    /**
     * Create HTML response
     *
     * @param string $content
     * @param int $code
     * @param array $headers
     * @return Response\Html
     */
    public static function html($content = null, $code = 200, array $headers = [])
    {
        return new Response\Html($content, $code , $headers);
    }

    /**
     * Create JSON response
     *
     * @param string $content
     * @param int $code
     * @param array $headers
     * @return Response\Json
     */
    public static function json($content = null, $code = 200, array $headers = [])
    {
        return new Response\Json($content, $code , $headers);
    }

    /**
     * Create redirect response
     *
     * @param string $uri
     * @param int $code
     * @param array $headers
     * @return Response\Redirect
     */
    public static function redirect($uri, $code = 200, array $headers = [])
    {
        return new Response\Redirect($uri, $code , $headers);
    }

    /**
     * Create download response
     *
     * @param string $filename
     * @param int $code
     * @param array $headers
     * @return Response\Redirect
     */
    public static function download($filename, $code = 200, array $headers = [])
    {
        return new Response\Download($filename, $code , $headers);
    }

    /**
     * Create template response
     *
     * @param string $template
     * @param array $vars
     * @param int $code
     * @param array $headers
     * @return Response\Template
     */
    public static function template($template, array $vars = [], $code = 200, array $headers = [])
    {
        return new Response\Template($template, $vars, $code , $headers);
    }

}


<?php

/*
 * This file is part of madewithlove/service-providers
 *
 * (c) madewithlove <heroes@madewithlove.be>
 *
 * For the full copyright and license information, please view the LICENSE
 */

namespace Madewithlove\ServiceProviders\Templating;

use Interop\Container\ServiceProviderInterface;
use Madewithlove\ServiceProviders\Utilities\Alias;
use Psr\Container\ContainerInterface;
use Twig_Environment;
use Twig_Extension;
use Twig_Loader_Array;
use Twig_Loader_Filesystem;
use Twig_LoaderInterface;

class TwigServiceProvider implements ServiceProviderInterface
{
    /**
     * Path to the views or a list of views.
     *
     * @var string|string[]
     */
    protected $views;

    /**
     * @var array
     */
    protected $options = [];

    /**
     * @var Twig_Extension[]
     */
    protected $extensions = [];

    /**
     * @param string|string[]  $views
     * @param array            $options
     * @param Twig_Extension[] $extensions
     */
    public function __construct($views = [], array $options = [], array $extensions = [])
    {
        $this->views = $views;
        $this->options = $options;
        $this->extensions = $extensions;
    }

    /**
     * {@inheritdoc}
     */
    public function getServices()
    {
        return [
            Twig_LoaderInterface::class => [$this, 'getLoader'],
            Twig_Environment::class => [$this, 'getEnvironment'],
            'twig' => new Alias(Twig_Environment::class),
        ];
    }

    /**
     * @return Twig_LoaderInterface
     */
    public function getLoader()
    {
        if (is_string($this->views) && !is_dir($this->views)) {
            $this->views = [$this->views];
        }

        $isViewsFolder = is_string($this->views) && is_dir($this->views);
        $loader = $isViewsFolder ? Twig_Loader_Filesystem::class : Twig_Loader_Array::class;

        return new $loader($this->views ?: []);
    }

    /**
     * @param ContainerInterface $container
     *
     * @return Twig_Environment
     */
    public function getEnvironment(ContainerInterface $container)
    {
        $twig = new Twig_Environment($container->get(Twig_LoaderInterface::class), $this->options);
        foreach ($this->extensions as $extension) {
            $twig->addExtension(is_string($extension) ? $container->get($extension) : $extension);
        }

        return $twig;
    }
}


<?php

namespace Reaction\Db;

use Reaction\Base\Component;
use Reaction\Exceptions\NotSupportedException;
use Reaction\Promise\ExtendedPromiseInterface;
use Reaction\Promise\LazyPromise;
use Reaction\Promise\LazyPromiseInterface;
use function Reaction\Promise\allInOrder;
use function Reaction\Promise\resolve;

/**
 * Class Connection.
 * Used for isolated transactions
 * @package Reaction\Db
 */
class Connection extends Component implements ConnectionInterface, DbConnectionGetterInterface
{
    /** @var DatabaseInterface */
    public $db;

    /**
     * Begin transaction
     * @param string|null $isolationLevel
     * @return LazyPromiseInterface
     */
    public function beginTransaction($isolationLevel = null)
    {
        $beginCmd = $this->createCommand("BEGIN")->execute();
        $isolationCmd = isset($isolationLevel)
            ? $this->setTransactionIsolationLevel($isolationLevel)
            : resolve(true);
        $promises = [$beginCmd, $isolationCmd];
        return new LazyPromise(function() use ($promises) {
            return allInOrder($promises);
        });
    }

    /**
     * Commit transaction
     * @return LazyPromiseInterface
     */
    public function commitTransaction()
    {
        return $this->createCommand("COMMIT")->execute();
    }

    /**
     * Rolls back whole transaction
     * @return LazyPromiseInterface
     */
    public function rollBackTransaction() {
        return $this->createCommand("ROLLBACK")->execute();
    }

    /**
     * Creates a new savepoint.
     * @param string $name the savepoint name
     * @return LazyPromiseInterface
     */
    public function createSavepoint($name)
    {
        return $this->createCommand("SAVEPOINT $name")->execute();
    }

    /**
     * Releases an existing savepoint.
     * @param string $name the savepoint name
     * @return LazyPromiseInterface
     */
    public function releaseSavepoint($name)
    {
        return $this->createCommand("RELEASE SAVEPOINT $name")->execute();
    }

    /**
     * Rolls back to a previously created savepoint.
     * @param string $name the savepoint name
     * @return LazyPromiseInterface
     */
    public function rollBackSavepoint($name)
    {
        return $this->createCommand("ROLLBACK TO SAVEPOINT $name")->execute();
    }

    /**
     * Sets the isolation level of the current transaction.
     * @param string $level The transaction isolation level to use for this transaction.
     * This can be one of [[Transaction::READ_UNCOMMITTED]], [[Transaction::READ_COMMITTED]], [[Transaction::REPEATABLE_READ]]
     * and [[Transaction::SERIALIZABLE]] but also a string containing DBMS specific syntax to be used
     * after `SET TRANSACTION ISOLATION LEVEL`.
     * @return LazyPromiseInterface
     * @see http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels
     */
    public function setTransactionIsolationLevel($level)
    {
        return $this->createCommand("SET TRANSACTION ISOLATION LEVEL $level")->execute();
    }

    /**
     * Create DB command
     * @param string|null $sql
     * @param array       $params
     * @return CommandInterface
     */
    public function createCommand($sql = null, $params = [])
    {
        return $this->db->createCommand($sql, $params, $this);
    }

    /**
     * Execute SQL statement string
     * @param string $sql Statement SQL string
     * @param array  $params Statement parameters
     * @param bool   $lazy Use lazy promise
     * @return ExtendedPromiseInterface|LazyPromiseInterface
     */
    public function executeSql($sql, $params = [], $lazy = true)
    {
        throw new NotSupportedException("SQL execution is not supported");
    }

    /**
     * Close connection
     */
    public function close()
    {
        $this->emit(static::EVENT_CLOSE, [$this]);
    }

    /**
     * Get Database if applicable.
     * @see DbConnectionGetterInterface
     * @return DatabaseInterface|null
     */
    public function getDb()
    {
        return $this->db;
    }

    /**
     * Get Connection if applicable
     * @see DbConnectionGetterInterface
     * @return ConnectionInterface|null
     */
    public function getConnection()
    {
        return $this;
    }
}


<?php

namespace Simples\Console;

/**
 * Class ControllerService
 * @package Simples\Console
 */
abstract class ControllerService extends GeneratorService
{
    /**
     * @var string
     */
    protected static $layer = 'controller';

    /**
     * Ask for others layers
     * @param FileManager $fileManager
     * @param array $parameters
     */
    protected static function others(FileManager $fileManager, array &$parameters)
    {
        if (in_array(
            static::explain($parameters, 'Do you want to create Model layer?', '[y/n]'),
            static::POSITIVES)
        ) {
            $fileManager->execute('model');
        }
        if (in_array(
            static::explain($parameters, 'Do you want to create Repository layer?', '[y/n]'),
            self::POSITIVES
        )) {
            $fileManager->execute('repository');
        }
    }
}


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

/**
 * @see Zend_Filter_Interface
 */

/**
 * Compresses a given string
 *
 * @category   Zend
 * @package    Zend_Filter
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Filter_Compress implements Zend_Filter_Interface
{
    /**
     * Compression adapter
     */
    protected $_adapter = 'Gz';

    /**
     * Compression adapter constructor options
     */
    protected $_adapterOptions = array();

    /**
     * Class constructor
     *
     * @param string|array $options (Optional) Options to set
     */
    public function __construct($options = null)
    {
        if ($options instanceof Zend_Config) {
            $options = $options->toArray();
        }
        if (is_string($options)) {
            $this->setAdapter($options);
        } elseif ($options instanceof Zend_Filter_Compress_CompressInterface) {
            $this->setAdapter($options);
        } elseif (is_array($options)) {
            $this->setOptions($options);
        }
    }

    /**
     * Set filter setate
     *
     * @param  array $options
     * @return Zend_Filter_Compress
     */
    public function setOptions(array $options)
    {
        foreach ($options as $key => $value) {
            if ($key == 'options') {
                $key = 'adapterOptions';
            }
            $method = 'set' . ucfirst($key);
            if (method_exists($this, $method)) {
                $this->$method($value);
            }
        }
        return $this;
    }

    /**
     * Returns the current adapter, instantiating it if necessary
     *
     * @return string
     */
    public function getAdapter()
    {
        if ($this->_adapter instanceof Zend_Filter_Compress_CompressInterface) {
            return $this->_adapter;
        }

        $adapter = $this->_adapter;
        $options = $this->getAdapterOptions();
        if (!class_exists($adapter)) {

            if (Zend_Loader::isReadable('Zend/Filter/Compress/' . ucfirst($adapter) . '.php')) {
                $adapter = 'Zend_Filter_Compress_' . ucfirst($adapter);
            }
            Zend_Loader::loadClass($adapter);
        }

        $this->_adapter = new $adapter($options);
        if (!$this->_adapter instanceof Zend_Filter_Compress_CompressInterface) {

            throw new Zend_Filter_Exception("Compression adapter '" . $adapter . "' does not implement Zend_Filter_Compress_CompressInterface");
        }
        return $this->_adapter;
    }

    /**
     * Retrieve adapter name
     *
     * @return string
     */
    public function getAdapterName()
    {
        return $this->getAdapter()->toString();
    }

    /**
     * Sets compression adapter
     *
     * @param  string|Zend_Filter_Compress_CompressInterface $adapter Adapter to use
     * @return Zend_Filter_Compress
     */
    public function setAdapter($adapter)
    {
        if ($adapter instanceof Zend_Filter_Compress_CompressInterface) {
            $this->_adapter = $adapter;
            return $this;
        }
        if (!is_string($adapter)) {

            throw new Zend_Filter_Exception('Invalid adapter provided; must be string or instance of Zend_Filter_Compress_CompressInterface');
        }
        $this->_adapter = $adapter;

        return $this;
    }

    /**
     * Retrieve adapter options
     *
     * @return array
     */
    public function getAdapterOptions()
    {
        return $this->_adapterOptions;
    }

    /**
     * Set adapter options
     *
     * @param  array $options
     * @return void
     */
    public function setAdapterOptions(array $options)
    {
        $this->_adapterOptions = $options;
        return $this;
    }

    /**
     * Calls adapter methods
     *
     * @param string       $method  Method to call
     * @param string|array $options Options for this method
     */
    public function __call($method, $options)
    {
        $adapter = $this->getAdapter();
        if (!method_exists($adapter, $method)) {

            throw new Zend_Filter_Exception("Unknown method '{$method}'");
        }

        return call_user_func_array(array($adapter, $method), $options);
    }

    /**
     * Defined by Zend_Filter_Interface
     *
     * Compresses the content $value with the defined settings
     *
     * @param  string $value Content to compress
     * @return string The compressed content
     */
    public function filter($value)
    {
        return $this->getAdapter()->compress($value);
    }
}


<?php namespace Ordercloud\Entities\Products;

use JsonSerializable;
use Ordercloud\Entities\Organisations\OrganisationShort;

class ProductShort implements JsonSerializable
{
    /** @var integer */
    private $id;
    /** @var string */
    private $name;
    /** @var float */
    private $price;
    /** @var string */
    private $description;
    /** @var string */
    private $shortDescription;
    /** @var OrganisationShort */
    private $organisation;
    /** @var boolean */
    private $available;
    /** @var boolean */
    private $enabled;
    /** @var string */
    private $sku;
    /** @var boolean */
    private $availableOnline;
    /** @var ProductType */
    private $productType;
    /**
     * @var array|ProductShort[]
     * @reflectType Ordercloud\Entities\Products\ProductShort
     *
     * eg. meal => burger + chips + coke
     */
    private $groupItems;

    public function __construct($id, $name, $price, $description, $shortDescription, OrganisationShort $organisation, $available, $enabled, $sku, $availableOnline, ProductType $productType, array $groupItems)
    {
        $this->id = $id;
        $this->name = $name;
        $this->price = $price;
        $this->description = $description;
        $this->shortDescription = $shortDescription;
        $this->organisation = $organisation;
        $this->available = $available;
        $this->enabled = $enabled;
        $this->sku = $sku;
        $this->availableOnline = $availableOnline;
        $this->productType = $productType;
        $this->groupItems = $groupItems;
    }

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

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

    /**
     * @return float
     */
    public function getPrice()
    {
        return $this->price;
    }

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

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

    /**
     * @return OrganisationShort
     */
    public function getOrganisation()
    {
        return $this->organisation;
    }

    /**
     * @return boolean
     */
    public function isAvailable()
    {
        return $this->available;
    }

    /**
     * @return boolean
     */
    public function isEnabled()
    {
        return $this->enabled;
    }

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

    /**
     * @return boolean
     */
    public function isAvailableOnline()
    {
        return $this->availableOnline;
    }

    /**
     * @return ProductType
     */
    public function getProductType()
    {
        return $this->productType;
    }

    /**
     * @return array|ProductShort[]
     */
    public function getGroupItems()
    {
        return $this->groupItems;
    }

    /**
     * Specify data which should be serialized to JSON
     */
    public function jsonSerialize()
    {
        return [
            'id' => $this->getId(),
            'name' => $this->getName(),
            'price' => $this->getPrice(),
            'description' => $this->getDescription(),
            'shortDescription' => $this->getShortDescription(),
            'organisation' => $this->getOrganisation(),
            'available' => $this->isAvailable(),
            'enabled' => $this->isEnabled(),
            'sku' => $this->getSku(),
            'availableOnline' => $this->isAvailableOnline(),
            'productType' => $this->getProductType(),
            'groupItems' => $this->getGroupItems(),
        ];
    }
}


<?php namespace Ordercloud\Support\Http;

use League\Url\Url;

class LeagueUrlParameteriser implements UrlParameteriser
{
    /**
     * @param string $url
     * @param array  $parameters
     *
     * @return string
     */
    public function appendParametersToUrl(array $parameters, $url)
    {
        if (strpos($url, '//') === false) {
            $url = 'dummy.host/' . ltrim($url, '/');
        }

        $leagueUrl = Url::createFromUrl($url);

        $leagueUrl->getQuery()->modify($parameters);

        return $this->stripParameterArrayBrackets($leagueUrl->getRelativeUrl());
    }

    /**
     * @param string $leagueUrl
     *
     * @return string
     */
    private function stripParameterArrayBrackets($leagueUrl)
    {
        return preg_replace('/%5B\d+%5D/', '', $leagueUrl);
    }
}


<?php

namespace Priskz\SORAD\Routes\Laravel;

use Exception;
use Illuminate\Support\Facades\Route;

abstract class AbstractRoutes
{
    /**
     * @property string $prefix
     */
	protected static $prefix = null;

    /**
     * @property array $middleware
     */
	protected static $middleware = [];

    /**
     * @property array $nameSpace
     */
	protected static $namespace = null;

    /**
     * Register the route group.
     *
     * @return void
     */
	abstract protected static function register();

	/**
	 *	Load Routes
	 */
	public static function load(array $config = [])
	{
		// Set configuration values passed.
		static::setConfig($config);

		// Register the routes.
		static::register();
	}

    /**
     * Set route configuration values.
     *
     * @param  array $config
     * @return void
     */
	private static function setConfig(array $config)
	{
		// $prefix
		static::setPrefix($config);

		// $namespace
		static::setNamespace($config);

		// $middleware
		static::setMiddleware($config);
	}

    /**
     * Set static prefix value.
     *
     * @param  array $config
     * @return void
     */
	private static function setPrefix(array $config)
	{
		if(array_key_exists('prefix', $config))
		{
			static::$prefix = $config['prefix'];
		}

		// Route group prefix must be set or defined.
		if(is_null(static::$prefix))
		{
			throw new Exception(__CLASS__ . ': $prefix can not be null.');
		}
	}

    /**
     * Set static namespace value.
     *
     * @param  array $config
     * @return void
     */
	private static function setNamespace(array $config)
	{
		if(array_key_exists('namespace', $config))
		{
			static::$namespace = $config['namespace'];
		}

		// Route group prefix must be set or defined.
		if(is_null(static::$prefix))
		{
			throw new Exception(__CLASS__ . ': $namespace can not be null.');
		}
	}

    /**
     * Set static middlware value.
     *
     * @param  array $config
     * @return void
     */
	private static function setMiddleware(array $config)
	{
		if(array_key_exists('middleware', $config))
		{
			static::$middleware = $config['middleware'];
		}
	}
}


<?php
/**
 * Created by PhpStorm.
 * User: Bartosz Gołek
 * Date: 09.11.13
 * Time: 15:30
 *
 * @package    Conpago
 * @subpackage Helpers
 * @author     Bartosz Gołek <bartosz.golek@gmail.com>
 * @copyright  Copyright (c) 2015, Bartosz Gołek
 */

namespace Conpago\Helpers;

use Conpago\File\Contract\IFileSystem;
use Conpago\Helpers\Contract\IRequest;
use Conpago\Utils\ServerAccessor;

/**
 * Provides access to request properties.
 */
class Request implements IRequest
{

    /**
     * $_SERVER array operations access provider.
     * @var ServerAccessor
     */
    private $serverAccessor;

    /**
     * File system operations provider.
     * @var IFileSystem
     */
    private $fileSystem;

    /**
     * Creates
     *
     * @param ServerAccessor $serverAccessor Static $_SERVER array operations access provider.
     * @param IFileSystem    $fileSystem     File system operations provider.
     */
    public function __construct(ServerAccessor $serverAccessor, IFileSystem $fileSystem)
    {
        $this->serverAccessor = $serverAccessor;
        $this->fileSystem     = $fileSystem;
    }

    /**
     * Gets named http request value.
     *
     * @param string $name Name of property.
     *
     * @return mixed Value of property or null if not exists.
     */
    private function getValue($name)
    {
        if (!$this->serverAccessor->contains($name)) {
            return null;
        }

        return $this->serverAccessor->getValue($name);
    }

    /**
     * Gets http request method.
     *
     * @return string Http request method.
     */
    public function getRequestMethod()
    {
        return $this->getValue('REQUEST_METHOD');
    }

    /**
     * Gets http request path info.
     *
     * @return string Http request path info.
     */
    public function getPathInfo()
    {
        return $this->getValue('PATH_INFO');
    }

    /**
     * Gets http request query string.
     *
     * @return string Http request query string.
     */
    public function getQueryString()
    {
        return $this->getValue('QUERY_STRING');
    }

    /**
     * Gets http request content type.
     *
     * @return string Http request content type.
     */
    public function getContentType()
    {
        return $this->getValue('CONTENT_TYPE');
    }

    /**
     * Gets http request body.
     *
     * @return string Http request body.
     */
    public function getBody()
    {
        return $this->fileSystem->getFileContent('php://input');
    }

    /**
     * Get accept.
     *
     * @return string Returns accept header value.
     */
    public function getAccept()
    {
        return $this->getValue('ACCEPT');
    }
}


<?php
/**
 * This file is part of the CarteBlanche PHP framework.
 *
 * (c) Pierre Cassat <me@e-piwi.fr> and contributors
 *
 * License Apache-2.0 <http://github.com/php-carteblanche/carteblanche/blob/master/LICENSE>
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CarteBlanche\Controller;

use \CarteBlanche\CarteBlanche;
use \CarteBlanche\Abstracts\AbstractControllerCarteBlancheDefault;

/**
 * The default application controller
 *
 * @author  Piero Wbmstr <me@e-piwi.fr>
 */
class DefaultController
    extends AbstractControllerCarteBlancheDefault
{

    /**
     * The directory where to search the views files
     */
    static $views_dir = 'system/';

    /**
     * The home page of the controller
     *
     * @param   int     $offset   The offset used for the tables dump
     * @param   int     $limit    The limit used for the tables dump
     * @param   string  $table    The name of a table to isolate it
     * @param   mixed   $show     ??
     * @return  string            The home page view content
     */
    public function indexAction($offset = 0, $limit = 5, $table = null, $show = null)
    {
        return array(self::$views_dir.'hello', array(
            'altdb'=>$this->getContainer()->get('request')->getUrlArg('altdb'),
            'title' => $this->trans("Hello"),
        ));
    }

    /**
     * Page for uninstalled application
     *
     * @param string $altdb     The alternative database
     * @return string           The view content
     */
    public function emptyAction($altdb = 'default')
    {
        return array('empty', array(
            'altdb'=>$this->getContainer()->get('request')->getUrlArg('altdb'),
            'title' => $this->trans("System not installed"),
        ));
    }

    /**
     * Credits Page
     *
     * @return string The view content
     */
    public function creditsAction()
    {
        $_app = $this->getContainer()->get('config')->getRegistry()->dumpStack('app');
        return array(self::$views_dir.'credits', array(
            '_app' => !empty($_app['app']) ? $_app['app'] : array(),
            'title' => $this->trans("About"),
        ));
    }

    /**
     * Page of system check
     *
     * @return string The view content
     */
    public function check_systemAction()
    {
        $errs=$ctt=array();
        $sqlite=$php=null;
        $_altdb = $this->getContainer()->get('request')->getUrlArg('altdb');

        // directories ?
        $required_dirs = CarteBlanche::getConfig('carte_blanche.required_dirs', null, true);
        foreach ($required_dirs as $_dir) {
            $_fulldir = CarteBlanche::getPath($_dir);
            if ($ok_file = file_exists($_fulldir)) {
                $ctt[] = $this->trans('Directory "%dirname%" exists.', array('dirname'=>$_dir));
            } else {
                $errs[] = $this->trans('Directory "%dirname%" does not exist!', array('dirname'=>$_dir))
                     . $this->trans('Please create it manually.');
            }
        }

        $writable_dirs = CarteBlanche::getConfig('carte_blanche.writable_dirs', null, true);
        foreach ($writable_dirs as $_dir) {
            $_fulldir = CarteBlanche::getPath($_dir);
            if (!file_exists($_fulldir)) {
                $ok_file = mkdir($_fulldir);
            } else {
                $ok_file = true;
            }
            if ($ok_file) {
                if (is_dir($_fulldir) && is_writable($_fulldir)) {
                    $ctt[] = $this->trans('Directory "%dirname%" is writable.', array('dirname'=>$_dir));
                } else {
                    $errs[] = $this->trans('Directory "%dirname%" is not writable!', array('dirname'=>$_dir))
                        . $this->trans('Please authorize system\'s web user to write in it.');
                }
            } else {
                $errs[] = $this->trans('Directory "%dirname%" doesn\'t exist and can not be created!', array('dirname'=>$_dir))
                    . $this->trans('Please create it manually and authorize system\'s web user to write in it.');
            }
        }

        // PHP ?
        if (function_exists('phpversion')) {
            $ctt[] = $this->trans('PHP version: %version%', array('version'=>phpversion()));
        } else {
            $errs[] = $this->trans('Your PHP version is not enough. Please check the PHP manual.');
        }
        // SQLite ?
        if (function_exists('sqlite_libversion')) {
            $ctt[] = $this->trans('SQLite version: %version%', array('version'=>sqlite_libversion()));
        } else {
            $errs[] = $this->trans('SQLite is not installed. Please check the PHP manual.');
        }

        return array(self::$views_dir.'check_system', array(
            'title' => $this->trans("System checker"),
            'errors'=>$errs,
            'contents'=>$ctt
        ));
    }

    /**
     * Page of system installation
     *
     * @return string The view content
     */
    public function installAction()
    {
        $_altdb = $this->getContainer()->get('request')->getUrlArg('altdb');
        $SQLITE = $this->getContainer()->get('database');
        $tables = \CarteBlanche\Library\AutoObject\AutoObjectMapper::getObjectsStructure( $_altdb );
        if (!empty($tables)) {
            $installed = array();
            foreach ($tables as $table) {
                $err = $SQLITE->add_table( $table['table'], $table['structure'] );
                if (!$err) {
                    trigger_error( "An error occurred while creating table '{$table['table']}'!", E_USER_ERROR);
                }
                $installed[] = $table['table'];
            }
        }
        $this->getContainer()->get('session')
            ->setFlash("ok:".$this->trans('OK - Tables "%list%" created', array('list'=>join("', '", $installed))));
        $this->getContainer()->get('session')->commit();
        $this->getContainer()->get('router')->redirect(
            $this->getContainer()->get('router')->buildUrl('altdb',$_altdb)
        );
    }

    /**
     * Page of system errors
     *
     * @param   null|array  $errors
     * @return  array
     */
    public function bootErrorAction(array $errors = null)
    {
        $session = $this->getContainer()->get('session');
        $original_errors = $session->has('boot_errors') ? $session->get('boot_errors') : $errors;
        $running_user = $this->getKernel()->whoAmI();

        return array(self::$views_dir.'errors', array(
            'title'=>$this->trans('System errors'),
            'original_errors'=>$original_errors,
            'running_user' => $running_user,
            'errors'=>$errors
        ));
    }

    /**
     * Test content page
     *
     * @param   string  $type
     * @return  string  A "lorem ipsum" content
     */
    public function loremIpsumAction($type = 'html')
    {
        $view = $type==='text' ? 'lorem_ipsum.txt' : 'lorem_ipsum.html';
        return array($view, array(
            'title'=>'Lorem Ipsum'
        ));
    }

}

// Endfile


<?php
/**
 * This file is part of the Hephaistos project management API.
 *
 * As each files provides by the CSCFA, this file is licensed
 * under the MIT license.
 *
 * PHP version 5.6
 *
 * @category Trait
 * @package  Hephaistos
 * @author   matthieu vallance <matthieu.vallance@cscfa.fr>
 * @license  MIT <https://opensource.org/licenses/MIT>
 * @link     http://cscfa.fr
 */
namespace CSDT\CollectionsBundle\CollectionHelper\HelperTrait;

use CSDT\CollectionsBundle\CollectionInterfaces\CollectionInterface;

/**
 * Helper sub trait
 *
 * This trait define the logic of the Helper
 * partitioning support.
 *
 * @category Trait
 * @package  Hephaistos
 * @author   matthieu vallance <matthieu.vallance@cscfa.fr>
 * @license  MIT <https://opensource.org/licenses/MIT>
 * @link     http://cscfa.fr
 */
trait HelperSubTrait
{

    /**
     * Sub collection
     *
     * Return a Collection that contain a part
     * of the $collection starting at an integer
     * index and for the given length. Th content
     * will be truncated if the length is superior
     * of the real collection length. Note you are
     * able to use it with a map collection.
     *
     * @param CollectionInterface $collection The collection where find the content
     * @param number              $start      The start index
     * @param integer             $length     The length of the result collection
     *                                        content
     *
     * @throws \ParseError if the caster manager is not able to parse the
     *                     array to the first collection
     * @return CollectionInterface
     */
    public function subCollection(
        CollectionInterface $collection,
        $start = 0,
        $length = null
    ) {
        $content = $collection->toArray();

        $resultContent = array_slice($content, $start, $length, true);

        return $this->arrayToCollection($resultContent, get_class($collection));
    }

    /**
     * Sub map
     *
     * Return a Collection that contain a part
     * of the $collection corresponding to the
     * to the given $keys. Note you are able to
     * use it with any collection.
     *
     * @param CollectionInterface $collection The collection where
     *                                        find the content
     * @param array               $keys       The keys to return
     *
     * @throws \ParseError if the caster manager is not able to parse the
     *                     array to the first collection
     * @return CollectionInterface
     */
    public function subMap(
        CollectionInterface $collection,
        array $keys
    ) {
        $content = $collection->toArray();

        $resultContent = array_intersect_key($content, array_flip($keys));

        return $this->arrayToCollection($resultContent, get_class($collection));
    }

}


<?php

namespace Gwsn\Prismic\Models\Dom;

class Link
{
    /**
     * Returns the URL we're linking to.
     * The linkResolver will be needed in case the link is a document link.
     * Read more about the link resolver at https://prismic.io/docs/php/beyond-the-api/link-resolving
     *
     *
     * @param object                $link           The document link
     * @param \Gwsn\Prismic\Models\LinkResolver $linkResolver   The link resolver
     *
     * @return string|null The URL of the resource we're linking to online
     */
    public static function asUrl($link, $linkResolver = null)
    {
        if ($link->link_type === 'Document') {
            return $linkResolver ? $linkResolver($link) : null;
        }

        return property_exists($link, 'url') ? $link->url : null;
    }
}


<?php

namespace Reaction\Helpers;

use Reaction\Base\Arrayable;
use Reaction\Exceptions\InvalidValueException;

/**
 * VarDumper is intended to replace the buggy PHP function var_dump and print_r.
 * It can correctly identify the recursively referenced objects in a complex
 * object structure. It also has a recursive depth control to avoid indefinite
 * recursive display of some peculiar variables.
 *
 * VarDumper can be used as follows,
 *
 * ```php
 * VarDumper::dump($var);
 * ```
 */
class VarDumper
{
    private static $_objects;
    private static $_output;
    private static $_depth;
    private static $_serializer;

    /**
     * Displays a variable.
     * This method achieves the similar functionality as var_dump and print_r
     * but is more robust when handling complex objects such as Yii controllers.
     * @param mixed $var variable to be dumped
     * @param int $depth maximum depth that the dumper should go into the variable. Defaults to 10.
     * @param bool $highlight whether the result should be syntax-highlighted
     */
    public static function dump($var, $depth = 10, $highlight = false)
    {
        echo static::dumpAsString($var, $depth, $highlight);
    }

    /**
     * Dumps a variable in terms of a string.
     * This method achieves the similar functionality as var_dump and print_r
     * but is more robust when handling complex objects such as Yii controllers.
     * @param mixed $var variable to be dumped
     * @param int $depth maximum depth that the dumper should go into the variable. Defaults to 10.
     * @param bool $highlight whether the result should be syntax-highlighted
     * @return string the string representation of the variable
     */
    public static function dumpAsString($var, $depth = 10, $highlight = false)
    {
        self::$_output = '';
        self::$_objects = [];
        self::$_depth = $depth;
        self::dumpInternal($var, 0);
        if ($highlight) {
            $result = highlight_string("<?php\n" . self::$_output, true);
            self::$_output = preg_replace('/<\\?php<br \\/>/', '', $result, 1);
        }

        return self::$_output;
    }

    /**
     * @param mixed $var variable to be dumped
     * @param int $level depth level
     */
    private static function dumpInternal($var, $level)
    {
        switch (gettype($var)) {
            case 'boolean':
                self::$_output .= $var ? 'true' : 'false';
                break;
            case 'integer':
                self::$_output .= (string)$var;
                break;
            case 'double':
                self::$_output .= (string)$var;
                break;
            case 'string':
                self::$_output .= "'" . addslashes($var) . "'";
                break;
            case 'resource':
                self::$_output .= '{resource}';
                break;
            case 'NULL':
                self::$_output .= 'null';
                break;
            case 'unknown type':
                self::$_output .= '{unknown}';
                break;
            case 'array':
                if (self::$_depth <= $level) {
                    self::$_output .= '[...]';
                } elseif (empty($var)) {
                    self::$_output .= '[]';
                } else {
                    $keys = array_keys($var);
                    $spaces = str_repeat(' ', $level * 4);
                    self::$_output .= '[';
                    foreach ($keys as $key) {
                        self::$_output .= "\n" . $spaces . '    ';
                        self::dumpInternal($key, 0);
                        self::$_output .= ' => ';
                        self::dumpInternal($var[$key], $level + 1);
                    }
                    self::$_output .= "\n" . $spaces . ']';
                }
                break;
            case 'object':
                if (($id = array_search($var, self::$_objects, true)) !== false) {
                    self::$_output .= get_class($var) . '#' . ($id + 1) . '(...)';
                } elseif (self::$_depth <= $level) {
                    self::$_output .= get_class($var) . '(...)';
                } else {
                    $id = array_push(self::$_objects, $var);
                    $className = get_class($var);
                    $spaces = str_repeat(' ', $level * 4);
                    self::$_output .= "$className#$id\n" . $spaces . '(';
                    if ('__PHP_Incomplete_Class' !== get_class($var) && method_exists($var, '__debugInfo')) {
                        $dumpValues = $var->__debugInfo();
                        if (!is_array($dumpValues)) {
                            throw new InvalidValueException('__debuginfo() must return an array');
                        }
                    } else {
                        $dumpValues = (array) $var;
                    }
                    foreach ($dumpValues as $key => $value) {
                        $keyDisplay = strtr(trim($key), "\0", ':');
                        self::$_output .= "\n" . $spaces . "    [$keyDisplay] => ";
                        self::dumpInternal($value, $level + 1);
                    }
                    self::$_output .= "\n" . $spaces . ')';
                }
                break;
        }
    }

    /**
     * Exports a variable as a string representation.
     *
     * The string is a valid PHP expression that can be evaluated by PHP parser
     * and the evaluation result will give back the variable value.
     *
     * This method is similar to `var_export()`. The main difference is that
     * it generates more compact string representation using short array syntax.
     *
     * It also handles objects by using the PHP functions serialize() and unserialize().
     *
     * PHP 5.4 or above is required to parse the exported value.
     *
     * @param mixed $var the variable to be exported.
     * @return string a string representation of the variable
     */
    public static function export($var)
    {
        self::$_output = '';
        self::exportInternal($var, 0);
        return self::$_output;
    }

    /**
     * @param mixed $var variable to be exported
     * @param int $level depth level
     */
    private static function exportInternal($var, $level)
    {
        switch (gettype($var)) {
            case 'NULL':
                self::$_output .= 'null';
                break;
            case 'array':
                if (empty($var)) {
                    self::$_output .= '[]';
                } else {
                    $keys = array_keys($var);
                    $outputKeys = ($keys !== range(0, count($var) - 1));
                    $spaces = str_repeat(' ', $level * 4);
                    self::$_output .= '[';
                    foreach ($keys as $key) {
                        self::$_output .= "\n" . $spaces . '    ';
                        if ($outputKeys) {
                            self::exportInternal($key, 0);
                            self::$_output .= ' => ';
                        }
                        self::exportInternal($var[$key], $level + 1);
                        self::$_output .= ',';
                    }
                    self::$_output .= "\n" . $spaces . ']';
                }
                break;
            case 'object':
                if ($var instanceof \Closure) {
                    self::$_output .= self::exportClosure($var);
                } else {
                    try {
                        $output = 'unserialize(' . var_export(serialize($var), true) . ')';
                    } catch (\Exception $e) {
                        // serialize may fail, for example: if object contains a `\Closure` instance
                        // so we use a fallback
                        if ($var instanceof Arrayable) {
                            self::exportInternal($var->toArray(), $level);
                            return;
                        } elseif ($var instanceof \IteratorAggregate) {
                            $varAsArray = [];
                            foreach ($var as $key => $value) {
                                $varAsArray[$key] = $value;
                            }
                            self::exportInternal($varAsArray, $level);
                            return;
                        } elseif ('__PHP_Incomplete_Class' !== get_class($var) && method_exists($var, '__toString')) {
                            $output = var_export($var->__toString(), true);
                        } else {
                            $outputBackup = self::$_output;
                            $output = var_export(self::dumpAsString($var), true);
                            self::$_output = $outputBackup;
                        }
                    }
                    self::$_output .= $output;
                }
                break;
            default:
                self::$_output .= var_export($var, true);
        }
    }

    /**
     * Exports a [[Closure]] instance.
     * @param \Closure $closure closure instance.
     * @return string
     */
    private static function exportClosure(\Closure $closure)
    {
        $reflection = new \ReflectionFunction($closure);

        $fileName = $reflection->getFileName();
        $start = $reflection->getStartLine();
        $end = $reflection->getEndLine();

        if ($fileName === false || $start === false || $end === false) {
            return 'function() {/* Error: unable to determine Closure source */}';
        }

        --$start;

        $source = implode("\n", array_slice(file($fileName), $start, $end - $start));
        $tokens = token_get_all('<?php ' . $source);
        array_shift($tokens);

        $closureTokens = [];
        $pendingParenthesisCount = 0;
        foreach ($tokens as $token) {
            if (isset($token[0]) && $token[0] === T_FUNCTION) {
                $closureTokens[] = $token[1];
                continue;
            }
            if ($closureTokens !== []) {
                $closureTokens[] = isset($token[1]) ? $token[1] : $token;
                if ($token === '}') {
                    $pendingParenthesisCount--;
                    if ($pendingParenthesisCount === 0) {
                        break;
                    }
                } elseif ($token === '{') {
                    $pendingParenthesisCount++;
                }
            }
        }

        return implode('', $closureTokens);
    }

    /**
     * Serialize any data
     * @param mixed $data
     * @return string
     * @see VarDumper::unserialize()
     */
    public static function serialize($data)
    {
        return static::getSerializer()->serialize($data);
    }

    /**
     * Unserialize string previously serialized with VarDumper::serialize()
     * @param string $dataStr
     * @return mixed
     * @see VarDumper::serialize()
     */
    public static function unserialize($dataStr)
    {
        return static::getSerializer()->unserialize($dataStr);
    }

    /**
     * Get serializer instance
     * @return \Zumba\JsonSerializer\JsonSerializer
     * @see VarDumper::serialize()
     * @see VarDumper::unserialize()
     */
    private static function getSerializer()
    {
        if (!isset(static::$_serializer)) {
            $superClosure = new \SuperClosure\Serializer();
            static::$_serializer = new \Zumba\JsonSerializer\JsonSerializer($superClosure);
        }
        return static::$_serializer;
    }
}


<?php

namespace KsUtils;

/**
 * File utils
 */
class File
{
    /**
     * Returns new version of filename. abc.2.ext -> abc.3.ext; abc.4 -> abc.5
     * abc -> abc.1
     * @param  string $filename Old version of filename
     * @return New    version of filename
     */
    public function incrVersion($filename)
    {
        $pat = "|^\d+$|";

        $parts = explode(".", $filename);
        $partsCount = count($parts);

        if ($partsCount == 1) {
            return $filename . ".1";
        }

        if ($partsCount == 2) {
            if (preg_match($pat, $parts[1])) {
                return $parts[0] . "." . ++$parts[1];
            }

            return $parts[0] . ".1." . $parts[1];
        }

        if (preg_match($pat, $parts[$partsCount - 1])) {
            return implode(".", array_slice($parts, 0, -1)) . "." . ++$parts[$partsCount - 1];
        }

        if (preg_match($pat, $parts[$partsCount - 2])) {
            return implode(
                ".",
                array_slice($parts, 0, -2)
            )
            . "." . ++$parts[$partsCount - 2]
            . "." . $parts[$partsCount - 1];
        }

        return implode(".", array_slice($parts, 0, -1)) . ".1." . $parts[$partsCount - 1];
    }
}


<?php

namespace Ekyna\Bundle\CoreBundle\Form\DataTransformer;

use Doctrine\Common\Persistence\ObjectRepository;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Symfony\Component\Form\Exception\UnexpectedTypeException;
use Symfony\Component\PropertyAccess\PropertyAccess;

/**
 * Class ObjectToIdentifierTransformer
 * @package Ekyna\Bundle\CoreBundle\Form\DataTransformer
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
class ObjectToIdentifierTransformer implements DataTransformerInterface
{
    /**
     * Repository
     *
     * @var ObjectRepository
     */
    protected $repository;

    /**
     * Identifier
     *
     * @var string
     */
    protected $identifier;

    /**
     * Constructor.
     *
     * @param ObjectRepository $repository
     * @param string           $identifier
     */
    public function __construct(ObjectRepository $repository = null, $identifier = 'id')
    {
        $this->repository = $repository;
        $this->identifier = $identifier;
    }

    /**
     * Sets the repository.
     *
     * @param ObjectRepository $repository
     * @return ObjectToIdentifierTransformer
     */
    public function setRepository(ObjectRepository $repository)
    {
        $this->repository = $repository;
        return $this;
    }

    /**
     * Sets the identifier.
     *
     * @param string $identifier
     * @return ObjectToIdentifierTransformer
     */
    public function setIdentifier($identifier)
    {
        $this->identifier = $identifier;
        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function transform($value)
    {
        if (null === $value) {
            return '';
        }

        $class = $this->repository->getClassName();

        if (!$value instanceof $class) {
            throw new UnexpectedTypeException($value, $class);
        }

        $accessor = PropertyAccess::createPropertyAccessor();

        return $accessor->getValue($value, $this->identifier);
    }

    /**
     * {@inheritdoc}
     */
    public function reverseTransform($value)
    {
        if (!$value) {
            return null;
        }

        if (null === $entity = $this->repository->findOneBy([$this->identifier => $value])) {
            throw new TransformationFailedException(sprintf(
                'Object "%s" with identifier "%s"="%s" does not exist.',
                $this->repository->getClassName(),
                $this->identifier,
                $value
            ));
        }

        return $entity;
    }
}


<?php namespace RestGalleries\Http;

use RestGalleries\Http\ResponseAdapter;

/**
 * This class receives the http response from the http client, processes it and returns the data in an orderly manner..
 */
abstract class Response implements ResponseAdapter
{
    /**
     * Stores the body of the Http response.
     *
     * @var string
     */
    protected $body;

    /**
     * Here will be stored the Http response headers array.
     *
     * @var array
     */
    protected $headers = [];

    /**
     * Stores status code as integer of the Http response.
     *
     * @var integer
     */
    protected $statusCode;

    /**
     * Initializes processing of response.
     *
     * @param  object $data
     * @return void
     */
    public function __construct($data)
    {
        $this->processResponseData($data);
    }

    /**
     * Process the http client response and separates it into variables.
     *
     * @param  object $raw
     * @return void
     */
    abstract protected function processResponseData($raw);

    /**
     * Returns the xml|json as string, array or object.
     *
     * @return string|array|object
     */
    public function getBody($format = 'object')
    {
        if (! $this->isValidBodyFormat($format)) {
            return;
        }

        $method = 'body' . ucfirst($format);

        return call_user_func_array([$this, $method], [null]);

    }

    /**
     * Checks if a string matches some type of specified variable.
     *
     * @param  string $format
     * @return boolean
     */
    protected function isValidBodyFormat($format)
    {
        $formats = ['string', 'array', 'object'];

        if (! in_array($format, $formats)) {
            return false;
        }

        return true;

    }

    /**
     * Returns body string (xml or json) without changes.
     *
     * @return string
     */
    protected function bodyString()
    {
        return $this->body;
    }

    /**
     * It return the xml|json as an array.
     *
     * @return array
     */
    protected function bodyArray()
    {
        if (is_xml($this->body)) {
            return xml_decode($this->body, true);
        }

        if (is_json($this->body)) {
            return json_decode($this->body, true);
        }

    }

    /**
     * It return the xml|json as an object.
     *
     * @return array
     */
    protected function bodyObject()
    {
        if (is_xml($this->body)) {
            return xml_decode($this->body);
        }

        if (is_json($this->body)) {
            return json_decode($this->body);
        }

    }

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

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

}


<?php

namespace QCharts\CoreBundle\Service;

use Doctrine\ORM\EntityRepository;
use QCharts\CoreBundle\Entity\QueryRequest;
use QCharts\CoreBundle\Entity\User\QChartsSubjectInterface;
use QCharts\CoreBundle\Exception\DatabaseException;
use QCharts\CoreBundle\Exception\InstanceNotFoundException;
use QCharts\CoreBundle\Exception\OffLimitsException;
use QCharts\CoreBundle\Exception\ParameterNotPassedException;
use QCharts\CoreBundle\Exception\TypeNotValidException;
use QCharts\CoreBundle\Exception\ValidationFailedException;
use QCharts\CoreBundle\Exception\OverlappingException;
use QCharts\CoreBundle\Repository\DynamicRepository;
use QCharts\CoreBundle\Repository\QueryRepository;
use QCharts\CoreBundle\Service\ServiceInterface\QueryServiceInterface;
use Doctrine\DBAL\DBALException;
use Symfony\Bridge\Doctrine\RegistryInterface;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormInterface;
use \SqlFormatter;
use Symfony\Component\HttpFoundation\ParameterBag;

class QueryService implements QueryServiceInterface
{

    /** @var QueryRepository $repository */
    private $repository = null;
    /** @var \QCharts\CoreBundle\Service\QueryValidatorService|null s */
    private $queryValidator = null;
    /** @var null|DynamicRepository $dynamicRepo */
    private $dynamicRepo = null;

    /**
     * QueryService constructor.
     * @param EntityRepository $repo
     * @param DynamicRepository $dynamicRepository
     * @param QueryValidatorService $val
     */
    public function __construct(
        EntityRepository $repo,
        DynamicRepository $dynamicRepository,
        QueryValidatorService $val
        )
	{
        $this->repository = $repo;
        $this->dynamicRepo = $dynamicRepository;
        $this->queryValidator = $val;
    }

    /**
     * @return null|QueryValidatorService
     */
    public function getQueryValidator()
    {
        return $this->queryValidator;
    }

    /**
     * Returns all queries ordered by date
     * @return array
     */
    public function getAllQueries()
    {
        $allQueries = $this->repository->findAllOrderedByDateCreated();
        return $allQueries;
    }

    /**
     * @return array
     */
    public function getPreFetchedQueries()
    {
        return $this->repository->getCachedQueries();
    }

    /**
     * @return array
     */
    public function getTimeMachinedQueries()
    {
        return $this->repository->getTimeMachineQueries();
    }

    /**
     * @param null $queryId
     * @return array|QueryRequest
     * @throws InstanceNotFoundException
     */
    public function getQueries($queryId = null)
    {
        if (is_null($queryId) || $queryId < 0)
        {
            //return all
            $queryRequest = $this->getAllQueries();
        }
        else
        {
            $queryRequest = $this->getQueryRequestById($queryId);
        }
        return $queryRequest;
    }

    /**
     * @param number $id
     * @return QueryRequest
     * @throws InstanceNotFoundException
     */
    public function getQueryRequestById($id)
    {
        if (is_null($id))
        {
            throw new InstanceNotFoundException("No valid Id was given or found", 404);
        }

        /** @var QueryRequest $query */
        $query = $this->repository->find($id);

        if (!$query)
        {
            throw new InstanceNotFoundException("Requested Query not found", 404);
        }
        return $query;
    }

    /**
     * @param $id
     * @return mixed
     * @throws InstanceNotFoundException
     */
    public function getQueryFromQueryRequest($id)
    {
    	$query = $this->getQueryRequestById($id);
    	return $query->getQuery();
    }

    /**
     * @param null $directoryId
     * @return array
     */
    public function getQueriesInDirectory($directoryId = null)
    {
        $queries = $this->repository->getQueriesInDirectory($directoryId);
        return $queries;
    }

    /**
     * @param Form $form
     * @param QChartsSubjectInterface $user
     * @return array
     * @throws OffLimitsException
     * @throws ParameterNotPassedException
     * @throws TypeNotValidException
     * @throws ValidationFailedException
     */
    public function add(Form $form, QChartsSubjectInterface $user)
    {
        /** @var QueryRequest $queryRequest */
        /** @var Form $form */

        $queryRequest = $form->getData();
        $queryRequest->setCreatedBy($user);
        $queryRequest->setModifiedLastBy($user);

        $query = $queryRequest->getQuery();
        $chartConfig = $queryRequest->getConfig();

        $rawQueryString = $query->getQuery();
        $htmlQuery = SqlFormatter::format($rawQueryString);
        $query->setQueryHTML($htmlQuery);
        $results = [];

        try
        {
            $this->queryValidator->isValidQuery($rawQueryString, $chartConfig->getDatabaseConnection());

            $configuration = [
                "time"=>$chartConfig->getExecutionLimit(),
                "rows"=>$chartConfig->getQueryLimit(),
                "chartType"=>$chartConfig->getTypeOfChart(),
                "offset"=>$chartConfig->getOffset(),
                "connection"=>$chartConfig->getDatabaseConnection(),
                "cronExpression"=>$queryRequest->getCronExpression()
            ];

            $results = $this->queryValidator->validateQueryExecution($rawQueryString, $configuration);

            $queryRequest->setQuery($query);
            $queryRequest->setConfig($chartConfig);

            $this->repository->save($queryRequest, $query, $chartConfig);

            return [
                "results" => $results,
                "query" => $queryRequest
            ];
        }
        catch (OffLimitsException $e)
        {
            //process default values
            $limit = $this->queryValidator->getMaxRows($chartConfig->getQueryLimit());
            $timeLimit = $this->queryValidator->getMaxTime($chartConfig->getExecutionLimit(), $chartConfig->getDatabaseConnection());
            $offset = 0;

            $chartConfig->setExecutionLimit($timeLimit);
            $chartConfig->setQueryLimit($limit);
            $chartConfig->setOffset($offset);

            $queryRequest->setQuery($query);
            $queryRequest->setConfig($chartConfig);

            $this->repository->save($queryRequest, $query, $chartConfig);

            $exception = new OffLimitsException("One of the limits were off limits, default ones were applied", $e->getCode(), $e);
            $exception->setData(["query" => $queryRequest, "results" => $results]);
            throw $exception;
        }
        catch (ParameterNotPassedException $e)
        {
            throw $e;
        }
        catch (TypeNotValidException $e)
        {
            throw $e;
        }
        catch (ValidationFailedException $e)
        {
            throw $e;
        }

    }

    /**
     * @param FormInterface $form
     * @param QChartsSubjectInterface $user
     * @param $queryId
     * @return array
     * @throws DatabaseException
     * @throws OffLimitsException
     * @throws ValidationFailedException
     * @throws OverlappingException
     */
    public function edit(FormInterface $form, QChartsSubjectInterface $user, $queryId)
    {
        /** @var QueryRequest $queryRequest */
        /** @var Form $form */
    	$queryRequest = $form->getData();
    	$query = $queryRequest->getQuery();
    	$config = $queryRequest->getConfig();

		try
        {
            $queryRequest->setModifiedLastBy($user);

            $rawQueryString = $query->getQuery();
            $query->setQueryHTML(\SqlFormatter::format($rawQueryString));

            $this->queryValidator->isValidQuery($rawQueryString, $config->getDatabaseConnection());

            $configuration = [
                "rows"=>$config->getQueryLimit(),
                "time"=>$config->getExecutionLimit(),
                "chartType"=>$config->getTypeOfChart(),
                "offset"=>$config->getOffset(),
                "connection"=>$config->getDatabaseConnection(),
                "cronExpression"=>$queryRequest->getCronExpression()
            ];

            $results = $this->queryValidator->validateQueryExecution($rawQueryString, $configuration);

            $queryRequest->setConfig($config);
            $queryRequest->setQuery($query);

            $this->repository->update($queryRequest);

            return [
                "query" => $queryRequest,
                "results" => $results
            ];
		}
        catch (OffLimitsException $e)
        {
            // set the default values
            $limit = $this->queryValidator->getMaxRows($config->getQueryLimit());
            $config->setQueryLimit($limit);
            $offset = 0;
            $config->setOffset($offset);
            $timeLimit = $this->queryValidator->getMaxTime($config->getExecutionLimit(), $config->getDatabaseConnection());
            $config->setExecutionLimit($timeLimit);

            $queryRequest->setConfig($config);
            $queryRequest->setQuery($query);

            $this->repository->update($queryRequest);

            throw new OffLimitsException("One of the limits were off limit, their respective default value were used", 200, $e);
        }
        catch (ValidationFailedException $e)
        {
			throw $e;
		}
    }

    /**
     * @param $queryId
     * @throws InstanceNotFoundException
     * @throws ParameterNotPassedException
     */
    public function delete($queryId)
    {
        /** @var QueryRequest $queryRequest */
    	$queryRequest = $this->getQueryRequestById($queryId);
    	$this->deleteQuery($queryRequest);
    }

    /**
     * @param QueryRequest $queryRequest
     * @throws ParameterNotPassedException
     */
    public function deleteQuery(QueryRequest $queryRequest)
    {
    	if (!$queryRequest)
        {
            throw new ParameterNotPassedException('The given Query was not valid', 500);
        }
    	$this->repository->deleteQuery($queryRequest);
    }

    /**
     * @return array
     */
    public function getConnections()
    {
        return $this->dynamicRepo->getConnectionNames();
    }

    /**
     * @param string $connectionName
     * @return array
     */
    public function getSchemas($connectionName = "default")
    {
        $this->queryValidator->validateConnection($connectionName);
        $this->dynamicRepo->setUp($connectionName);

        return $this->dynamicRepo->getSchemaNames();
    }

    /**
     * @param string $connectionName
     * @param string $schemaName
     * @return array
     */
    public function getTableNames($schemaName, $connectionName = "default")
    {
        $this->queryValidator->validateConnection($connectionName);
        $this->dynamicRepo->setUp($connectionName);

        return $this->dynamicRepo->getTableNamesOfSchema($schemaName);
    }

    /**
     * @param ParameterBag $parameterBag
     * @return array
     * @throws InstanceNotFoundException
     * @throws ParameterNotPassedException
     */
    public function getTableInformation(ParameterBag $parameterBag)
    {
        $tableName = $parameterBag->get('tableName', '');
        $connectionName = $parameterBag->get('connection', 'default');

        if ($tableName == '')
        {
            throw new ParameterNotPassedException("Table Name was not passed", 404);
        }

        $this->queryValidator->validateConnection($connectionName);
        $this->dynamicRepo->setUp($connectionName);
        return $this->dynamicRepo->getColumnNamesFromTable($tableName);
    }

    /**
     * Calls the dynamic repository and calls the results from the query
     *
     * @param $query
     * @param int $limit
     * @param string $connection
     * @return array
     * @throws DatabaseException
     * @throws ParameterNotPassedException
     * @throws ValidationFailedException
     * @throws \Exception
     */
    public function getResultsFromQuery($query, $limit = 0, $connection='default')
    {
        try
        {
            $this->queryValidator->isValidQuery($query, $connection);

            $query = $this->queryValidator->getLimitedQuery($query, $limit);

            $this->dynamicRepo->setUp($connection);
            $res = $this->dynamicRepo->execute($query);

            $duration = $this->dynamicRepo->getExecutionDuration();
            $duration = number_format($duration, 7, '.', ',');

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

}


<?php
/*
 * This file is part of the Skeetr package.
 *
 * (c) Máximo Cuadros <mcuadros@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Skeetr\Client\HTTP;

use http\Cookie;
use http\Header;
use http\Message;
use http\Message\Body;
use Skeetr\Runtime\Manager;

class Response extends Message
{
    public function __construct()
    {
        parent::__construct();
        $this->setType(Message::TYPE_RESPONSE);
    }

    /**
     * Sets the default server and content type headers and response code if
     * not is setted allready.
     */
    public function setDefaults()
    {
        if ( !$this->getResponseCode() ) $this->setResponseCode(200);
        if ( !$this->getContentType() ) $this->setContentType('text/html');
        if ( !$this->getServer() ) $this->setServer('Skeetr 0.0.1');
    }

    /**
     * Return a new instance of Response with the headers and response code retuned by
     * Skeetr\Runtime\Manager::value() method
     *
     * @return Response
     */
    public static function fromRuntime()
    {
        $response = new static();

        $values = Manager::values();

        $response->setResponseCode($values['header']['code']);
        $response->setHeaders($values['header']['list'], true);

        return $response;
    }

    /**
     * Sets the headers.
     *
     * @param  array   $headers associative array containing the new HTTP headers
     * @return boolean Returns TRUE on success or FALSE on failure.
     */
    public function setHeaders(array $headers)
    {
        return $this->addHeaders($headers, false);
    }

    /**
     * Add headers. If append is true, headers with the same name will be separated,
     * else overwritten.
     *
     * @param array $headers associative array containing the new HTTP headers
     * @param array $append  if true, and a header with the same name of one to add exists
     *                      already, this respective header will be converted to an array
     *                      containing both header values, otherwise it will be
     *                      overwritten with the new header value
     * @return boolean Returns TRUE on success or FALSE on failure.
     */
    public function addHeaders(array $headers, $append = null)
    {
        $data = array();
        foreach ($headers as $header => $value) {
            if ( is_array($value) ) {
                foreach($value as $val) $data[$header] = $val;
            } else {
                $data[$header] = (string) $value;
            }
        }

        return parent::addHeaders($data, $append);
    }

    /**
     * Add headers. If append is true, headers with the same name will be separated,
     * else overwritten.
     *
     * @param string $header just a string with the header
     * @param array  $append if true, and a header of the same type allready exists will
     *                      append, if false will be replaced.
     * @return boolean Returns TRUE on success or FALSE on failure.
     */
    public function addHeader($header, $append = false)
    {
        if ( !$headers = Header::parse($header) ) return false;
        return $this->addHeaders($headers, $append);
    }

    /**
     * Set the response code of an HTTP Response Message.
     *
     * @param  integer $code HTTP response code
     * @return mixed   Returns TRUE on success or the response code is out of range (100-510).
     */
    public function setResponseCode($code, $strict = null)
    {
        return parent::setResponseCode((int) $code);
    }

    /**
     * Set message body
     *
     * @param  string  $body the new body of the message
     * @return boolean Returns TRUE on success or FALSE on failure.
     */
    public function setBody(Body $body)
    {
        parent::setBody($body);

        return $this->addHeaders(array(
            'Content-Length' => (string) strlen($this->body)
        ), true);
    }

    /**
     * Set content type
     *
     * @param  string  $contentType the content type of the sent entity
     * @return boolean Returns TRUE on success or FALSE on failure.
     */
    public function setContentType($contentType)
    {
        return parent::addHeaders(array(
            'Content-Type' => $contentType
        ), false);
    }

    /**
     * Set server name and version
     *
     * @param  string  $server
     * @return boolean Returns TRUE on success or FALSE on failure.
     */
    public function setServer($server)
    {
        return $this->addHeaders(array(
            'Server' => $server
        ), false);
    }

    /**
     * Defines a cookie to be sent along with the rest of the HTTP headers.
     *
     * @param  string  $name     The name of the cookie.
     * @param  string  $value    The value of the cookie.
     * @param  integer $expire   (optional) The time the cookie expires. This is a Unix timestamp
     * @param  string  $path     (optional) The path on the server in which the cookie will be available on.
     * @param  string  $domain   (optional) The domain that the cookie is available to.
     * @param  boolean $secure   (optional) Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client.
     * @param  boolean $httpOnly (optional) When TRUE the cookie will be made accessible only through the HTTP protocol.
     * @return boolean Returns TRUE on success or FALSE on failure.
     */
    public function setCookie(
        $name, $value, $expire = 0,  $path = null,
        $domain = null, $secure = false, $httpOnly = false
    ) {

        $cookie = new Cookie();
        $cookie->addCookie($name, $value);
        $cookie->setExpires($expire);
        $cookie->setPath($path);
        $cookie->setDomain($domain);

        $flags = 0;
        if ($secure) {
            $flags = Cookie::SECURE;
        }

        if ($httpOnly) {
            $flags = $flags | Cookie::HTTPONLY;
        }

        $cookie->setFlags($flags);

        return $this->addHeaders(array(
            'Set-Cookie' => $cookie->toString()
        ), true);
    }

    /**
     * Get headers
     *
     * @return array
     */
    public function getHeaders()
    {
        return parent::getHeaders();
    }

    /**
     * Get a header by name
     *
     * @param  string $header
     * @return string
     */
    public function getHeader($header, $infoClass = null)
    {
        return parent::getHeader($header);
    }

    /**
     * Get the Response Code of the Message.
     *
     * @return string
     */
    public function getResponseCode()
    {
        return parent::getResponseCode();
    }

    /**
     * Get message body
     *
     * @return string
     */
    public function getBody()
    {
        return parent::getBody();
    }

    /**
     * Get content type
     *
     * @return string
     */
    public function getContentType()
    {
        return parent::getHeader('Content-Type');
    }

    /**
     * Get content length
     *
     * @return integer
     */
    public function getContentLength()
    {
        return (int) parent::getHeader('Content-Length');
    }

    /**
     * Get server name
     *
     * @return string
     */
    public function getServer()
    {
        return parent::getHeader('Server');
    }

    /**
     * Get cookies
     *
     * @return array
     */
    public function getCookies()
    {
        $cookies = parent::getHeader('Set-Cookie');

        if ( !$cookies ) return false;
        else if ( $cookies && !is_array($cookies) ) $cookies = array($cookies);

        $result = array();
        foreach ($cookies as $cookie) {
            $result[] = new Cookie($cookie);
        }

        return $result;
    }

    /**
     * Returns a array with the values of this Response
     *
     * @param  boolean $default if TRUE setDefaults() is called
     * @return array
     */
    public function toArray($default = true)
    {
        if ( $default ) $this->setDefaults();
        return array(
            'responseCode' => $this->getResponseCode(),
            'body' => $this->getBody()->toString(),
            'headers' => $this->getHeaders()
        );
    }

    /**
     * Returns a string with the values of this Response
     *
     * @param  boolean $default if TRUE setDefaults() is called
     * @return string
     */
    public function toString($default = true)
    {
        if ( $default ) $this->setDefaults();
        return (string) $this;
    }

    /**
     * Returns a JSON with the values of this Response
     *
     * @param  boolean $default if TRUE setDefaults() is called
     * @return string
     */
    public function toJSON($default = true)
    {
        return json_encode($this->toArray($default));
    }
}


<?php

namespace bariew\postModule\models;

use bariew\postModule\components\NestedQuery;
use bariew\postModule\Module;
use bariew\yii2Tools\behaviors\FileBehavior;
use creocoder\nestedsets\NestedSetsBehavior;
use Yii;
use yii\db\ActiveQuery;

/**
 * This is the model class for table "post_category".
 *
 * @property integer $id
 * @property string $title
 * @property string $name
 * @property string $content
 * @property integer $lft
 * @property integer $rgt
 * @property integer $depth
 * @property integer $is_active
 * @property Item[] $items
 *
 * @method NestedSetsBehavior makeRoot()
 * @method NestedSetsBehavior prependTo()
 * @method NestedSetsBehavior appendTo()
 * @method NestedSetsBehavior insertBefore()
 * @method NestedSetsBehavior insertAfter()
 * @method NestedSetsBehavior deleteWithChildren()
 * @method NestedSetsBehavior parents()
 * @method NestedSetsBehavior children()
 * @method NestedSetsBehavior prev()
 * @method NestedSetsBehavior next()
 * @method NestedSetsBehavior isRoot()
 * @method NestedSetsBehavior isLeaf()
 *
 * @method FileBehavior getRemoveLink
 * @method FileBehavior getFileLink
 * @method FileBehavior linkList
 * @method FileBehavior deleteFile
 * @method FileBehavior renameFile
 */
class Category extends \yii\db\ActiveRecord
{
    const SCENARIO_ADMIN = 'admin';

    public $items = [];

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'post_category';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['content'], 'string'],
            [['is_active'], 'integer'],
            [['title', 'name'], 'string', 'max' => 255],
            ['image', 'image', 'maxFiles' => 10],
        ];
    }

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
        switch ($this->scenario) {
            case self::SCENARIO_ADMIN:

                break;
            default : $this->is_active = 1;
        }
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        return [
            self::SCENARIO_ADMIN => [
                'content', 'title', 'is_active', 'name', 'image'
            ],
            self::SCENARIO_DEFAULT => []
        ];
    }

    /**
     * @param array $params
     * @return NestedQuery
     */
    public function search($params = [])
    {
        return self::find()->andFilterWhere(array_merge($this->attributes, $params));
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('modules/post', 'ID'),
            'title' => Yii::t('modules/post', 'Title'),
            'name' => Yii::t('modules/post', 'Name'),
            'content' => Yii::t('modules/post', 'Content'),
            'lft' => Yii::t('modules/post', 'Lft'),
            'rgt' => Yii::t('modules/post', 'Rgt'),
            'depth' => Yii::t('modules/post', 'Depth'),
            'is_active' => Yii::t('modules/post', 'Is Active'),
            'image' => Yii::t('modules/post', 'Image'),
        ];
    }

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'tree' => ['class' => NestedSetsBehavior::className()],
            'fileBehavior' => [
                'class' => FileBehavior::className(),
                'storage' => [$this, 'getStoragePath'],
                'fileField' => 'image',
                'imageSettings' => [
                    'thumb1' => ['method' => 'thumbnail', 'width' => 50, 'height' => 50],
                    'thumb2' => ['method' => 'thumbnail', 'width' => 100, 'height' => 100],
                    'thumb3' => ['method' => 'thumbnail', 'width' => 200, 'height' => 200],
                ]
            ],
        ];
    }

    /**
     * is_active available value list.
     * @return array
     */
    public static function activeList()
    {
        return [
            0 => Yii::t('modules/post', 'No'),
            1 => Yii::t('modules/post', 'Yes'),
        ];
    }
    /**
     * @return array
     */
    public function transactions()
    {
        return [
            static::SCENARIO_DEFAULT => static::OP_ALL,
        ];
    }

    /**
     * @return NestedQuery
     */
    public static function find()
    {
        return new NestedQuery(get_called_class());
    }

    /**
     * @return NestedQuery
     */
    public static function active()
    {
        return self::find()->andWhere(['is_active'=>1]);
    }

    public function beforeDelete()
    {
        if ($this->depth == 0) {
            throw new \BadMethodCallException(
                \Yii::t('modules/post', "Root category can not be deleted.")
            );
        }
        return parent::beforeDelete();
    }

    public function updateChildren($attributes)
    {
        $childrenIds = $this->children()->select(['id'])->column();
        return $this->updateAll($attributes, ['id' => $childrenIds]);
    }

    public function getCategoryToItems()
    {
        $relation = Module::getModel($this, 'CategoryToItem');
        return self::hasMany($relation::className(), ['category_id' => 'id']);
    }

    /**
     * @return ActiveQuery
     */
    public function getItems()
    {
        $relation = Module::getModel($this, 'Item');
        return self::hasMany($relation::className(), ['id' => 'item_id'])
            ->via('categoryToItems');
    }

    public static function activeItems($items)
    {
        $result = [];
        $exclude = [];
        foreach ($items as $k => $item) {
            if (!$item['is_active']) {
                $exclude[] = $item;
                continue;
            }
            if (self::isChildOfArray($exclude, $item)) {
                continue;
            }
            $result[$k] = $item;
        }
        return $result; // keys are kept!
    }

    public static function toTree($items)
    {
        $result = [];
        $parents = [];
        foreach ($items as $item) {
            $parents[$item['depth']][$item['lft']] = $item;
            if (!isset($parents[$item['depth']-1])) {
                $resultEnd = end($result);
                if (!$resultEnd || ($resultEnd['depth'] == $item['depth'])) {
                } else if ($resultEnd['depth'] > $item['depth']) {
                    $result = []; // We will unset previous result if its depth more than current
                } else {
                    continue; // we will not include current to result as its depth more that results roots
                }
                $result[$item['lft']] = &$parents[$item['depth']][$item['lft']];
                continue;
            }
            $parent = end($parents[$item['depth']-1]);
            if (!self::isChildOfArray([$parent], $item)) {
                continue;
            }
            $key = key($parents[$item['depth']-1]);
            $parents[$item['depth']-1][$key]['items'][$item['lft']]
                = &$parents[$item['depth']][$item['lft']];
        }
        return $result;
    }

    public static function isChildOfArray($parents, $child)
    {
        foreach ($parents as $parent) {
            if ($child['lft'] > $parent['lft']
                && $child['rgt'] < $parent['rgt']) {
                return true;
            }
        }
        return false;
    }

    /**
     * Relative path for saving model files.
     * @return string path.
     */
    public function getStoragePath()
    {
        $moduleName = \bariew\postModule\Module::moduleName($this);
        return "@app/web/files/{$moduleName}/"
            . $this->formName() . '/' . $this->id;
    }
}


<?php

namespace Oxygen\Data\Behaviour;

use Doctrine\Common\Collections\Collection;

trait Versions {

    /**
     * Returns the versions of the entity.
     *
     * @return Collection
     */
    public function getVersions() {
        if($this->isHead()) {
            return $this->versions;
        } else {
            return $this->headVersion->getVersions();
        }
    }

    /**
     * Returns true if the entity has any versions.
     *
     * @return boolean
     */
    public function hasVersions() {
        return !$this->getVersions()->isEmpty();
    }

    /**
     * Whether the current version is the head version.
     *
     * @return boolean
     */
    public function isHead() {
        return $this->headVersion === null;
    }

    /**
     * Returns the primary key of the head.
     *
     * @return integer
     */
    public function getHeadId() {
        return $this->isHead() ? $this->getId() : $this->headVersion->getId();
    }

    /**
     * Returns the head version.
     *
     * @return object
     */
    public function getHead() {
        return ($this->isHead()) ? $this : $this->headVersion;
    }

    /**
     * Sets the head version.
     *
     * @param object $head
     * @return $this
     */
    public function setHead($head) {
        $this->headVersion = $head;
        return $this;
    }

    /**
     * Returns a validation rule that validates this entity for uniqueness, ignoring other versions.
     *
     * @param $field
     * @return string
     */
    protected function getUniqueValidationRule($field) {
        $rule = 'unique:' . get_class($this) . ',' . $field . ',' . $this->getHeadId() . ',id';

        // ignore other versions of this entity
        if($this->getHeadId()) {
            $rule .= ',headVersion,!=,' . $this->getHeadId();
        }

        return $rule;
    }

}


<?php
namespace FzyCommon\Service;

/**
 * Class Url
 * @package FzyCommon\Service
 * Service Key: FzyCommon\Url
 */
class Url extends Base
{
    /**
     * @param $routeName
     * @param  array  $routeParams
     * @param  array  $routeOptions
     * @return string
     */
    public function fromRoute($routeName, $routeParams = array(), $routeOptions = array())
    {
        /* @var $router \Zend\Mvc\Router\Http\TreeRouteStack */
        $router = $this->getServiceLocator()->get('router');

        return $router->assemble($routeParams, array_merge($routeOptions, array('name' => $routeName)));
    }

    /**
     * Returns the S3 URL for the file at the specified key.
     * expiration determines how long the URL will work
     * downlaodAs specifies what the file name should start as when downloading
     * @param $key
     * @param  null   $expiration
     * @param  null   $downloadAs
     * @return string
     */
    public function fromS3($key, $expiration = null, $downloadAs = null)
    {
        $args = array();
        if (!empty($downloadAs)) {
            if (empty($expiration)) {
                throw new \RuntimeException("Unable to set download name on URL without expiration.");
            }
            $args['ResponseContentDisposition'] = 'attachment;filename='.$downloadAs;
        }

        return $this->getServiceLocator()->get('FzyCommon\Service\Aws\S3')->getObjectUrl($this->getServiceLocator()->get('FzyCommon\Service\Aws\S3\Config')->get('bucket'), $key, $expiration, $args);
    }
}


<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Tecnocreaciones\Bundle\ResourceBundle\Doctrine\ORM;

use Doctrine\ORM\QueryBuilder;
use Pagerfanta\Adapter\DoctrineORMAdapter;
use Tecnocreaciones\Bundle\ResourceBundle\Model\Paginator\Paginator;
use Sylius\Bundle\ResourceBundle\Doctrine\ORM\EntityRepository as BaseEntityRepository;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Security\Core\SecurityContext;
use Pagerfanta\Adapter\ArrayAdapter;

/**
 * Doctrine ORM driver entity repository.
 *
 * @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl>
 */
class EntityRepository extends BaseEntityRepository implements ContainerAwareInterface
{
    /**
     * @var SecurityContext
     */
    protected $securityContext;

    protected $container;
    public function getPaginator(QueryBuilder $queryBuilder)
    {
        $pagerfanta = new Paginator(new DoctrineORMAdapter($queryBuilder));
        $pagerfanta->setContainer($this->container);
        return $pagerfanta;
    }

    public function findAllPaginated()
    {
        return $this->getPaginator($this->getQueryBuilder())
        ;
    }

    public function setSecurityContext(SecurityContext $securityContext) {
        $this->securityContext = $securityContext;
    }

    public function setContainer(ContainerInterface $container = null) {
        $this->container = $container;
    }

    /**
     * Get a user from the Security Context
     *
     * @return mixed
     *
     * @throws \LogicException If SecurityBundle is not available
     *
     * @see Symfony\Component\Security\Core\Authentication\Token\TokenInterface::getUser()
     */
    public function getUser()
    {
        if (!$this->container->has('security.context')) {
            throw new \LogicException('The SecurityBundle is not registered in your application.');
        }

        if (null === $token = $this->container->get('security.context')->getToken()) {
            return null;
        }

        if (!is_object($user = $token->getUser())) {
            return null;
        }

        return $user;
    }

    /**
     * @param mixed $id
     *
     * @return null|object
     */
    public function find($id)
    {
        if(is_array($id) && isset($id['id'])){
            $id = $id['id'];
        }
        return $this
            ->getQueryBuilder()
            ->andWhere($this->getAlias().".id = '".$id."'")
            ->getQuery()
            ->getOneOrNullResult()
        ;
    }

    /**
     * Retorna un paginador con valores escalares (Sin hidratar)
     * @param \Doctrine\ORM\QueryBuilder $queryBuilder
     * @return \Tecnocreaciones\Bundle\ResourceBundle\Model\Paginator\Paginator
     */
    public function getScalarPaginator(\Doctrine\ORM\QueryBuilder $queryBuilder)
    {
        $pagerfanta = new \Tecnocreaciones\Bundle\ToolsBundle\Model\Paginator\Paginator(new ArrayAdapter($queryBuilder->getQuery()->getScalarResult()));

        $pagerfanta->setContainer($this->container);
        return $pagerfanta;
    }

    public function getSecurityContext()
    {
        if (!$this->container->has('security.context')) {
            throw new \LogicException('The SecurityBundle is not registered in your application.');
        }

        return $this->container->get('security.context');
    }

    /**
     *
     * @param array $criteria
     * @return \Doctrine\Common\Collections\ArrayCollection
     */
    protected function parseCriteria(array $criteria) {
        return new \Doctrine\Common\Collections\ArrayCollection($criteria);
    }
}