<?php

namespace SwooleFlierMouseBase\http;

use SwooleFlierMouseBase\Conf;
use SwooleFlierMouseBase\Core;

class Response
{

	private $http_protocol = 'HTTP/1.1';
	private $status_code   = '200';

	private $head   = [];
	private $body   = NULL;
	private $cookie = NULL;

	private $request;
	private $serv;

	private $HTTP_HEADERS
		= [
			100 => "100 Continue",
			101 => "101 Switching Protocols",
			200 => "200 OK",
			201 => "201 Created",
			204 => "204 No Content",
			206 => "206 Partial Content",
			300 => "300 Multiple Choices",
			301 => "301 Moved Permanently",
			302 => "302 Found",
			303 => "303 See Other",
			304 => "304 Not Modified",
			307 => "307 Temporary Redirect",
			400 => "400 Bad Request",
			401 => "401 Unauthorized",
			403 => "403 Forbidden",
			404 => "404 Not Found",
			405 => "405 Method Not Allowed",
			406 => "406 Not Acceptable",
			408 => "408 Request Timeout",
			410 => "410 Gone",
			413 => "413 Request Entity Too Large",
			414 => "414 Request URI Too Long",
			415 => "415 Unsupported Media Type",
			416 => "416 Requested Range Not Satisfiable",
			417 => "417 Expectation Failed",
			500 => "500 Internal Server Error",
			501 => "501 Method Not Implemented",
			503 => "503 Service Unavailable",
			506 => "506 Variant Also Negotiates"
		];

	/**
	 * 静态文件类型
	 *
	 * @var array
	 */
	static public $ASSET_TYPES
		= [
			'js'    => 'application/x-javascript',
			'css'   => 'text/css',
			'png'   => 'image/png',
			'jpg'   => 'image/jpeg',
			'jpeg'  => 'image/jpeg',
			'gif'   => 'image/gif',
			'json'  => 'application/json',
			'xml'   => 'application/xml',
			'svg'   => 'image/svg+xml',
			'woff'  => 'application/font-woff',
			'woff2' => 'application/font-woff2',
			'ttf'   => 'application/x-font-ttf',
			'eot'   => 'application/vnd.ms-fontobject',
			'html'  => 'text/html',
			'zip'   => 'application/x-zip-compressed',
		];

	function __construct (RequestEvent $request, $serv)
	{
		$this->request = $request;
		$this->serv    = $serv;
	}

	public function bodyIsNull ()
	{
		return $this->body === NULL;
	}

	/**
	 * 自定义tcp_http 使用
	 *
	 * @return string
	 */
	public function toString ()
	{
		$this->setHeader('Server', sprintf('%s/%s %s.%s.%s', Core::SERVER_SOFT_NAME, Core::SERVER_SOFT_VERSION_NAME, Core::SERVER_SOFT_VERSION, Core::SERVER_SOFT_MINOR_VERSION, Core::SERVER_SOFT_BUILD_VERSION));

		if (!isset($this->head['Cache-Control'])) {
			$this->setHeader('Cache-Control', 'no-cache');
		}
		if (!isset($this->head['Connection'])) {
			$this->setHeader('Connection', 'Keep-Alive');
		}

		if ($this->bodyIsNull() && in_array((int)$this->status_code, $this->HTTP_HEADERS) && (int)$this->status_code != 200) {
			$this->setBody($this->HTTP_HEADERS[ $this->status_code ]);
		}

		if (is_array($this->body)) {
			$this->setHeader('Content-Type', 'application/json');
			$this->body = json_encode($this->body, 256);
		}

		if (!isset($this->head['Content-Type'])) {
			$this->setContentType('html');
		}

		if (!isset($this->head['Content-Length'])) {
			$this->setHeader('Content-Length', strlen($this->body));
		}

		if (is_array($this->head)) {
			foreach ($this->head as $key => $val) {
				$head [] = "{$key}: {$val}";
			}
		}

		$head[] = 'Date: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT';;

		if ($this->serv->session) {
			$this->setCookie('SFMBSESSION', $this->request->getSessionId());
		}

		$cookie = [];
		if (!empty($this->cookie) and is_array($this->cookie)) {
			foreach ($this->cookie as $v) {
				$cookie[] = "Set-Cookie: $v";
			}
		}

		$head = join("\r\n", array_merge($head, $cookie));

		$responseBody
			= <<<CONTEXT
$this->http_protocol {$this->HTTP_HEADERS[$this->status_code]}
$head

$this->body
CONTEXT;

		return $responseBody;

	}

	public function setHeader ($name, $value)
	{
		$this->head[ $name ] = $value;

		return $this;
	}

	public function setBody ($raw_body)
	{
		$this->body = $raw_body;

		return $this;
	}

	public function setStatusCode ($code)
	{
		$this->status_code = $code;

		return $this;
	}

	public function setContentType ($content_type)
	{

		$this->setHeader('Content-Type', isset(self::$ASSET_TYPES[ $content_type ]) ? self::$ASSET_TYPES[ $content_type ] : $content_type);

		return $this;
	}

	public function with ($string)
	{
		$this->withHtml($string);
	}

	public function withHtml ($html)
	{
		$this->setHeader('Content-Type', self::$ASSET_TYPES['html']);
		$this->body = $html;

		$this->httpResponseEnd();
	}

	public function withJson ($data)
	{
		if (isset($data['error_code'])) {
			$data['error_code'] = (int)$data['error_code'];
		}
		else {
			$data['error_code'] = 0;
		}

		$this->body = json_encode($data);
		$this->setHeader('Content-Type', 'application/json');

		$this->httpResponseEnd();
	}

	public function crossAllow ($access_control_allow_origin = '*', $access_control_allow_headers = 'content-type , Content-Type')
	{
		$this->setHeader('Access-Control-Allow-Origin', $access_control_allow_origin);
		$this->setHeader('Access-Control-Allow-Headers', $access_control_allow_headers);

		return $this;
	}

	function noCache ()
	{
		$this->head['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0';
		$this->head['Pragma']        = 'no-cache';

		return $this;
	}

	/**
	 * cookie
	 *
	 * @param         $name
	 * @param null    $value
	 * @param null    $expire
	 * @param string  $path
	 * @param null    $domain
	 * @param null    $secure
	 * @param boolean $http_only
	 *
	 * @return object
	 */
	function setCookie ($name, $value = NULL, $expire = NULL, $path = '/', $domain = NULL, $secure = NULL, $http_only = FALSE)
	{
		$cookie[] = "{$name}={$value}";
		if ($expire) $cookie[] = "expires=Tue, " . date("D, d-M-Y H:i:s T", $expire) . "";
		if ($path) $cookie[] = "path={$path}";
		if ($domain) $cookie[] = "domain={$domain}";
		if ($http_only) $cookie[] = " httponly";

		$this->cookie[] = join(';', $cookie);

		return $this;
	}

	function download ($file_type, $file_name, $file_path)
	{
		return $this->noCache()
			->setContentType($file_type)
			->setHeader('Expires', 0)
			->setHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\'' . rawurlencode($file_name))
			->setBody(file_get_contents($file_path));
	}

	public function destroy ()
	{
		$this->head    = [];
		$this->body    = NULL;
		$this->cookie  = NULL;
		$this->request = NULL;
		$this->serv    = NULL;
	}

	function send ($server, $fd, $reactor_id)
	{
		if ($server->exist($fd)) {
			$body = $this->toString();
			$server->send($fd, $body);

			$connection = $this->request->getHeader('connection');
			if (!$connection || !strtolower($connection) == 'keep-alive') {
				$server->close($fd);
			}

		}

		Conf::deleteDir(Conf::$temp . DIRECTORY_SEPARATOR . $this->request->getSessionId());
		$this->request->destroy();
		$this->destroy();
	}
}


<?php

namespace Dothiv\Bundle\ContentfulBundle\Repository;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityRepository;
use Dothiv\Bundle\ContentfulBundle\Item\ContentfulContentType;
use Dothiv\Bundle\ContentfulBundle\Item\ContentfulEntry;
use PhpOption\Option;

class DoctrineContentfulEntryRepository extends EntityRepository implements ContentfulEntryRepository
{
    use Traits\ValidatorTrait;

    /**
     * {@inheritdoc}
     */
    function findNewestById($spaceId, $id)
    {
        $result = $this->findBy(array('id' => $id, 'spaceId' => $spaceId), array('revision' => 'DESC'), 1);
        return Option::fromValue(count($result) == 1 ? array_shift($result) : null);
    }

    /**
     * {@inheritdoc}
     */
    function persist(ContentfulEntry $entry)
    {
        $this->getEntityManager()->persist($this->validate($entry));
        return $this;
    }

    /**
     * {@inheritdoc}
     */
    function remove(ContentfulEntry $entry)
    {
        $this->getEntityManager()->remove($entry);
        return $this;
    }

    /**
     * {@inheritdoc}
     */
    function flush()
    {
        $this->getEntityManager()->flush();
        return $this;
    }

    /**
     * @param ContentfulContentType $contentType
     *
     * @return ContentfulEntry[]|ArrayCollection
     */
    function findByContentType(ContentfulContentType $contentType)
    {
        // Do not rely on Mysql Group By.
        $query   = $this->getEntityManager()->createQuery(
            'SELECT e1 FROM Dothiv\Bundle\ContentfulBundle\Item\ContentfulEntry e1 '
            . 'WHERE e1.contentTypeId = :contentTypeId '
            . 'AND e1.spaceId = :spaceId '
            . 'AND e1.revision = (SELECT MAX(e2.revision) FROM Dothiv\Bundle\ContentfulBundle\Item\ContentfulEntry e2 WHERE e2.id = e1.id AND e2.spaceId = :spaceId)')
            ->setParameter('contentTypeId', $contentType->getId())
            ->setParameter('spaceId', $contentType->getSpaceId())
        ;
        return new ArrayCollection($query->getResult());
    }

    /**
     * @param string $spaceId
     * @param string $contentTypeId
     * @param string $name
     *
     * @return Option
     */
    function findByContentTypeIdAndName($spaceId, $contentTypeId, $name)
    {
        $query = $this->getEntityManager()->createQuery(
            'SELECT e1 FROM Dothiv\Bundle\ContentfulBundle\Item\ContentfulEntry e1 '
            . 'WHERE e1.name = :name '
            . 'AND e1.contentTypeId = :contentTypeId '
            . 'AND e1.spaceId = :spaceId '
            . 'AND e1.revision = (SELECT MAX(e2.revision) FROM Dothiv\Bundle\ContentfulBundle\Item\ContentfulEntry e2 WHERE e2.id = e1.id AND e2.spaceId = :spaceId)'
        )
            ->setParameter('contentTypeId', $contentTypeId)
            ->setParameter('spaceId', $spaceId)
            ->setParameter('name', $name)
        ;
        return Option::fromValue($query->getOneOrNullResult());
    }
}


<?php

/*
 * This file is part of the overtrue/wechat.
 *
 * (c) overtrue <i@overtrue.me>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

/**
 * MessageBuilder.php.
 *
 * @author    overtrue <i@overtrue.me>
 * @copyright 2015 overtrue <i@overtrue.me>
 *
 * @see      https://github.com/overtrue
 * @see      http://overtrue.me
 */

namespace EasyWeChat\Staff;

use EasyWeChat\Core\Exceptions\InvalidArgumentException;
use EasyWeChat\Core\Exceptions\RuntimeException;
use EasyWeChat\Message\AbstractMessage;
use EasyWeChat\Message\Raw as RawMessage;
use EasyWeChat\Message\Text;

/**
 * Class MessageBuilder.
 */
class MessageBuilder
{
    /**
     * Message to send.
     *
     * @var \EasyWeChat\Message\AbstractMessage;
     */
    protected $message;

    /**
     * Message target user open id.
     *
     * @var string
     */
    protected $to;

    /**
     * Message sender staff id.
     *
     * @var string
     */
    protected $account;

    /**
     * Staff instance.
     *
     * @var \EasyWeChat\Staff\Staff
     */
    protected $staff;

    /**
     * MessageBuilder constructor.
     *
     * @param \EasyWeChat\Staff\Staff $staff
     */
    public function __construct(Staff $staff)
    {
        $this->staff = $staff;
    }

    /**
     * Set message to send.
     *
     * @param string|AbstractMessage $message
     *
     * @return MessageBuilder
     *
     * @throws InvalidArgumentException
     */
    public function message($message)
    {
        if (is_string($message)) {
            $message = new Text(['content' => $message]);
        }

        $this->message = $message;

        return $this;
    }

    /**
     * Set staff account to send message.
     *
     * @param string $account
     *
     * @return MessageBuilder
     */
    public function by($account)
    {
        $this->account = $account;

        return $this;
    }

    /**
     * Set target user open id.
     *
     * @param string $openId
     *
     * @return MessageBuilder
     */
    public function to($openId)
    {
        $this->to = $openId;

        return $this;
    }

    /**
     * Send the message.
     *
     * @return bool
     *
     * @throws RuntimeException
     */
    public function send()
    {
        if (empty($this->message)) {
            throw new RuntimeException('No message to send.');
        }

        $transformer = new Transformer();

        if ($this->message instanceof RawMessage) {
            $message = $this->message->get('content');
        } else {
            $content = $transformer->transform($this->message);
            $message = [
                'touser' => $this->to,
            ];

            if ($this->account) {
                $message['customservice'] = ['kf_account' => $this->account];
            }

            $message = array_merge($message, $content);
        }

        return $this->staff->send($message);
    }

    /**
     * Return property.
     *
     * @param $property
     *
     * @return mixed
     */
    public function __get($property)
    {
        if (property_exists($this, $property)) {
            return $this->$property;
        }
    }
}


<?php
/**
 * User: Alex Gusev <alex@flancer64.com>
 */

namespace Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase2\Fun\Rou;

use Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase2\Data\Legs as DLegs;

/**
 * Routine to calculate legs using team OVs.
 */
class CalcLegs
{
    /**
     * Run though first-line team members and collect OVs (plain or compressed).
     *
     * @param array $team Customers IDs for first-line team.
     * @param \Praxigento\BonusHybrid\Repo\Data\Downline[] $mapById Downline data (with OV) mapped by customer
     *     ID.
     * @return \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase2\Data\Legs
     */
    public function exec($team, $mapById): DLegs
    {
        $legMax = $legSecond = $legOthers = 0;
        $custMax = $custSecond = null;
        foreach ($team as $memberId) {
            /** @var \Praxigento\BonusHybrid\Repo\Data\Downline $member */
            $member = $mapById[$memberId];
            $ovMember = $member->getOv();
            if ($ovMember > $legMax) {
                /* update MAX leg */
                $legOthers += $legSecond;
                $legSecond = $legMax;
                $custSecond = $custMax;
                $legMax = $ovMember;
                $custMax = $memberId;
            } elseif ($ovMember > $legSecond) {
                /* update second leg */
                $legOthers += $legSecond;
                $legSecond = $ovMember;
                $custSecond = $memberId;
            } else {
                $legOthers += $ovMember;
            }
        }

        /* compose results */
        $result = new DLegs();
        $result->setMaxOv($legMax);
        $result->setSecondOv($legSecond);
        $result->setOthersOv($legOthers);
        $result->setMaxCustId($custMax);
        $result->setSecondCustId($custSecond);
        return $result;
    }
}


<?php
namespace Lead\Benchmark;

class Matrix
{
    /**
     * The task collection.
     *
     * @var array
     */
    protected $_tasks = [];

    /**
     * The matrix result.
     *
     * @var array
     */
    protected $_matrix = [];

    /**
     * The ordered task name (faster first).
     *
     * @var array
     */
    protected $_ranking = [];

    /**
     * Constructor
     *
     * @param array $tasks A collection of tasks.
     */
    public function __construct($tasks = [])
    {
        foreach($tasks as $task) {
            $this->_tasks[$task->name()] = $task;
        }
    }

    /**
     * Returns the matrix result.
     *
     * @return array
     */
    public function matrix()
    {
        return $this->_matrix;
    }

    /**
     * Returns the tasks ranking.
     *
     * @return array
     */
    public function ranking()
    {
        return $this->_ranking;
    }

    /**
     * Builds the matrix result.
     *
     * @return self
     */
    public function process()
    {
        $orderedTasks = $this->_tasks;
        usort($orderedTasks, function($a, $b) {
            return $a->duration() > $b->duration() ? 1 : -1;
        });

        $this->_ranking = $orderedTasks;

        $matrix = [];
        foreach($this->_ranking as $task1) {
            $name1 = $task1->name();
            $matrix[$name1] = [];

            foreach($this->_ranking as $task2) {
                $name2 = $task2->name();
                $percent = intval(round($task1->duration() / $task2->duration() * 100));
                $matrix[$name1][$name2] = $percent;
            }
        }
        $this->_matrix = $matrix;
        return $this;
    }
}


<?php

namespace Maba\OAuthCommerceAccountsClient\DependencyInjection;

use Maba\OAuthCommerceClient\MacSignature\RsaAlgorithm;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\DefinitionDecorator;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;

class AccountsClientExtension implements ExtensionInterface
{
    /**
     * Loads a specific configuration.
     *
     * @param array            $config    An array of configuration values
     * @param ContainerBuilder $container A ContainerBuilder instance
     *
     * @throws InvalidArgumentException When provided tag is not defined in this extension
     * @api
     */
    public function load(array $config, ContainerBuilder $container)
    {
        $container->setParameter('maba_oauth_commerce.accounts_client.default_base_url', null);

        $container
            ->setDefinition(
                'maba_oauth_commerce.factory.accounts',
                new DefinitionDecorator('maba_oauth_commerce.factory.base')
            )
            ->addMethodCall('setDefaultBaseUrl', array('%maba_oauth_commerce.accounts_client.default_base_url%'))
            ->setClass('Maba\OAuthCommerceAccountsClient\AccountsClientFactory')
        ;

        $container->register(
            'maba_oauth_commerce.factory.accounts_api',
            'Maba\OAuthCommerceAccountsClient\AccountsApiFactory'
        )->setArguments(array(
            new Reference('maba_oauth_commerce.factory.auth'),
            new Reference('maba_oauth_commerce.factory.accounts'),
            new Reference('maba_oauth_commerce.algorithm_manager'),
            new Definition('Maba\OAuthCommerceClient\Random\DefaultRandomProvider'),
        ));
    }

    /**
     * Returns the namespace to be used for this extension (XML namespace).
     * @return string The XML namespace
     * @api
     */
    public function getNamespace()
    {
        return $this->getAlias();
    }

    /**
     * Returns the base path for the XSD files.
     * @return string The XSD base path
     * @api
     */
    public function getXsdValidationBasePath()
    {
        return false;
    }

    /**
     * Returns the recommended alias to use in XML.
     * This alias is also the mandatory prefix to use when using YAML.
     * @return string The alias
     * @api
     */
    public function getAlias()
    {
        return 'maba_oauth_commerce_internal_client';
    }
}


<?php
Web2All_Manager_Main::loadClass('Web2All_Table_ObjectBaseList');

/**
 * Web2All Table ObjectList class
 *
 * This class manages a list of Web2All_Table_Object's
 * (or an extension off). It makes use of special hooks exposed
 * in the Object.
 *
 * Usage sample:
 *  $filter=$this->Web2All->Plugin->Web2All_Intra_Service_WebServer($this->serviceDB);
 *  $filter->centralftp='web2all';
 *  $result=$this->Web2All->Plugin->Web2All_Table_ObjectList($filter);
 *  $result->setKey('id');
 *  $result->setExtra('ORDER BY name');
 *  $result->setRange(10,0);
 *  $result->fetchData();
 *  foreach($result as $object){
 *    $object->debugDump();
 *  }
 *
 * @author Merijn van den Kroonenberg
 * @copyright (c) Copyright 2008 Web2All BV
 * @since 2008-01-31
 */
class Web2All_Table_ObjectList extends Web2All_Table_ObjectBaseList implements Iterator,ArrayAccess,Countable {

  protected $key;

  protected $result;

  protected $is_assoc;

  /**
   * constructor
   *
   * @param Web2All_Manager_Main $web2all
   * @param Web2All_Table_Object $obj
   */
  public function __construct(Web2All_Manager_Main $web2all,$obj) {
    parent::__construct($web2all,$obj);

    $this->key=null;

    $this->result=null;

    $this->is_assoc=false;

  }

  /**
   * Assign a key to the list.
   * If you do this before calling fetchData() then
   * this list will become associative.
   *
   * The key should be the name of a property
   *
   * @param string $key
   */
  public function setKey($key)
  {
    $this->key=$key;
    $this->is_assoc=(is_null($this->key) ? false : true);
  }

  /**
   * remove the data from the list
   */
  public function clearList()
  {
    $this->key=null;

    $this->result=null;
  }

  /**
   * fetch all data from the database
   * and store the result in this object.
   *
   * after this method has been called, this object can be
   * treated as an array of Web2All_Table_IListableObject's
   *
   */
  public function fetchData()
  {
    parent::fetchData();
    $this->is_assoc=(is_null($this->key) ? false : true);
    $this->result=array();
    while (!$this->recordSet->EOF) {
      $table_obj=clone $this->search_obj;
      $table_obj->loadFromDBArray($this->recordSet->FetchRow());
      if ($this->is_assoc) {
        $this->result[$table_obj->{$this->key}]=$table_obj;
      }else{
        $this->result[]=$table_obj;
      }
    }
    $this->recordSet->close();
  }

  /**
   * return the list data as an array (non assoc)
   *
   * @return array
   */
  public function asArray()
  {
    if (is_null($this->result)) {
      $this->fetchData();
    }
    if ($this->is_assoc) {
      return array_values($this->result);
    }else{
      return $this->result;
    }
  }

  /**
   * return the list data as an array
   *
   * if the list is associative, the returned array
   * will be too.
   *
   * @return array
   */
  public function asAssocArray()
  {
    if (is_null($this->result)) {
      $this->fetchData();
    }
    return $this->result;
  }

  /**
   * Check if this list is associative
   * (a key was set with setKey())
   *
   * @return boolean
   */
  public function isAssoc()
  {
    return $this->is_assoc;
  }

  /**
   * check if the data was fetched from the database
   * (was fetchData() called)
   *
   * @return boolean
   */
  public function isFetched()
  {
    return (is_null($this->result) ? false :true );
  }

  /**
   * equal to reset() on an array
   *
   * Iterator implementation
   */
  public function rewind() {
    if (is_null($this->result)) {
      $this->fetchData();
    }
    reset($this->result);
  }

  /**
   * equal to current() on an array
   *
   * Iterator implementation
   *
   * @return mixed
   */
  public function current() {
    if (is_null($this->result)) {
      $this->fetchData();
    }
    $var = current($this->result);
    return $var;
  }

  /**
   * equal to key() on an array
   *
   * Iterator implementation
   *
   * @return mixed
   */
  public function key() {
    if (is_null($this->result)) {
      $this->fetchData();
    }
    $var = key($this->result);
    return $var;
  }

  /**
   * equal to next() on an array
   *
   * Iterator implementation
   *
   * @return mixed
   */
  public function next() {
    if (is_null($this->result)) {
      $this->fetchData();
    }
    $var = next($this->result);
    return $var;
  }

  /**
   * check if the end of array is reached
   *
   * Iterator implementation
   *
   * @return boolean
   */
  public function valid() {
    $var = $this->current() !== false;
    return $var;
  }

  /**
   * Check if the key exists in the array
   *
   * ArrayAccess implementation
   *
   * @param mixed $offset
   * @return boolean
   */
  public function offsetExists($offset){

    if (is_null($this->result)) {
      $this->fetchData();
    }

    if(array_key_exists($offset,$this->result)){
      return true;
    }
    else{
      return false;
    }

  }

  /**
   * get value by key from the list
   * (called when using the brackets [$key])
   *
   * ArrayAccess implementation
   *
   * @param unknown_type $offset
   * @return unknown
   */
  public function offsetGet($offset){

    if (is_null($this->result)) {
      $this->fetchData();
    }
    return $this->result[$offset];

  }

  /**
   * Add a new element to the array
   *
   * ArrayAccess implementation
   *
   * @param mixed $offset
   * @param mixed $value
   * @return boolean
   */
  public function offsetSet($offset, $value){

    if (is_null($this->result)) {
      $this->fetchData();
    }
    if (!$this->isFetched()) {
      trigger_error('Web2All_Table_ObjectList::offsetSet: cannot set value on unitialized list',E_USER_NOTICE);
      return false;
    }
    if (!$this->is_assoc && !is_numeric($value)) {
      trigger_error('Web2All_Table_ObjectList::offsetSet: can only set numeric keys non assoc lists',E_USER_NOTICE);
      return false;
    }

    if ($value instanceof $this->classname) {
      $this->result[$offset]=$value;
    }else{
      trigger_error('Web2All_Table_ObjectList::offsetSet: can only add objects of type '.$this->classname.' to the list',E_USER_NOTICE);
      return false;
    }
  }

  /**
   * Remove element from the list
   *
   * ArrayAccess implementation
   *
   * @param mixed $offset
   */
  public function offsetUnset($offset){
    if ($this->offsetExists($offset)) {
      unset($this->result[$offset]);
    }
  }

  /**
   * Retrieve number of elements in array
   *
   * Countable implementation
   *
   * *NOTE* it returns the actual amount of results returned
   *        and not the count of the results if no limit was
   *        given. If you want that, use the Web2All_Table_PagedObjectList
   *        instead.
   *
   * @return int
   */
  public function count() {
    if (is_null($this->result)) {
      $this->fetchData();
    }
    return count($this->result);
  }

  /**
   * Method which removes all database table entries collected in this object.
   *
   * The table objects should extend the Web2All_Table_SaveObject class.
   *
   * @throws Exception
   */
  public function removeFromDB(){
    if (is_null($this->result)) {
      $this->fetchData();
    }
    if(count($this->result) > 0){
      if(!$this->result[0] instanceof Web2All_Table_SaveObject){
        throw new Exception("Web2All_Table_ObjectList->removeFromDB: Not a saveobject, you can't delete a non saveobject.");
      }
      foreach($this->result as $row){
        $row->deleteFromDB();
      }
    }
  }

}

?>


<?php

namespace Webforge\Types;

use Webforge\Common\Util;

class Inferrer {

  /**
   * Versucht den Typ von einem PHP-Basis-Datentyp zu erraten
   *
   * @throws Webforge\Types\InferException
   */
  public function inferType($value) {
    if (is_string($value)) {
      return new StringType();
    } elseif (is_array($value)) {
      return new ArrayType();
    } elseif (is_object($value)) {
      return $this->inferObjectType($value);
    } elseif (is_integer($value)) {
      return new IntegerType();
    } elseif (is_bool($value)) {
      return new BooleanType();
    } elseif(is_null($value)) {
      return new MixedType();
    }

    $e = new InferException('Typ konnte nicht geraten werden: '.Util::varInfo($value));
    $e->value = $value;
    throw $e;
  }

  public function inferObjectType($object) {
    $objectClass = GClassAdapter::newGClass(get_class($object));
    if ($object instanceof \Doctrine\Common\Collections\Collection) {
      return new CollectionType($objectClass);
    } else {
      return new ObjectType($objectClass);
    }
  }
}


<?php

/**
 * @file
 *
 * @package In2pire
 * @subpackage Cli
 * @author Nhat Tran <nhat.tran@inspire.vn>
 */

namespace In2pire\Cli;

use In2pire\Cli\Configuration\PhpConfiguration;
use In2pire\Cli\Configuration\YamlConfiguration;
use In2pire\Cli\Configuration\Exception\FileNotFoundException;
use In2pire\Cli\Configuration\Exception\RuntimeException;
use In2pire\Component\Utility\NestedArray;

/**
 * Configuration.
 */
final class Configuration
{
    /**
     * Path to configuration folder.
     *
     * @var string
     */
    protected $confPath = '.';

    /**
     * Cached configuration.
     *
     * @var array
     */
    protected $cache = [];

    /**
     * Get configuration instance.
     *
     * @param string $id
     *   Instance ID.
     *
     * @return In2pire\Cli\Configuration
     *   Configuration.
     */
    public static function getInstance($id = 'application')
    {
        static $instances = [];

        if (isset($instances[$id])) {
            return $instances[$id];
        }

        return $instances[$id] = new static();
    }

    /**
     * Init configuration.
     *
     * @param string $confPath
     *   Path to configuration folder.
     * @param boolean $useCache
     *   Check wether use cached configuration.
     */
    public function init($confPath, $useCache = true)
    {
        $this->confPath = $confPath;

        if ($useCache) {
            $cachedConfig = new PhpConfiguration();
            $this->cache = $cachedConfig->get();
            unset($cachedConfig);
        }
    }

    /**
     * Set path to configuration folder.
     *
     * @param string $path
     *   Path.
     */
    protected function setConfigPath($path)
    {
        $this->confPath = $path;
    }

    /**
     * Get path to configuration folder.
     *
     * @return string
     *   Path.
     */
    protected function getConfigPath()
    {
        return $this->confPath;
    }

    /**
     * Get config file path.
     *
     * @param string $namespace
     *   Configuration namespace.
     *
     * @return string
     *   Path to configuration file.
     */
    protected function getConfigFile($namespace)
    {
        if (empty($namespace)) {
            throw new RuntimeException('Namespace is empty');
        }

        return $this->getConfigPath() . '/' . str_replace('.', '/', $namespace) . '.yml';
    }

    /**
     * Load configuration from namespace.
     *
     * @param string $namespace
     *   Configuration namespace.
     * @param  boolean $require
     *   (optional) Throw expcetion if namespace configuration file could not be
     *   found.
     *
     * @return mixed|null
     *   List of configurations or null if file not found.
     */
    protected function load($namespace, $require = false)
    {
        // If cache is set.
        if (isset($this->cache[$namespace])) {
            return $this->cache[$namespace];
        }

        $file = $this->getConfigFile($namespace);
        $configuration = null;

        try {
            $configFile = new YamlConfiguration($file);
            $configuration = $configFile->get();

            if (is_array($configuration) && !empty($configuration['inherits'])) {
                $allConfiguration = [];

                foreach ($configuration['inherits'] as $parentNamespace) {
                    $allConfiguration[] = $this->load($parentNamespace);
                }

                $allConfiguration[] = $configuration;
                $configuration = $this->merge($allConfiguration);
                unset($allConfiguration, $configuration['inherits']);
            }

            unset($configFile);
        } catch (FileNotFoundException $e) {
            if ($require) {
                throw new FileNotFoundException('Could not find settings file for ' . $namespace);
            }
        }

        return $this->cache[$namespace] = $configuration;
    }

    /**
     * Get all configuration from namespace
     *
     * @param string $namespace
     *   Configuration namespace.
     * @param  boolean $require
     *   (optional) Throw expcetion if namespace configuration file could not be
     *   found.
     *
     * @return mixed|null
     *   List of configurations or null if file not found.
     */
    public function getAll($namespace, $require = false)
    {
        return $this->load($namespace, $require);
    }

    /**
     * Get a configuration from namespace
     *
     * @param string $namespace
     *   Configuration $name.
     * @param string $namespace
     *   Configuration name.
     * @param mixed $default
     *   (optional) Default value if cannot find configuration.
     * @param  boolean $require
     *   (optional) Throw expcetion if namespace configuration file could not be
     *   found.
     *
     * @return mixed|null
     *   Configurations or null if file not found.
     */
    public function get($namespace, $name, $default = null, $require = false)
    {
        $configuration = $this->load($namespace, $require);
        return array_key_exists($name, $configuration) ? $configuration[$name] : $default;
    }

    /**
     * Merge configuration.
     *
     * @param array $configs
     *   Group of configuration.
     *
     * @return mixed
     *   Merged configuration.
     */
    protected function merge(array $configs)
    {
        $objects = array_filter($configs, 'is_object');

        if (!empty($objects)) {
            $listConfigs = [];

            foreach ($configs as $config) {
                if (!is_object($config)) {
                    throw new RuntimeException('Cannot merge object with other types');
                }

                $listConfigs[] = (array) $config;
            }

            $result = (object) $this->merge($listConfigs);
        } else {
            foreach ($configs as $config) {
                foreach ($config as $key => $value) {
                    $existed = isset($result[$key]);

                    switch (true) {
                        case ($existed && (is_object($result[$key]) || is_object($value))):
                        case ($existed && (is_array($result[$key]) && is_array($value))):
                            $result[$key] = $this->merge(array($result[$key], $value));
                            break;

                        default:
                            $result[$key] = $value;
                    }
                }
            }
        }

        return $result;
    }
}


<?php
/**
 * @link http://psesd.org/
 *
 * @copyright Copyright (c) 2015 Puget Sound ESD
 * @license http://psesd.org/license/
 */

namespace cascade\components\dataInterface\connectors\file;

/**
 * Model [[@doctodo class_description:cascade\components\dataInterface\connectors\file\Model]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class Model extends \cascade\components\dataInterface\connectors\generic\Model
{
    /**
     * @var [[@doctodo var_type:_id]] [[@doctodo var_description:_id]]
     */
    protected $_id;
    /**
     * @var [[@doctodo var_type:_keys]] [[@doctodo var_description:_keys]]
     */
    protected $_keys;
    /**
     * @var [[@doctodo var_type:_meta]] [[@doctodo var_description:_meta]]
     */
    protected $_meta;
    /**
     * @var [[@doctodo var_type:_children]] [[@doctodo var_description:_children]]
     */
    protected $_children = [];

    // public $attributeNames = [];

    // public function hasAttribute($attribute)
    // {
    //     return in_array($attribute, $this->attributeNames);
    // }
    /**
     * Get id.
     *
     * @return [[@doctodo return_type:getId]] [[@doctodo return_description:getId]]
     */
    public function getId()
    {
        return $this->_id;
    }

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

    /**
     * Set id.
     *
     * @param [[@doctodo param_type:id]] $id [[@doctodo param_description:id]]
     *
     * @return [[@doctodo return_type:setId]] [[@doctodo return_description:setId]]
     */
    public function setId($id)
    {
        return $this->_id = $id;
    }

    /**
     * Set source file.
     *
     * @param [[@doctodo param_type:sourceFile]] $sourceFile [[@doctodo param_description:sourceFile]]
     *
     * @return [[@doctodo return_type:setSourceFile]] [[@doctodo return_description:setSourceFile]]
     */
    public function setSourceFile($sourceFile)
    {
        $this->_meta = Meta::get($this->interface, $sourceFile);

        return $this;
    }

    /**
     * Get children.
     *
     * @return [[@doctodo return_type:getChildren]] [[@doctodo return_description:getChildren]]
     */
    public function getChildren()
    {
        return $this->_children;
    }

    /**
     * [[@doctodo method_description:addChild]].
     *
     * @param [[@doctodo param_type:object]] $object [[@doctodo param_description:object]]
     */
    public function addChild($object)
    {
        $this->_children[$object->id] = $object;
    }

    /**
     * [[@doctodo method_description:primaryKey]].
     *
     * @return [[@doctodo return_type:primaryKey]] [[@doctodo return_description:primaryKey]]
     */
    public function primaryKey()
    {
        return 'id';
    }

    /**
     * Get primary key.
     *
     * @return [[@doctodo return_type:getPrimaryKey]] [[@doctodo return_description:getPrimaryKey]]
     */
    public function getPrimaryKey()
    {
        return $this->id;
    }

    /**
     * Get attributes.
     *
     * @return [[@doctodo return_type:getAttributes]] [[@doctodo return_description:getAttributes]]
     */
    public function getAttributes()
    {
        if (!isset($this->meta)) {
            return $this->_attributes;
        }
        $a = [];
        foreach ($this->meta->attributeKeys as $k) {
            $a[$k] = null;
            if (is_array($this->_attributes) && isset($this->_attributes[$k])) {
                $a[$k] = $this->_attributes[$k];
            }
        }

        return $a;
    }

    /**
     * Set table name.
     *
     * @param [[@doctodo param_type:value]] $value [[@doctodo param_description:value]]
     */
    public function setTableName($value)
    {
        $this->_tableName = $value;
    }

    /**
     * @inheritdoc
     */
    public function getTableName()
    {
        if (isset($this->_tableName)) {
            return $this->_tableName;
        }

        return static::baseClassName();
    }

    /**
     * [[@doctodo method_description:fetchAll]].
     *
     * @param boolean $lazy [[@doctodo param_description:lazy]] [optional]
     *
     * @return [[@doctodo return_type:fetchAll]] [[@doctodo return_description:fetchAll]]
     */
    public static function fetchAll($lazy = false)
    {
        $models = [];
        $baseModel = new static();
        foreach ($baseModel->meta->sourceFile->getLines($lazy, true) as $line) {
            $model = $this->populateRecord($line->attributes);
            $models[] = $model;
        }

        return $models;
    }
}


<?php

namespace Peridot\Plugin\Gherkin;

class SpecReporter extends \Peridot\Reporter\SpecReporter
{
    protected $currentSuite;
    protected $lastFeature;
    protected $lastScenario;

    protected static $instance;
    protected static $quiet = false;

    public function init(...$args)
    {
        static::$instance = $this;
        return parent::init(...$args);
    }

    public static function beQuiet()
    {
        static::$instance->output->setVerbosity(
            \Symfony\Component\Console\Output\OutputInterface::VERBOSITY_QUIET
        );
    }

    public function onRunnerStart()
    {
        //
    }

    /**
     * @param Suite $suite
     */
    public function onSuiteEnd()
    {
        parent::onSuiteEnd();
    }

    /**
     * @param Suite $suite
     */
    public function onSuiteStart($suite)
    {
        $description = $suite->getDescription();
        if (strpos($description, 'Feature:') !== 0) {
            $this->output->writeln('');
        }

        parent::onSuiteStart($suite);
    }

    /**
     * Output a test failure.
     *
     * @param int $errorNumber
     * @param TestInterface $test
     * @param $exception
     */
    protected function outputError($errorNumber, $test, $exception)
    {
        $feature = null;
        $scenario = null;
        $testDescription = null;

        $node = $test;
        while ($node !== null) {
            $class = get_class($node);
            $description = str_replace(
                "\n    ",
                "\n   ",
                $node->getDescription()
            );

            if ($description === '') {
                $node = $node->getParent();
                continue;
            }

            if ($class === 'Peridot\Core\Test') {
                $testDescription = $description;
            } elseif ($class === 'Peridot\Core\Suite') {
                if (strpos($description, 'Feature:') === 0) {
                    $feature = $description;
                } else {
                    $scenario = trim($description);
                }
            }

            $node = $node->getParent();
        }

        if ($this->lastFeature !== $feature) {
            $this->output->writeln("  " . $feature . "\n");
            $this->lastFeature = $feature;
            $this->lastScenario = null;
        }

        if ($this->lastScenario !== $scenario) {
            $this->output->writeln("   " . $scenario . "\n");
            $this->lastScenario = $scenario;
        }

        $this->output->writeln(
            $this->color(
                'error',
                sprintf("    %d) %s", $errorNumber, $testDescription)
            )
        );

        $message = sprintf(
            "       %s",
            str_replace("\n", "\n      ", $exception->getMessage())
        );
        $this->output->writeln($this->color('pending', $message));

        $class = method_exists($exception, 'getClass') ?
            $exception->getClass() :
            get_class($exception);

        $trace = method_exists($exception, 'getTrueTrace') ?
            $exception->getTrueTrace() :
            $exception->getTrace();

        array_unshift($trace, [
            'function' => $class . ' thrown',
            'file' => $exception->getFile(),
            'line' => $exception->getLine()
        ]);

        $this->outputTrace($trace);
    }
}


<?php

namespace OpenOrchestra\ModelBundle\Repository\RepositoryTrait;

use OpenOrchestra\ModelInterface\Model\StatusInterface;

/**
 * Trait StatusableTrait
 */
trait StatusableTrait
{
    /**
     * @param StatusInterface $status
     */
    public function updateEmbeddedStatus(StatusInterface $status)
    {
        $this->createQueryBuilder()
            ->updateMany()
            ->field('status.id')->equals($status->getId())
            ->field('status')->set($status)
            ->getQuery()
            ->execute();
    }

    /**
     * @param StatusInterface $status
     *
     * @return bool
     */
    public function hasStatusedElement(StatusInterface $status)
    {
        $qa = $this->createAggregationQuery();
        $qa->match(array('status._id' => new \MongoId($status->getId())));

        return 0 !== $this->countDocumentAggregateQuery($qa);
    }
}


<?php

/**
 * Manage Form
 *
 * @category  	lib
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */
namespace Venus\lib;

use \Venus\core\Mother as Mother;
use \Venus\lib\Request as Request;
use \Venus\lib\Response\Json as Json;
use \Venus\lib\Response\Mock as Mock;
use \Venus\lib\Response\Yaml as Yaml;

/**
 * This class manage the Form
 *
 * @property \Venus\lib\Request\Headers headers
 * @category  	lib
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */
class Response extends Mother
{
	const HTTP_CONTINUE = 100;
	const HTTP_SWITCHING_PROTOCOLS = 101;
	const HTTP_PROCESSING = 102;
	const HTTP_OK = 200;
	const HTTP_CREATED = 201;
	const HTTP_ACCEPTED = 202;
	const HTTP_NON_AUTHORITATIVE_INFORMATION = 203;
	const HTTP_NO_CONTENT = 204;
	const HTTP_RESET_CONTENT = 205;
	const HTTP_PARTIAL_CONTENT = 206;
	const HTTP_MULTI_STATUS = 207;
	const HTTP_ALREADY_REPORTED = 208;
	const HTTP_CONTENT_DIFFERENT = 210;
	const HTTP_IM_USED = 226;
	const HTTP_MULTIPLE_CHOICES = 300;
	const HTTP_MOVED_PERMANENTLY = 301;
	const HTTP_MOVED_TEMPORARILY = 302;
	const HTTP_SEE_OTHER = 303;
	const HTTP_NOT_MODIFIED = 304;
	const HTTP_USE_PROXY = 305;
	const HTTP_RESERVED = 306;
	const HTTP_TEMPORARY_REDIRECT = 307;
	const HTTP_PERMANENTLY_REDIRECT = 308;
	const HTTP_TOO_MANY_REDIRECTS = 310;
	const HTTP_BAD_REQUEST = 400;
	const HTTP_UNAUTHORIZED = 401;
	const HTTP_PAYMENT_REQUIRED = 402;
	const HTTP_FORBIDDEN = 403;
	const HTTP_NOT_FOUND = 404;
	const HTTP_METHOD_NOT_ALLOWED = 405;
	const HTTP_NOT_ACCEPTABLE = 406;
	const HTTP_PROXY_AUTHENTICATION_REQUIRED = 407;
	const HTTP_REQUEST_TIMEOUT = 408;
	const HTTP_CONFLICT = 409;
	const HTTP_GONE = 410;
	const HTTP_LENGTH_REQUIRED = 411;
	const HTTP_PRECONDITION_FAILED = 412;
	const HTTP_REQUEST_ENTITY_TOO_LARGE = 413;
	const HTTP_REQUEST_URI_TOO_LONG = 414;
	const HTTP_UNSUPPORTED_MEDIA_TYPE = 415;
	const HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
	const HTTP_EXPECTATION_FAILED = 417;
	const HTTP_I_AM_A_TEAPOT = 418;
	const HTTP_MISDIRECTED_REQUEST = 421;
	const HTTP_UNPROCESSABLE_ENTITY = 422;
	const HTTP_LOCKED = 423;
	const HTTP_METHOD_FAILURE = 424;
	const HTTP_UNORDERED_COLLECTION = 425;
	const HTTP_UPGRADE_REQUIRED = 426;
	const HTTP_PRECONDITION_REQUIRED = 428;
	const HTTP_TOO_MANY_REQUESTS = 429;
	const HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431;
	const HTTP_RETRY_WITH = 449;
	const HTTP_BLOCKED_BY_WINDOWS_PARENTAL_CONTROLS = 450;
	const HTTP_UNAVAILABLE_FOR_LEGAL_REASONS = 451;
	const HTTP_UNRECOVERABLE_ERROR = 456;
	const HTTP_CLIENT_HAS_CLOSED_CONNECTION = 499;
	const HTTP_INTERNAL_SERVER_ERROR = 500;
	const HTTP_NOT_IMPLEMENTED = 501;
	const HTTP_BAD_GATEWAY = 502;
	const HTTP_SERVICE_UNAVAILABLE = 503;
	const HTTP_GATEWAY_TIMEOUT = 504;
	const HTTP_VERSION_NOT_SUPPORTED = 505;
	const HTTP_VARIANT_ALSO_NEGOTIATES = 506;
	const HTTP_INSUFFICIENT_STORAGE = 507;
	const HTTP_LOOP_DETECTED = 508;
	const HTTP_BANDWIDTH_LIMIT_EXCEEDED = 509;
	const HTTP_NOT_EXTENDED = 510;
	const HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511;
	const HTTP_WEB_SERVER_IS_RETURNING_AN_UNKNOWN_ERROR = 520;

	public static $statusTexts = [
		100 => 'Continue',
		101 => 'Switching Protocols',
		102 => 'Processing',
		200 => 'OK',
		201 => 'Created',
		202 => 'Accepted',
		203 => 'Non-Authoritative Information',
		204 => 'No Content',
		205 => 'Reset Content',
		206 => 'Partial Content',
		207 => 'Multi-Status',
		208 => 'Already Reported',
		210 => 'Content Different',
		226 => 'IM Used',
		300 => 'Multiple Choices',
		301 => 'Moved Permanently',
		302 => 'Moved Temporarily',
		303 => 'See Other',
		304 => 'Not Modified',
		305 => 'Use Proxy',
		306 => '',
		307 => 'Temporary Redirect',
		308 => 'Permanent Redirect',
		310 => 'Too many Redirects',
		400 => 'Bad Request',
		401 => 'Unauthorized',
		402 => 'Payment Required',
		403 => 'Forbidden',
		404 => 'Not Found',
		405 => 'Method Not Allowed',
		406 => 'Not Acceptable',
		407 => 'Proxy Authentication Required',
		408 => 'Request Timeout',
		409 => 'Conflict',
		410 => 'Gone',
		411 => 'Length Required',
		412 => 'Precondition Failed',
		413 => 'Payload Too Large',
		414 => 'Request-URI Too Long',
		415 => 'Unsupported Media Type',
		416 => 'Requested range unsatisfiable',
		417 => 'Expectation Failed',
		418 => 'I\'m a teapot',
		421 => 'Misdirected Request',
		422 => 'Unprocessable Entity',
		423 => 'Locked',
		424 => 'Method failure',
		425 => 'Unordered Collection',
		426 => 'Upgrade Required',
		428 => 'Precondition Required',
		429 => 'Too Many Requests',
		431 => 'Request Header Fields Too Large',
		449 => 'Retry With',
		450 => 'Blocked by Windows Parental Controls',
		451 => 'Unavailable For Legal Reasons',
		456 => 'Unrecoverable Error',
		499 => 'Client has closed connection',
		500 => 'Internal Server Error',
		501 => 'Not Implemented',
		502 => 'Bad Gateway',
		503 => 'Service Unavailable',
		504 => 'Gateway Timeout',
		505 => 'HTTP Version Not Supported',
		506 => 'Variant Also Negotiates',
		507 => 'Insufficient Storage',
		508 => 'Loop Detected',
		509 => 'Bandwidth Limit Exceeded',
		510 => 'Not Extended',
		511 => 'Network Authentication Required',
		520 => 'Web server is returning an unknown error',
	];

	/**
	 * the translation language
	 * @var string
	 */
	private static $_sKindOfReturn = 'json';

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

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

	/**
	 * Response constructor.
     */
	public function __construct()
	{
		/**
		 * @return \Venus\lib\Request
         */
		$this->headers = function() { $request = new Request(); return $request->headers; };
	}

	/**
	 * set the language if you don't want take the default language of the configuration file
	 *
	 * @access public
	 * @param  string $sKindOfReturn
	 * @return void
	 */
	public static function setKindOfReturn(string $sKindOfReturn)
	{
		self::$_sKindOfReturn = $sKindOfReturn;
	}

	/**
	 * translate the content
	 *
	 * @access public
	 * @param  mixed $mContent content to translate
	 * @return mixed
	 */
	public function translate($mContent)
	{
		if (self::$_sKindOfReturn === 'yaml') { return Yaml::translate($mContent); }
		else if (self::$_sKindOfReturn === 'mock') { return Mock::translate($mContent); }
		else { return Json::translate($mContent); }
	}

	/**
	 * @return string
     */
	public function getContent() : string
	{
		return $this->content;
	}

	/**
	 * @param string $content
	 * @return Response
     */
	public function setContent(string $content) : Response
	{
		$this->content = $content;
		return $this;
	}

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

	/**
	 * @param int $statusCode
	 * @return Response
     */
	public function setStatusCode(int $statusCode) : Response
	{
		$this->statusCode = $statusCode;
		return $this;
	}

	public function send()
	{
		if ($this->getStatusCode() > 0) {
			$this->headers->set('HTTP/1.1 '.$this->getStatusCode().' '.self::$statusTexts[$this->getStatusCode()]);
		}

		echo $this->getContent();
	}
}


<?php
/**
 * This file is part of the RedKite CMS Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <info@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */

namespace RedKiteCms\Content\Theme;

use RedKiteCms\Configuration\ConfigurationHandler;
use RedKiteCms\Content\SlotsManager\SlotsManagerFactoryInterface;
use RedKiteCms\FilesystemEntity\Page;
use RedKiteCms\Tools\FilesystemTools;
use Symfony\Component\Finder\Finder;

/**
 * Class ThemeSlotsGenerator is the object assigned to update the Theme's blocks from the web site who handles the Theme itself
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Content\Theme
 */
class ThemeSlotsGenerator extends ThemeBase
{
    /**
     * @type \RedKiteCms\Content\SlotsManager\SlotsManagerFactoryInterface
     */
    private $slotsManagerFactory;

    /**
     * Constructor
     *
     * @param \RedKiteCms\Configuration\ConfigurationHandler $configurationHandler
     * @param \RedKiteCms\Content\SlotsManager\SlotsManagerFactoryInterface $slotsManagerFactory
     */
    public function __construct(ConfigurationHandler $configurationHandler, SlotsManagerFactoryInterface $slotsManagerFactory)
    {
        parent::__construct($configurationHandler);

        $this->slotsManagerFactory = $slotsManagerFactory;
    }

    /**
     * Synchronizes the site slots with the theme slots
     *
     * @param \RedKiteCms\FilesystemEntity\Page $page
     * @param array $pages
     */
    public function synchronize(Page $page, array $pages)
    {
        if (!$this->configurationHandler->isTheme()) {
            return;
        }

        foreach ($pages as $pageValues) {
            $tokens = explode("_", $pageValues["seo"][0]["language"]);
            $pageOptions = array(
                'page' => $pageValues["name"],
                'language' => $tokens[0],
                'country' => $tokens[1],
            );
            $page->render($this->configurationHandler->siteDir(), $pageOptions);
            $this->saveTemplateSlots($page->getPageSlots(), $pageValues["template"]);
        }

        $this->saveTemplateSlots($page->getCommonSlots(), 'base');
    }

    /**
     * Generates the slots from the web site that handles the theme into the Theme slots
     */
    public function generate()
    {
        $templates = array_merge(array_keys($this->templates["base"]), array_keys($this->templates["template"]));
        foreach($templates as $template) {
            $templateDir = $this->themeDir . '/' . $template;
            if (!is_dir($templateDir)) {
                continue;
            }
            $finder = new Finder();
            $files = $finder->files()->depth(0)->in($templateDir);
            foreach ($files as $file) {
                $file = (string)$file;
                $slotName = basename($file, '.json');
                $json = FilesystemTools::readFile($file);
                $slot = json_decode($json, true);

                $blocks = array();
                if (array_key_exists("blocks", $slot)) {
                    $blocks = $slot["blocks"];
                }

                $slotManager = $this->slotsManagerFactory->createSlotManager($slot["repeat"]);
                $slotManager->addSlot($slotName, $blocks);
            }
        }
    }

    private function saveTemplateSlots(array $slots, $templateName)
    {
        foreach($slots as $slot) {
            $slotName = $slot->getSlotName();
            $templateSlotFile = sprintf('%s/%s/%s.json', $this->themeDir, $templateName, $slotName);
            if (!file_exists($templateSlotFile)) {
                continue;
            }
            $templateSlotContent = json_decode(file_get_contents($templateSlotFile), true);

            $blocks = array();
            foreach($slot->getProductionEntities() as $block) {
                $blocks[] = json_decode($block, true);
            }
            $templateSlotContent["blocks"] = $blocks;

            FilesystemTools::writeFile($templateSlotFile, json_encode($templateSlotContent));
        }
    }
}


<?php
/**
 * Options configure
 * User: moyo
 * Date: 13/12/2017
 * Time: 4:29 PM
 */

namespace Carno\Console;

use Symfony\Component\Console\Command\Command;

class Configure
{
    /**
     * @var Command
     */
    private $cmd = null;

    /**
     * Configure constructor.
     * @param Command $cmd
     */
    public function __construct(Command $cmd)
    {
        $this->cmd = $cmd;
    }

    /**
     * Adds an option.
     *
     * @param string $name        The option name
     * @param string $shortcut    The shortcut (can be null)
     * @param int    $mode        The option mode: One of the InputOption::VALUE_* constants
     * @param string $description A description text
     * @param mixed  $default     The default value (must be null for InputOption::VALUE_NONE)
     *
     * @return static
     */
    public function addOption($name, $shortcut = null, $mode = null, $description = '', $default = null) : self
    {
        $this->cmd->addOption($name, $shortcut, $mode, $description, $default);
        return $this;
    }
}


<?php
/**
 * This file is part of Formular.
 *
 * (c) Philippe Gerber
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace bigwhoop\Formular\Validation\Adapter;
use bigwhoop\Formular\Validation\ValidatorInterface;
use Respect\Validation\Validator as RespectValidator;
use Respect\Validation\Exceptions\ValidationException;;

/**
 * @author Philippe Gerber <philippe@bigwhoop.ch>
 */
class RespectValidationAdapter implements ValidatorInterface
{
    /** @var string */
    private $label;

    /** @var RespectValidator */
    private $validator;

    /** @var string */
    private $errorMessage = '';

    /**
     * @param string $label
     * @param RespectValidator $validator
     */
    public function __construct($label, RespectValidator $validator)
    {
        $this->label = $label;
        $this->validator = $validator;
    }

    /**
     * {@inheritdoc}
     */
    public function isValid($value)
    {
        try {
            $this->validator->check($value);
            $this->errorMessage = '';
            return true;
        } catch (ValidationException $e) {
            $this->errorMessage = (empty($this->label) ? '' : "{$this->label}: ") . $e->getMessage();
            return false;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getErrorMessage()
    {
        return $this->errorMessage;
    }
}


<?php

/*
 * This file is part of the Predis package.
 *
 * (c) Daniele Alessandri <suppakilla@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Predis\Protocol\Text\Handler;

use Predis\CommunicationException;
use Predis\Connection\CompositeConnectionInterface;
use Predis\Protocol\ProtocolException;

/**
 * Handler for the bulk response type in the standard Redis wire protocol.
 * It translates the payload to a string or a NULL.
 *
 * @link http://redis.io/topics/protocol
 *
 * @author Daniele Alessandri <suppakilla@gmail.com>
 */
class BulkResponse implements ResponseHandlerInterface
{
    /**
     * {@inheritdoc}
     */
    public function handle(CompositeConnectionInterface $connection, $payload)
    {
        $length = (int) $payload;

        if ("$length" !== $payload) {
            CommunicationException::handle(new ProtocolException(
                $connection, "Cannot parse '$payload' as a valid length for a bulk response [{$connection->getParameters()}]"
            ));
        }

        if ($length >= 0) {
            return substr($connection->readBuffer($length + 2), 0, -2);
        }

        if ($length == -1) {
            return;
        }

        CommunicationException::handle(new ProtocolException(
            $connection, "Value '$payload' is not a valid length for a bulk response [{$connection->getParameters()}]"
        ));

        return;
    }
}


<?php
/**
 * Core functionality
 *
 * @author    G. Giunta
 * @copyright (C) G. Giunta 2013-2014
 * @license   code licensed under the GNU GPL 2.0: see README file
 */

namespace eZExtBuilder;

use pakeException;
use pakeFinder;
use pakeYaml;

class Builder
{

    static $options = null;
    static $defaultExt = null;
    protected static $options_dir = 'pake';
    const VERSION = '0.5.0-dev';
    const MIN_PAKE_VERSION = '1.7.4';

    static function getBuildDir( $opts )
    {
        $dir = $opts['build']['dir'];
        if ( $opts['create']['ezpackage'] || $opts['create']['pearpackage'] )
        {
            $dir .= '/ezextension';
        }
        return $dir;
    }

    static function getReportDir( $opts )
    {
        return $opts['report']['dir'];
    }

    static function getOptionsDir()
    {
        return self::$options_dir;
    }

    /**
     * Tries to find out the vendor dir of composer - should work both when ezextbuilder is main project and when it is
     * a dependency. Returns FALSE if not found
     *
     * @param string $vendorPrefix
     * @return string
     */
    static function getVendorDir( $vendorPrefix = 'vendor' )
    {
        if( is_dir( __DIR__ . '/../../../composer' ) && is_file( __DIR__ . '/../../../autoload.php' ) )
        {
            return realpath( __DIR__ . '/../../..' );
        }
        if( is_dir( __DIR__ . "/../$vendorPrefix/composer" ) && is_file( __DIR__ . "/../$vendorPrefix/autoload.php" ) )
        {
            return realpath( __DIR__ . "/../$vendorPrefix" );
        }
        return false;
    }

    static function getResourceDir()
    {
        return __DIR__ . '/..';
    }

    /**
     * Searches for a default extension name (i.e. when there is only 1 config file in the config dir), saves it internally
     * and returns it
     *
     * @return string
     * @throws pakeException
     */
    static function getDefaultExtName()
    {
        if ( self::$defaultExt != null )
        {
            return self::$defaultExt;
        }
        $optsDir = self::getOptionsDir();
        /// @bug corner case: what if file options-.yaml is there?
        $files = pakeFinder::type( 'file' )->name( 'options-*.yaml' )->not_name( 'options-sample.yaml' )->
            not_name( 'options-user.yaml' )->maxdepth( 0 )->in( $optsDir );
        if ( count( $files ) == 1 )
        {
            self::$defaultExt = substr( basename( $files[0] ), 8, -5 );
            pake_echo ( 'Found extension: ' . self::$defaultExt );
            return self::$defaultExt;
        }
        else if ( count( $files ) == 0 )
        {
            throw new pakeException( "Missing configuration file $optsDir/options-[extname].yaml, cannot continue" );
        }
        else
        {
            throw new pakeException( "Multiple configuration files $optsDir/options-*.yaml found, need to specify an extension name to continue\n(run ezextbuilder list-extensions for a list of available extensions)" );
        }
    }

    /**
     * Returns the list of extensions for which we have a config file available
     * @return array
     */
    static function getAvailableExtNames()
    {
        $files = pakeFinder::type( 'file' )->name( 'options-*.yaml' )->not_name( 'options-sample.yaml' )->not_name( 'options-user.yaml' )->maxdepth( 0 )->in( self::getOptionsDir() );
        foreach ( $files as $i => $file )
        {
            $files[$i] = substr( basename( $file ), 8, -5 );
        }
        return $files;
    }

    static function setConfigDir( $cliopts = array() )
    {
        if ( isset( $cliopts['config-dir'] ) )
        {
            if( !is_dir( $cliopts['config-dir'] ) )
            {
                throw new pakeException( "Could not find configuration-file directory {$cliopts['config-dir']}" );
            }
            self::$options_dir = $cliopts['config-dir'];
        }
    }

    /**
     * Loads, caches and returns the config options for a given extension
     *
     * Too smart fo our own good: we accept
     * - (nothing: extension is figured out based on single existing config file, version from config file)
     * - extension (version taken from config file)
     * - version (extension is figured out based on single existing config file, version from cli)
     * - extension, version
     * @return array
     */
    static function getOpts( $extname='', $version='', $cliopts = array() )
    {
        self::setConfigDir( $cliopts );

        if ( $version == '' && self::isValidVersion( $extname ) )
        {
            // lazy user
            $version = $extname;
            $extname = '';
        }

        if ( $version != '' && !self::isValidVersion( $version ) )
        {
            throw new PakeException( "'$version' is not a valid version number" );
        }

        if ( $extname == '' )
        {
            $extname = self::getDefaultExtName();
        }

        /// @bug we cache the options gotten from disk, but what if this function is invoked multiple times with different cli options?
        if ( !isset( self::$options[$extname] ) || !is_array( self::$options[$extname] ) )
        {
            // custom config file
            if ( isset( $cliopts['config-file'] ) )
            {
                $cfgfile = $cliopts['config-file'];
            }
            else
            {
                $cfgfile = self::getOptionsDir() . "/options-$extname.yaml";
            }

            // user-local config file
            if ( isset( $cliopts['user-config-file'] ) )
            {
                $usercfgfile = $cliopts['user-config-file'];
                if ( !is_file( $cliopts['user-config-file'] ) )
                {
                    throw new PakeException( "Could not find user-configuration-file {$cliopts['user-config-file']}" );
                }
            }
            else
            {
                $usercfgfile = self::getOptionsDir() . "/options-user.yaml";
            }

            // command-line config options
            foreach( $cliopts as $opt => $val )
            {
                if ( substr( $opt, 0, 7 ) == 'option.')
                {
                    unset( $cliopts[$opt] );

                    // transform dotted notation in array structure
                    $work = array_reverse( explode( '.', substr( $opt, 7 ) ) );
                    $built = array( array_shift( $work ) => $val );
                    foreach( $work as $key )
                    {
                        $built = array( $key=> $built );
                    }
                    self::recursivemerge( $cliopts, $built );
                }
            }

            self::loadConfiguration( $cfgfile, $extname, $version, $usercfgfile, $cliopts );
        }

        pake_echo( "Building extension $extname ( " . self::$options[$extname]['extension']['name'] . " ) version " .
            self::$options[$extname]['version']['alias'] .
            self::$options[$extname]['releasenr']['separator'] .
            self::$options[$extname]['version']['release'] );

        return self::$options[$extname];
    }

    /// @bug this only works as long as all defaults are 2 levels deep
    static protected function loadConfiguration ( $infile='', $extname='', $extversion='', $useroptsfile='', $overrideoptions=array() )
    {
        if ( $infile == '' )
        {
            $infile = self::getOptionsDir() . '/options' . ( $extname != '' ? "-$extname" : '' ) . '.yaml';
        }
        $mandatory_opts = array( /*'extension' => array( 'name' ),*/ 'version' => array( 'major', 'minor', 'release' ) );
        $default_opts = array(
            'build' => array( 'dir' => 'build' ),
            'dist' => array( 'dir' => 'dist' ),
            'report' => array( 'dir' => 'dist/report' ),
            'create' => array( 'tarball' => false, 'zip' => false, 'filelist_md5' => true, 'doxygen_doc' => false, 'ezpackage' => false, 'pearpackage' => false ),
            'version' => array( 'license' => 'GNU General Public License v2.0' ),
            'releasenr' => array( 'separator' => '-' ),
            'files' => array( 'to_parse' => array(), 'to_exclude' => array(), 'gnu_dir' => '', 'sql_files' => array( 'db_schema' => 'schema.sql', 'db_data' => 'cleandata.sql' ) ),
            'dependencies' => array( 'extensions' => array() ) );

        // load main config file
        /// @todo !important: test if !file_exists give a nicer warning than what we get from loadFile()
        $options = pakeYaml::loadFile( $infile );

        // merge data from local config file
        if ( $useroptsfile != '' && file_exists( $useroptsfile ) )
        {
            $useroptions = pakeYaml::loadFile( $useroptsfile );
            //var_dump( $useroptions );
            self::recursivemerge( $options, $useroptions );
        }

        // merge options from cli
        if ( count( $overrideoptions ) )
        {
            //var_dump( $overrideoptions );
            self::recursivemerge( $options, $overrideoptions );
        }

        // check if anything mandatory is missing
        foreach( $mandatory_opts as $key => $opts )
        {
            foreach( $opts as $opt )
            {
                if ( !isset( $options[$key][$opt] ) )
                {
                    throw new pakeException( "Missing mandatory option: $key:$opt" );
                }
            }
        }

        // hardcoded overrides
        if ( !isset( $options['extension']['name'] ) || $options['extension']['name'] == '' )
        {
            // ext. name from cli only trumps one from ext. file if not there
            $options['extension']['name'] = $extname;
        }
        if ( $extversion != '' )
        {
            $pieces = self::splitVersion( $extversion );
            $options['version']['major'] = $pieces[0];
            $options['version']['minor'] = $pieces[1];
            $options['version']['release'] = $pieces[2];
        }
        if ( !isset( $options['version']['alias'] ) || $options['version']['alias'] == '' )
        {
            $options['version']['alias'] = $options['version']['major'] . '.' . $options['version']['minor'];
        }

        // merge default values
        foreach( $default_opts as $key => $opts )
        {
            if ( isset( $options[$key] ) && is_array( $options[$key] ) )
            {
                $options[$key] = array_merge( $opts, $options[$key] );
            }
            else
            {
                /// @todo echo a warning if $options[$key] is set but not array?
                $options[$key] = $opts;
            }
        }

        self::$options[$extname] = $options;
        return true;
    }

    /**
     * Converts a property file into a yaml file
     * @param array $transform an array of transformation rules such as eg. 'sourcetag' => 'desttag' (desttag can be empty for tag removal or an array for tag expansion)
     * @todo move to a separate class to slim down base class?
     * @todo make it capable to remove complete $ext.version.alias property
     */
    static function convertPropertyFileToYamlFile( $infile, $outfile='', $transform = array(), $prepend='' )
    {
        if ( $outfile == '' )
        {
            $outfile = self::getOptionsDir() . '/options.yaml';
        }
        $current = array();
        $out = array();
        foreach ( file( $infile ) as $line )
        {
            $line = trim( $line );
            if ( $line == '' )
            {
                $out[] = '';
            }
            else if ( strpos( $line, '<!--' ) === 0 )
            {
                $out[] .= preg_replace( '/^<!-- *(.*) *-->$/', '# $1', $line );
            }
            else if ( strpos( $line, '=' ) != 0 )
            {
                $line = explode( '=', $line, 2 );
                $path = explode( '.', trim( $line[0] ) );
                foreach( $transform as $src => $dst )
                {
                    foreach( $path as $i => $element )
                    {
                        if ( $element == $src )
                        {
                            if ( $dst == '' )
                            {
                                unset( $path[$i] );
                            }
                            else if ( is_array( $dst ) )
                            {
                                array_splice( $path, $i-1, 1, $dst );
                            }
                            else
                            {
                                $path[$i] = $dst;
                            }
                        }
                    }
                }
                // elements index can have holes here, cannot trust them => reorder
                $path = array_values( $path );

                $value = $line[1];
                $token = array_pop( $path );

                if ( $path != $current )
                {
                    $skip = 0;
                    foreach( $path as $j => $element )
                    {
                        if ( $element == @$current[$j] )
                        {
                            $skip++;
                        }
                        else
                        {
                            break;
                        }
                    }

                    for( $j = $skip; $j < count( $path ); $j++ )
                        //foreach( $path as $j => $element )
                    {
                        $line = '';
                        for ( $i = 0; $i < $j; $i++ )
                        {
                            $line .= '    ';
                        }
                        $line .= $path[$j] . ':';
                        $out[] = $line;
                    }
                }
                $line = '';
                for ( $i = 0; $i < count( $path ); $i++ )
                {
                    $line .= '    ';
                }
                $line .= $token . ': ' . $value;
                $out[] = $line;
                $current = $path;
            }
            else
            {
                /// @todo log warning?
            }
        }
        pake_mkdirs( 'pake' );
        // ask confirmation if file exists
        $ok = !file_exists( $outfile ) || ( pake_input( "Destionation file $outfile exists. Overwrite? [y/n]", 'n' ) == 'y' );
        if ( $ok )
        {
            file_put_contents( $outfile, $prepend . implode( $out, "\n" ) );
            pake_echo_action( 'file+', $outfile );
        }
    }

    /**
     * Creates an archive out of a directory.
     *
     * Uses command-lne tar as Zeta Cmponents do no compress well, and pake
     * relies on phar which is buggy/unstable on old php versions
     *
     * @param boolean $no_top_dir when set, $sourcedir directory is not packaged as top-level dir in archive
     * @todo for tar formats, fix the extra "." dir packaged
     */
    static function archiveDir( $sourcedir, $archivefile, $no_top_dir=false )
    {
        // please tar cmd on win - OH MY!

        $archivefile = str_replace( '\\', '/', $archivefile );
        $sourcedir = str_replace( '\\', '/', realpath( $sourcedir ) );

        if( $no_top_dir )
        {
            $srcdir = '.';
            $workdir = $sourcedir;
        }
        else
        {
            $srcdir = basename( $sourcedir );
            $workdir = dirname( $sourcedir );
        }
        $archivedir = dirname( $archivefile );
        $extra = '';

        $tar = self::getTool( 'tar' );

        if ( substr( $archivefile, -7 ) == '.tar.gz' || substr( $archivefile, -4 ) == '.tgz' )
        {
            $cmd = "$tar -z -cvf";
            $extra = "-C " . escapeshellarg( $workdir );
            $workdir = $archivedir;
            $archivefile = basename( $archivefile );
        }
        else if ( substr( $archivefile, -8 ) == '.tar.bz2' )
        {
            $cmd = "$tar -j -cvf";
            $extra = "-C " . escapeshellarg( $workdir );
            $workdir = $archivedir;
            $archivefile = basename( $archivefile );
        }
        else if ( substr( $archivefile, -4 ) == '.tar' )
        {
            $cmd = "$tar -cvf";
            $extra = "-C " . escapeshellarg( $workdir );
            $workdir = $archivedir;
            $archivefile = basename( $archivefile );
        }
        else if ( substr( $archivefile, -4 ) == '.zip' )
        {
            $zip = self::getTool( 'zip' );
            $cmd = "$zip -9 -r";
        }
        else
        {
            throw new pakeException( "Can not determine archive type from filename: $archivefile" );
        }

        pake_sh( self::getCdCmd( $workdir ) . " && $cmd $archivefile $extra $srcdir" );

        pake_echo_action( 'file+', $archivefile );
    }

    /**
     * Find a cli executable, looking first for configured binaries, then in $PATH and/or composer bin dir.
     * Takes proper care of adding windows suffixes to tool name when needed
     *
     * @param string $tool e.g. "git"
     * @param array $opts
     * @param bool $composerBinary when true, look in vendor/bin before $PATH
     * @return string
     */
    public static function getTool( $tool, $opts=false, $composerBinary=false )
    {
        // dirty workaround
        if ( $opts == false )
        {
            $opts = self::$options[self::$defaultExt];
        }
        if ( isset( $opts['tools'][$tool] ) && is_string( $opts['tools'][$tool] ) && $opts['tools'][$tool] != '' )
        {
            return escapeshellarg( $opts['tools'][$tool] );
        }
        else if ( isset( $opts['tools'][$tool] ) && is_array( $opts['tools'][$tool] )
            && isset( $opts['tools'][$tool]['binary'] ) && $opts['tools'][$tool]['binary'] != '' )
        {
            return escapeshellarg( $opts['tools'][$tool]['binary'] );
        }
        else
        {
            if ( $composerBinary )
            {
                $vendorDir = self::getVendorDir();
                if ( file_exists( $vendorDir . "/bin/$tool" ) )
                {
                    $file = realpath( $vendorDir . "/bin/$tool" );
                    if ( strtoupper( substr( PHP_OS, 0, 3) ) === 'WIN' )
                    {
                        $file .= '.bat';
                    }
                    return escapeshellarg( $file );
                }
            }
            return escapeshellarg( pake_which( $tool ) );
        }
    }

    /**
     * Make "cd" work for all cases, even on win
     */
    static function getCdCmd( $dir )
    {
        if ( $dir[1] == ':' )
        {
            return 'cd /D ' . escapeshellarg( $dir );
        }
        return 'cd ' . escapeshellarg( $dir );
    }

    static function recursivemerge( &$a, $b )
    {
        //$a will be result. $a will be edited. It's to avoid a lot of copying in recursion
        foreach( $b as $child => $value )
        {
            if( isset( $a[$child] ) )
            {
                if( is_array( $a[$child] ) && is_array( $value ) )
                {
                    //merge if they are both arrays
                    self::recursivemerge( $a[$child], $value );
                }
                else
                {
                    // replace otherwise
                    $a[$child] = $value;
                }
            }
            else
            {
                $a[$child] = $value; //add if not exists
            }
        }
    }

    static protected function isValidVersion( $versionString )
    {
        return preg_match( '/^v?[0-9]+\.[0-9]+(\.[0-9]+.*)?$/', $versionString );
    }

    static protected function splitVersion( $versionString )
    {
        preg_match( '/v?([0-9]+)\.([0-9]+)(?:\.([0-9]+.*))?$/', $versionString, $matches );
        return array( $matches[1], $matches[2], ( isset( $matches[3] ) ? $matches[3] : 0 ) );
    }

    /**
     * Mimics ant pattern matching.
     *
     * @see http://ant.apache.org/manual/dirtasks.html#patterns
     * @todo in pake 1.6.3 and later this functionality is supported natively. To be removed
     * @todo more complete testing
     * @bug looking for " d i r / * * / " will return subdirs but not dir itself
     */
    static function pake_antpattern( $files, $rootdir )
    {
        $results = array();
        foreach( $files as $file )
        {
            //echo " Beginning with $file in dir $rootdir\n";

            // safety measure: try to avoid multiple scans
            $file = str_replace( '/**/**/', '/**/', $file );

            $type = 'any';
            // if user set '/ 'as last char: we look for directories only
            if ( substr( $file, -1 ) == '/' )
            {
                $type = 'dir';
                $file = substr( $file, 0, -1 );
            }
            // managing 'any subdir or file' as last item: trick!
            if ( strlen( $file ) >= 3 && substr( $file, -3 ) == '/**' )
            {
                $file .= '/*';
            }

            $dir = dirname( $file );
            $file = basename( $file );
            if ( strpos( $dir, '**' ) !== false )
            {
                $split = explode( '/', $dir );
                $path = '';
                foreach( $split as $i => $part )
                {
                    if ( $part != '**' )
                    {
                        $path .= "/$part";
                    }
                    else
                    {
                        //echo "  Looking for subdirs in dir $rootdir{$path}\n";
                        $newfile = implode( '/', array_slice( $split, $i + 1 ) ) . "/$file" . ( $type == 'dir'? '/' : '' );
                        $dirs = pakeFinder::type( 'dir' )->in( $rootdir . $path );
                        // also cater for the case '** matches 0 subdirs'
                        $dirs[] = $rootdir . $path;
                        foreach( $dirs as $newdir )
                        {
                            //echo "  Iterating in $newdir, looking for $newfile\n";
                            $found = self::pake_antpattern( array( $newfile ), $newdir );
                            $results = array_merge( $results, $found );
                        }
                        break;
                    }
                }
            }
            else
            {
                //echo "  Looking for $type $file in dir $rootdir/$dir\n";
                $found = pakeFinder::type( $type )->name( $file )->maxdepth( 0 )->in( $rootdir . '/' . $dir );
                //echo "  Found: " . count( $found ) . "\n";
                $results = array_merge( $results, $found );
            }
        }
        return $results;
    }

}


<?php
/**
 * Copyright (c) 2014 Andrey Ryzhov.
 * All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @package     RznViewComponent
 * @author      Andrey Ryzhov <info@rznw.ru>
 * @copyright   2014 Andrey Ryzhov.
 * @license     http://www.opensource.org/licenses/mit-license.php  MIT License
 * @link https://github.com/AndyDune/RznViewComponent for the canonical source repository
 */

namespace RznViewComponent\Service;
use Zend\ServiceManager\AbstractFactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class CacheFactory implements AbstractFactoryInterface
{
    /**
     * Determine if we can create a service with name
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @param $name
     * @param $requestedName
     * @return bool
     */
    public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
    {
        return true;
    }

    /**
     * Create service with name
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @param $name
     * @param $requestedName
     * @return mixed
     */
    public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
    {
        $config = $serviceLocator->get('config');
        if (isset($config['rznviewcomponent']['cache_adapter']))
        {
            $config = $config['rznviewcomponent']['cache_adapter'];
        }
        else
            $config = array(
                'name' => 'filesystem',
                'options' => array(
                    'ttl' => 3600,
                    'dirLevel' => 2,
                    'file_locking' => false,
                    'cacheDir' => 'data/cache',
                    'dirPermission' => 0755,
                    'filePermission' => 0666,
                ),
            );

        return \Zend\Cache\StorageFactory::factory(
            array(
                'adapter' => $config,
                'plugins' => array('serializer'),
            )
        );
    }
}


<?php
/**
 * This source file is part of Xloit project.
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the MIT License that is bundled with this package in the file LICENSE.
 * It is also available through the world-wide-web at this URL:
 * <http://www.opensource.org/licenses/mit-license.php>
 * 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@xloit.com> so we can send you a copy immediately.
 *
 * @license   MIT
 * @link      http://xloit.com
 * @copyright Copyright (c) 2016, Xloit. All rights reserved.
 */

namespace Xloit\Bridge\Zend\Form\Element;

use InvalidArgumentException;
use Traversable;
use Zend\Form\Element\Textarea;
use Zend\Stdlib\ArrayUtils;

/**
 * A {@link CkEditor} class.
 *
 * @package Xloit\Bridge\Zend\Form\Element
 */
class CkEditor extends Textarea
{
    /**
     *
     *
     * @var string
     */
    const OPTION_CONFIG = 'ckeditor_config';

    /**
     * Seed attributes.
     *
     * @var array
     */
    protected $attributes = [
        'type' => 'ckeditor'
    ];

    /**
     * CKEditor config.
     *
     * @var array
     */
    protected $editorConfig = [];

    /**
     * Accepted options for CKEditor:
     * - config: an array used in the CKEditor.config
     *
     * @param array|Traversable $options
     *
     * @return $this
     * @throws \InvalidArgumentException
     */
    public function setOptions($options)
    {
        /** @noinspection UnSafeIsSetOverArrayInspection */
        if (isset($options[static::OPTION_CONFIG])) {
            $this->setEditorConfig($options[static::OPTION_CONFIG]);

            unset($options[static::OPTION_CONFIG]);
        }

        parent::setOptions($options);

        return $this;
    }

    /**
     * Set config for Namespace CKEDITOR.config.
     *
     * @param array|Traversable $config
     *
     * @return $this
     * @throws \InvalidArgumentException
     */
    public function setEditorConfig($config)
    {
        if ($config instanceof Traversable) {
            $config = ArrayUtils::iteratorToArray($config);
        }

        if (!is_array($config)) {
            throw new InvalidArgumentException(
                'The options parameter must be an array or a Traversable'
            );
        }

        $this->editorConfig = $config;

        return $this;
    }

    /**
     * Returns config for Namespace CKEDITOR.config.
     *
     * @return array
     */
    public function getEditorConfig()
    {
        return $this->editorConfig;
    }
}


<?php

/*
 *
 * Copyright (C) 2014, Champs Libres Cooperative SCRLFS, <http://www.champs-libres.coop>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
namespace Chill\PersonBundle\Search;

use Chill\MainBundle\Search\AbstractSearch;
use Doctrine\ORM\EntityManagerInterface;
use Chill\PersonBundle\Entity\Person;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use Chill\MainBundle\Search\ParsingException;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Symfony\Component\Security\Core\Role\Role;

class PersonSearch extends AbstractSearch implements ContainerAwareInterface
{
    use ContainerAwareTrait;

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

    /**
     *
     * @var \Chill\MainBundle\Entity\User
     */
    private $user;

    /**
     *
     * @var AuthorizationHelper
     */
    private $helper;

    public function __construct(EntityManagerInterface $em,
          TokenStorage $tokenStorage, AuthorizationHelper $helper)
    {
        $this->em = $em;
        $this->user = $tokenStorage->getToken()->getUser();
        $this->helper = $helper;

        // throw an error if user is not a valid user
        if (!$this->user instanceof \Chill\MainBundle\Entity\User) {
            throw new \LogicException('The user provided must be an instance'
                  . ' of Chill\MainBundle\Entity\User');
        }
    }

    /*
     * (non-PHPdoc)
     * @see \Chill\MainBundle\Search\SearchInterface::getOrder()
     */
    public function getOrder()
    {
        return 100;
    }

    /*
     * (non-PHPdoc)
     * @see \Chill\MainBundle\Search\SearchInterface::isActiveByDefault()
     */
    public function isActiveByDefault()
    {
        return true;
    }

    public function supports($domain)
    {
        return 'person' === $domain;
    }

    /*
     * (non-PHPdoc)
     * @see \Chill\MainBundle\Search\SearchInterface::renderResult()
     */
    public function renderResult(array $terms, $start = 0, $limit = 50, array $options = array())
    {

        return $this->container->get('templating')->render('ChillPersonBundle:Person:list.html.twig',
                array(
                    'persons' => $this->search($terms, $start, $limit, $options),
                    'pattern' => $this->recomposePattern($terms, array('nationality',
                        'firstname', 'lastname', 'birthdate', 'gender'), $terms['_domain']),
                    'total' => $this->count($terms)
                ));
    }

    /**
     *
     * @param string $pattern
     * @param int $start
     * @param int $limit
     * @param array $options
     * @return Person[]
     */
    protected function search(array $terms, $start, $limit, array $options = array())
    {
        $qb = $this->createQuery($terms, 'search');

        $qb->select('p')
              ->setMaxResults($limit)
              ->setFirstResult($start);

        //order by firstname, lastname

        $qb->orderBy('p.firstName')
                ->addOrderBy('p.lastName');

        return $qb->getQuery()->getResult();
    }

    protected function count(array $terms)
    {
        $qb = $this->createQuery($terms);

        $qb->select('COUNT(p.id)');

        return $qb->getQuery()->getSingleScalarResult();
    }

    private $_cacheQuery = array();

    /**
     *
     * @param array $terms
     * @return \Doctrine\ORM\QueryBuilder
     */
    protected function createQuery(array $terms)
    {
        //get from cache
        $cacheKey = md5(serialize($terms));
        if (array_key_exists($cacheKey, $this->_cacheQuery)) {
            return clone $this->_cacheQuery[$cacheKey];
        }

        $qb = $this->em->createQueryBuilder();

        $qb->from('ChillPersonBundle:Person', 'p');

        if (array_key_exists('firstname', $terms)) {
            $qb->andWhere($qb->expr()->like('UNACCENT(LOWER(p.firstName))', ':firstname'))
                  ->setParameter('firstname', '%'.$terms['firstname'].'%');
        }

        if (array_key_exists('lastname', $terms)) {
            $qb->andWhere($qb->expr()->like('UNACCENT(LOWER(p.lastName))', ':lastname'))
                  ->setParameter('lastname', '%'.$terms['lastname'].'%');
        }

        if (array_key_exists('birthdate', $terms)) {
            try {
                $date = new \DateTime($terms['birthdate']);
            } catch (\Exception $ex) {
                throw new ParsingException('The date is '
                      . 'not parsable', 0, $ex);
            }

            $qb->andWhere($qb->expr()->eq('p.birthdate', ':birthdate'))
              ->setParameter('birthdate', $date);
        }

        if (array_key_exists('gender', $terms)) {
            if (!in_array($terms['gender'], array(Person::MALE_GENDER, Person::FEMALE_GENDER))) {
                throw new ParsingException('The gender '
                      .$terms['gender'].' is not accepted. Should be "'.Person::MALE_GENDER
                      .'" or "'.Person::FEMALE_GENDER.'"');
            }

            $qb->andWhere($qb->expr()->eq('p.gender', ':gender'))
              ->setParameter('gender', $terms['gender']);
        }

        if (array_key_exists('nationality', $terms)) {
            try {
                $country = $this->em->createQuery('SELECT c FROM '
                      . 'ChillMainBundle:Country c WHERE '
                      . 'LOWER(c.countryCode) LIKE :code')
                      ->setParameter('code', $terms['nationality'])
                      ->getSingleResult();
            } catch (\Doctrine\ORM\NoResultException $ex)  {
                throw new ParsingException('The country code "'.$terms['nationality'].'" '
                      . ', used in nationality, is unknow', 0, $ex);
            }

            $qb->andWhere($qb->expr()->eq('p.nationality', ':nationality'))
                  ->setParameter('nationality', $country);
        }

        if ($terms['_default'] !== '') {
            $grams = explode(' ', $terms['_default']);

            foreach($grams as $key => $gram) {
                $qb->andWhere($qb->expr()
                      ->like('UNACCENT(LOWER(CONCAT(p.firstName, \' \', p.lastName)))', ':default_'.$key))
                      ->setParameter('default_'.$key, '%'.$gram.'%');
            }
        }

        //restraint center for security
        $reachableCenters = $this->helper->getReachableCenters($this->user,
                new Role('CHILL_PERSON_SEE'));
        $qb->andWhere($qb->expr()
                ->in('p.center', ':centers'))
                ->setParameter('centers', $reachableCenters)
                ;

        $this->_cacheQuery[$cacheKey] = $qb;

        return clone $qb;
    }

}


<?php
namespace BlogBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * @ORM\Entity
 * @ORM\Table(name="post_translation")
 */
class PostTranslation implements \A2lix\I18nDoctrineBundle\Doctrine\Interfaces\OneLocaleInterface
{
    use \A2lix\I18nDoctrineBundle\Doctrine\ORM\Util\Translation;

    /**
     * @var string
     *
     * @ORM\Column(name="title", type="string", length=255)
     * @Assert\NotBlank
     */
    private $title;

    /**
     * @var string
     *
     * @Gedmo\Slug(fields={"title"})
     * @ORM\Column(length=255, unique=true, nullable=true)
     */
    private $slug;

    /**
     * @var string
     *
     * @ORM\Column(name="short_description", type="text")
     * @Assert\NotBlank
     */
    private $shortDescription;

    /**
     * @var string
     *
     * @ORM\Column(name="description", type="text")
     * @Assert\NotBlank
     */
    private $description;

    /**
     * @var string
     *
     * @ORM\Column(name="meta_title", type="string", length=255)
     * @Assert\NotBlank
     */
    private $metaTitle;

    /**
     * @var string
     *
     * @ORM\Column(name="meta_description", type="text")
     * @Assert\NotBlank
     */
    private $metaDescription;

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

    /**
     * Set title
     *
     * @param string $title
     *
     * @return PostTranslation
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set slug
     *
     * @param string $slug
     *
     * @return PostTranslation
     */
    public function setSlug($slug)
    {
        $this->slug = $slug;

        return $this;
    }

    /**
     * Get slug
     *
     * @return string
     */
    public function getSlug()
    {
        return $this->slug;
    }

    /**
     * Set shortDescription
     *
     * @param string $shortDescription
     *
     * @return PostTranslation
     */
    public function setShortDescription($shortDescription)
    {
        $this->shortDescription = $shortDescription;
        if($this->shortDescription == '') $this->shortDescription = strip_tags(substr ($this->shortDescription, 0, 200));

        return $this;
    }

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

    /**
     * Set description
     *
     * @param string $description
     *
     * @return PostTranslation
     */
    public function setDescription($description)
    {
        $this->description = $description;
        if($this->metaDescription == '') $this->metaDescription = strip_tags(substr ($this->description, 0, 200));

        return $this;
    }

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

    /**
     * Set metaTitle
     *
     * @param string $metaTitle
     *
     * @return PostTranslation
     */
    public function setMetaTitle($metaTitle)
    {
        $this->metaTitle = $metaTitle;

        return $this;
    }

    /**
     * Get metaTitle
     *
     * @return string
     */
    public function getMetaTitle()
    {
        return $this->metaTitle;
    }

    /**
     * Set metaDescription
     *
     * @param string $metaDescription
     *
     * @return PostTranslation
     */
    public function setMetaDescription($metaDescription)
    {
        $this->metaDescription = $metaDescription;

        return $this;
    }

    /**
     * Get metaDescription
     *
     * @return string
     */
    public function getMetaDescription()
    {
        return $this->metaDescription;
    }

}