<?php

namespace Webforge\Types;

use OutOfBoundsException;
use Webforge\Common\ArrayUtil as A;
use Webforge\Common\Util;

class CompositeType extends Type {

  /**
   * @var Webforge\Types\Type[]
   */
  protected $components = array();

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

  public function __construct() {
    $this->defineHint();
    parent::__construct();
  }

  public function getName($context = self::CONTEXT_DEFAULT) {
    if ($context === self::CONTEXT_DEBUG)
      return A::implode($this->components, '|', function ($component) {
        return $component->getName(Type::CONTEXT_DEBUG);
      });

    return parent::getName($context);
  }

  /**
   * Sollte $this->phpHint setzen
   */
  protected function defineHint() {
  }

  /**
   * @param Webforge\Types\Type $componentType
   * @param Webforge\Types\Type $componentType, ...
   *
   */
  public function setComponents() {
    $c = 1;
    $this->components = array(); // reset
    foreach (func_get_args() as $type) {
      if (!($type instanceof Type)) throw new \InvalidArgumentException('Argumente können nur Webforge\Types\Type sein. '.Util::varInfo($type).' given');
      $this->components[$c] = $type;
      $c++;
    }
    return $this;
  }

  public function addComponent(Type $type) {
    $this->components[count($this->components)+1] = $type;
    return $this;
  }

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

  /**
   * Gibt eine bestimmte Componente zurück
   *
   * @param int $num 1-basierend.
   */
  public function getComponent($num) {
    $num = (int) $num;
    if (!array_key_exists($num,$this->components))
      throw new OutOfBoundsException(sprintf("Die Komponente %d existiert nicht im Type: '%s'",$num, $this->getName()));

    return $this->components[$num];
  }

  public function getPHPHint() {
    return $this->phpHint;
  }
}


<?php

/**
 * EC-CUBE が提供する API の不足や互換性を補う静的メソッドを集約したクラスです。
 *
 * @author Seiji Nitta
 */
class Zeclib_Compat
{
    private final function __construct() {
        throw new BadMethodCallException('Do not create instance.');
    }

    /**
     * 値を JSON 形式の文字列に変換します。
     *
     * @param mixed $native
     * @throws RuntimeException
     * @return string
     */
    public static function encodeJson($native)
    {
        if (function_exists('json_decode') && function_exists('json_last_error')) {
            $json = json_encode($native);
            $error = json_last_error();
            if ($error !== JSON_ERROR_NONE) {
                $message = function_exists('json_last_error_msg') ? json_last_error_msg() : 'error code: ' . $error;
                throw new RuntimeException($message, $error);
            }
            return $json;
        }

        $encoder = new Services_JSON();
        $json = $encoder->encode($native);
        if (Services_JSON::isError($json)) {
            throw new RuntimeException($json->toString(), $json->getCode());
        }

        return $json;
    }

    /**
     * JSON 形式の文字列を値に変換します。
     *
     * @param string $json
     * @param bool $returnAssoc
     * @throws RuntimeException
     * @return mixed
     */
    public static function decodeJson($json, $returnAssoc = false)
    {
        if (function_exists('json_decode') && function_exists('json_last_error')) {
            $native = json_decode($json, $returnAssoc);
            $error = json_last_error();
            if ($error !== JSON_ERROR_NONE) {
                $message = function_exists('json_last_error_msg') ? json_last_error_msg() : 'error code: ' . $error;
                throw new RuntimeException($message, $error);
            }

            return $native;
        }

        // オートローダーを働かせて定数を定義させる。
        class_exists('Services_JSON');

        $options = $returnAssoc ? SERVICES_JSON_LOOSE_TYPE : 0;
        $decoder = new Services_JSON($options);
        $native = $decoder->decode($json);
        if (Services_JSON::isError($json)) {
            throw new RuntimeException($native->toString(), $native->getCode());
        }

        return $native;
    }
}


<?php

namespace Extlib;

use Extlib\System\IpAddress,
    Extlib\System\Url;

/**
 * Utils class
 *
 * @category    Extlib
 * @author      Lukasz Ciolecki <ciolecki.lukasz@gmail.com>
 * @copyright   Copyright (c) Lukasz Ciolecki (mart)
 */
final class Utils
{
    /**
     * Sign code namespace
     */
    const SIGN_NAMESPACE = 'sign';

    /**
     * Instance of ip address obejct
     *
     * @var \Extlib\System\IpAddress
     */
    protected $ipAddress = null;

    /**
     * Instance of url address
     *
     * @var Extlib\System\Url
     */
    protected $urlAddress = null;

    /**
     * Instance of system
     *
     * @var \Extlib\System
     */
    protected $system = null;

    /**
     * Istance of utils object
     *
     * @var Utils
     */
    static private $instance = null;

    /**
     * Instance of construct
     */
    private function __construct()
    {
        $this->system = \Extlib\System::getInstance();
        $this->ipAddress = new IpAddress();
        $this->urlAddress = new Url();
    }

    /**
     * Alias for getDomain from Extlib\System\IpAddress
     *
     * @param string $address
     * @param boolean $scheme
     * @return string
     */
    public function getDomainUrl($address, $scheme = false)
    {
        $this->urlAddress->setAddress($address);
        return $this->urlAddress->getDomain($scheme);
    }

    /**
     * Alias for getMd5Address from Extlib\System\IpAddress
     *
     * @param string $addres
     * @param boolean $scheme
     * @param boolean $www
     * @return string
     */
    public function getMd5Url($address, $scheme = true, $www = true)
    {
        $this->urlAddress->setAddress($address);
        return $this->urlAddress->getMd5Address($scheme, $www);
    }

    /**
     * Get instance of utils
     *
     * @return Utils
     */
    static public function getInstance()
    {
        if (null === self::$instance) {
            self::$instance = new Utils();
        }

        return self::$instance;
    }

    /**
     * Return short text
     *
     * @param string $text
     * @param integer $length
     *
     * @return string
     */
    public function shortText($text, $length)
    {
        $text = trim($text);
        $charset = mb_detect_encoding($text);

        if (mb_strlen($text, $charset) > $length) {
            $text = mb_substr($text, 0, $length, $charset) . '...';
        } else {
            $text = $text;
        }

        return $text;
    }

    /**
     * Return security link for mod_secdownload lighttpd.
     * http://redmine.lighttpd.net/projects/1/wiki/Docs_ModSecDownload
     *
     * @param string $domain
     * @param string $path
     * @param string $prefix
     * @param string $secret
     * @return string
     */
    public function generateSecurityLink($domain, $path, $prefix, $secret)
    {
        $path = trim($path, Url::SEPARATOR);
        $prefix = trim($prefix, Url::SEPARATOR);
        $domain = rtrim($domain, Url::SEPARATOR);

        $hex = sprintf("%08x", time());
        $md5 = md5($secret . $path . $hex);

        return sprintf('%s/%s/%s/%s/%s', $domain, $prefix, $md5, $hex, $path);
    }

    /**
     * Generate sample secret code for sign any request, etc..
     *
     * @param array $params
     * @param string $secret
     * @return string
     */
    public function generateSignCode(array $params, $secret)
    {
        ksort($params);

        if (isset($params[self::SIGN_NAMESPACE])) {
            unset($params[self::SIGN_NAMESPACE]);
        }

        return md5(implode('', $params) . $secret);
    }

    /**
     * Check sign code for request
     *
     * @param array $params
     * @param string $secret
     * @return boolean
     */
    public function checkSignCode(array $params, $secret)
    {
        if (false === isset($params[self::SIGN_NAMESPACE])) {
            return false;
        }

        return $params[self::SIGN_NAMESPACE] === $this->generateSignCode($params, $secret);
    }

    /**
     * Create "nice" date
     *
     * @param \DateTime $date
     * @return string
     */
    public function niceDate(\DateTime $date)
    {
        $now = $this->system->getDate();

        if ($now->format('Y-m-d') === $date->format('Y-m-d')) {
            return $date->format('H:i');
        } elseif ($now->format('Y-m') === $date->format('Y-m') && $date->format('d') + 1 == $now->format('d')) {
            return sprintf($this->translate('yesterday, %s'), $date->format('H:i'));
        }

        return $date->format('d-m-Y');
    }

    /**
     * Translate function
     *
     * @param string $message
     * @return string
     */
    public function translate($message)
    {
        return $message;
    }

    /**
     * Count price netto from brutto by tax
     *
     * @param double $price
     * @param int $tax
     * @return double
     * @throws \Extlib\Exception
     */
    public function priceNetto($brutto, $tax)
    {
        $tax = round((double) $tax / 100.0, 2);

        if ($tax < 0.00) {
            throw new Exception(sprintf('Tax must be greater than or equal to 0, given %s.', $tax));
        }

        if ($tax === 0.00) {
            return $brutto;
        }

        $result = $brutto / ($tax + 1);

        return round($result, 2, PHP_ROUND_HALF_UP);
    }

    /**
     * Count price butto from netto by tax
     *
     * @param double $netto
     * @param int $tax
     * @return double
     * @throws \Extlib\Exception
     */
    public function priceBrutto($netto, $tax)
    {
        $tax = round((double) $tax / 100.0, 2);

        if ($tax < 0.00) {
            throw new Exception(sprintf('Tax must be greater than or equal to 0, given %s.', $tax));
        }

        if ($tax === 0.00) {
            return $netto;
        }

        $result = $netto * ($tax + 1);

        return round($result, 2, PHP_ROUND_HALF_UP);
    }

    /**
     * Count quartile from collections by number quartile
     * http://www.stat.gov.pl/gus/definicje_PLK_HTML.htm?id=POJ-7498.htm
     *
     * @param array $collections
     * @param int $number
     * @return float
     */
    public function quartile(array $collections, $number)
    {
        sort($collections);
        $cnt = count($collections);

        if ($cnt === 0) {
            return 0;
        } elseif ($cnt === 1) {
            return $collections[0];
        }

        switch ($number) {
            case 2:
                $part = (int) $cnt / 2;
                if ($cnt % 2 === 0) {
                    return ($collections[$part - 1] + $collections[$part]) / 2;
                } else {
                    return $collections[round($cnt / 2) - 1];
                }
            default:
                if ($cnt % 2 === 0) {
                    return $collections[(round($number * $cnt / 4)) - 1];
                } else {
                    return $collections[(round($number * ($cnt + 1) / 4)) - 1];
                }
                break;
        }
    }

    /**
     * Filter url address by params (scheme, www)
     *
     * @param string $url
     * @param boolean $withScheme
     * @param boolean $withWWW
     * @return string
     */
    static public function filterUrl($url, $withScheme = true, $withWWW = true)
    {
        $info = parse_url($url);
        if (false === $info || $url === null) {
            return $url;
        }

        $scheme = isset($info['scheme']) ? $info['scheme'] : null;
        $host = isset($info['host']) ? $info['host'] : $info['path'];

        $address = $url;
        if ($withScheme && null === $scheme) {
            $address = sprintf('http://%s', $url);
        } elseif (!$withScheme && $scheme) {
            $address = str_replace($scheme . '://', '', $url);
        }

        if (false === $withWWW) {
            return preg_replace('#^www\.(.+\.)#i', '$1', $address);
        }

        return $address;
    }
}


<?php

include_once(__DIR__ . '/SaveObjectTrait.php');

/**
 * Web2All Table SaveObjectCachedTrait trait
 *
 * This trait is for saving a Table Object using a caching layer.
 * The caching layer is only used for insert queries to do bulk inserts.
 *
 * @author Merijn van den Kroonenberg
 * @copyright (c) Copyright 2017 Web2All BV
 * @since 2017-08-14
 */
trait Web2All_Table_SaveObjectCachedTrait {
  use Web2All_Table_SaveObjectTrait;

  /**
   * caching layer for DB connection
   *
   * @var Web2All_ADODB_QueryCache
   */
  protected $caching_db;

  /**
   * Flush all queries done by this object to the DB
   *
   */
  public function flush()
  {
    $this->caching_db->flushAllQueries();
  }

  /**
   * Set the querycache object (used by insert queries)
   *
   * @param Web2All_ADODB_QueryCache $querycache
   */
  public function setQueryCacheObject($querycache)
  {
    $this->caching_db=$querycache;
  }

  /**
   * Insert this object into the DB
   *
   * Inserts are cached and only flushed at object destruction,
   * unless the nocache param is true, or if a manual flush is done.
   * The caching is the default setting, but is only recommended if you
   * use this object to insert multiple records after each other. When
   * using caching, do not use $this->getDB()->Insert_ID().
   *
   * @param boolean $nocache  [optional defaults to caching inserts]
   */
  public function insertIntoDB($nocache=false)
  {
    $query='INSERT INTO '.$this->quote($this->tablename).' (';
    $values=array();
    $fields=array();
    foreach ($this->obj_to_db_trans as $obj_prop => $db_field) {

      if(isset($this->{$obj_prop})){
        if ($this->{$obj_prop} instanceof Web2All_Table_SQLOperation) {
          // if there are placeholder values, replace the placeholders with the quoted values

          $values[]=$this->substituteSQLOperationPlaceholders($this->{$obj_prop});

        }else if ($this->{$obj_prop} instanceof Web2All_Table_SQLOperationList) {
          throw new Exception("Web2All_Table_SaveObjectCachedTrait: can't insert a Web2All_Table_SQLOperationList for key value ".$obj_prop);

        }else{
          $values[]=$this->db->Quote($this->{$obj_prop});
        }

        $fields[]=$this->quote($db_field);
      }
    }
    $query.=implode(',',$fields).') VALUES ';
    if(count($fields)>0){
      $this->caching_db->doInsertQueryCached($query,$values);
    }
    if($nocache){
      $this->caching_db->flushInsertQuery($query);
    }
  }

}

?>


<?php

/**
 * ItePHP: Framework PHP (http://itephp.com)
 * Copyright (c) NewClass (http://newclass.pl)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the file LICENSE
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) NewClass (http://newclass.pl)
 * @link          http://itephp.com ItePHP Project
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace ItePHP\Component\Form;

use ItePHP\Validator\FileValidator;

/**
 * FormBuilder field
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
class FileField extends InputField{

    /**
     * @var mixed[]
     */
	private $data;

    /**
     * @var int
     */
	private $maxSize;

	/**
	 * {@inheritdoc}
	 */
	public function __construct($options){

		$options+=array(
			'multiple'=>false
		);

		$options['type']='file';

		if(!isset($options['validator'])){
			$this->setValidator(new FileValidator());
		}

		if(isset($options['accept'])){
			$this->setAccept($options['accept']);
			unset($options['accept']);
		}

		if(isset($options['maxSize'])){
			$this->setMaxSize($options['maxSize']);
			unset($options['maxSize']);
		}
		else{
			$this->setMaxSize($this->getServerMaxSize());
		}

		parent::__construct($options);
	}

	/**
	 * Set html tag multiple
	 *
	 * @param boolean $flag - value of tag multiple
	 */
	public function setMultiple($flag){
		$this->setTag('multiple',$flag);
	}

	/**
	 * Get html tag multiple
	 *
	 * @return bool
	 */
	public function isMultiple(){
		$tags=$this->getTags();
		return (isset($tags['multiple']) && $tags['multiple']);
	}

	/**
	 * Set html tag accept
	 *
	 * @param string $accept - value of tag accept
	 */
	public function setAccept($accept){
		$this->setTag('accept',$accept);
		if($this->getValidator()){
			$this->getValidator()->setOption('accept',$accept);
		}
	}

	/**
	 * Get html tag accept
	 *
	 * @return string
	 */
	public function getAccept(){
		return $this->getTag('accept');
	}

    /**
     * Set max size file
     *
     * @param int $maxSize - size in bytes
     * @throws FileMaxSizeException
     */
	public function setMaxSize($maxSize){
		$serverMaxSize=$this->getServerMaxSize();
		if($maxSize>$serverMaxSize){
			throw new FileMaxSizeException($serverMaxSize);
		}
		$this->maxSize=$maxSize;
		if($this->getValidator()){
			$this->getValidator()->setOption('maxSize',$maxSize);
		}
	}

	/**
	 * Get max size file
	 *
	 * @return int - file size in bytes
	 */
	public function getMaxSize(){
		return $this->maxSize;
	}

	/**
	 * {@inheritdoc}
	 */
	public function setData($value){
		$this->data=$value;
	}

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

	/**
	 * {@inheritdoc}
	 */
	public function clearData(){
		$this->data=null;
	}

    /**
     * {@inheritdoc}
     */
	public function componentRender(){
		$template='<input ';

		foreach($this->getTags() as $kTag=>$tag){
			if($tag!=''){
				if($kTag=='name' && $this->isMultiple()){
					$tag.='[]';
				}
				$template.=$kTag.'="'.htmlspecialchars($tag).'" ';
			}
		}
		$template.=' />';
		return $template;

	}

	/**
	 * Get max size file from config server
	 *
	 * @return int - file size in bytes
	 */
	private function getServerMaxSize(){
		return min($this->phpSizeToBytes(ini_get('post_max_size')),$this->phpSizeToBytes(ini_get('upload_max_filesize')));
	}

	/**
	 * Php size format to bytes
	 *
	 * @param string $size - php size format
	 * @return int - file size in bytes
	 */
	private function phpSizeToBytes($size){
		if (is_numeric( $size)){
			return $size;
		}
		$suffix = substr($size, -1);
		$value = substr($size, 0, -1);
		switch(strtolower($suffix)){
            /** @noinspection PhpMissingBreakStatementInspection */
            case 'p':
				$value *= 1024;
            /** @noinspection PhpMissingBreakStatementInspection */
            case 't':
				$value *= 1024;
            /** @noinspection PhpMissingBreakStatementInspection */
            case 'g':
				$value *= 1024;
            /** @noinspection PhpMissingBreakStatementInspection */
            case 'm':
				$value *= 1024;
			case 'k':
				$value *= 1024;
				break;
		}
		return $value;
	}

}


<?php

namespace nadir2\core;

/**
 * This is a class of cli-application (command line interface application).
 * @author Leonid Selikhov
 */
class CliApp extends AbstractApp
{
    /** @var self The singleton object of current class. */
    protected static $instance = null;

    /**
     * @ignore.
     */
    protected function __construct()
    {
        // Nothing here...
    }

    /**
     * It processes the call parameters of cli-script and passed them to the
     * CliCtrlResolver object.
     * @global string[] $argv The array of passed to cli-scrypt args.
     * @throws \nadir2\core\Exception It's thrown if it was attempting to call cli-scprit
     * out the command line interface.
     */
    public function handleRequest(): void
    {
        global $argv;
        if (!is_array($argv) || empty($argv)) {
            throw new Exception('Invalid value of the cli args array was given.');
        }
        (new CliCtrlResolver($argv))->run();
    }
}


<?php
namespace app\manage\block;

class FileBlock extends Block
{

    /**
     * form
     *
     * @param array $data
     * @return string
     */
    public static function form($data = [])
    {
        $data = array_merge(self::$default_form, $data);
        $data['uuid'] = md5(serialize($data));

        $html = '
';
        $html .= '
' . $data['title'] . '
';
        $html .= '
';

        $html .= '
';
        $html .= '<input type="text" class="am-input-sm" name="' . $data['name'] . '" value="' . $data['value'] . '" id="upload_file_' . $data['uuid'] . '" />';
        $html .= '';
        $html .= '
';
        $html .= '<button type="button" class="am-btn am-btn-sm am-btn-default">';
        $html .= '';
        $html .= '选择文件';
        $html .= '</button>';
        $html .= '<input type="file" class="nd-upload-file" nd-target="upload_file_' . $data['uuid'] . '" nd-option=\'' . $data['option'] . '\' />';
        $html .= '
';
        $html .= '';
        $html .= '
';

        $html .= '
';
        $html .= '
';

        return $html;
    }
}


<?php

/**
 * ItePHP: Framework PHP (http://itephp.com)
 * Copyright (c) NewClass (http://newclass.pl)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the file LICENSE
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) NewClass (http://newclass.pl)
 * @link          http://itephp.com ItePHP Project
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace ItePHP\Error;

use \Exception;

/**
 * Error dispatcher.
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
class ErrorDispatcher{

	/**
	 * Flag block propagation error events
	 *
	 * @var bool $stopPropagation
	 */
	private $stopPropagation;

	/**
	 *
	 * @var ErrorHandler[]
	 */
	private $handlers=[];

	/**
	 *
	 * @param ErrorHandler $handler
	 */
	public function addHandler(ErrorHandler $handler){
		$this->handlers[spl_object_hash($handler)]=$handler;
	}

	/**
	 *
	 * @return ErrorHandler[]
	 */
	public function getHandlers(){
		return array_values($this->handlers);
	}

	/**
	 *
	 * @param ErrorHandler $handler
	 */
	public function removeHandler(ErrorHandler $handler){
		unset($this->handlers[spl_object_hash($handler)]);
	}

	/**
	 * Shutdown callback
	 */
	public function shutdown(){
		if($this->stopPropagation)
			return;
		$error = error_get_last();
		if( $error !== NULL) {
			$file = $error["file"];
			$line = $error["line"];
			$message = $error["message"];

			$this->fireHandlers(new SyntaxException($message,$file,$line));
		}
	}

	/**
	 * Exception callback.
	 *
	 * @param Exception $exception
	 * @return bool
	 */
	public function exception(Exception $exception){
		if($this->stopPropagation){
            return false;
        }

		$this->fireHandlers($exception);

		$this->stopPropagation=true;
		return false;
	}

	/**
	 * Error callback.
	 *
	 * @param int $level
	 * @param string $message
	 * @param string $file
	 * @param int $line
	 * @throws SyntaxException
	 */
	public function error($level, $message, $file, $line){
		throw new SyntaxException($message,$file,$line,$level);
	}

	/**
	 *
	 * @param Exception $exception
	 */
	private function fireHandlers(Exception $exception){
		foreach($this->handlers as $handler){
			$handler->execute($exception);
		}
	}

}


<?php
/**
 * Definition of class PageList
 *
 * @copyright  2014-today Justso GmbH
 * @author     j.schirrmacher@justso.de
 * @package    justso\justtexts\model
 */

namespace justso\justtexts;

use justso\justapi\Bootstrap;
use justso\justapi\InvalidParameterException;
use justso\justapi\RequestHelper;
use justso\justapi\SystemEnvironmentInterface;

/**
 * Class PageList
 * @package justso\justtexts\model
 */
class PageList
{
    /**
     * List of pages
     * @var Page[]
     */
    private $pages;

    /** @var SystemEnvironmentInterface */
    private $env;

    /**
     * Initializes the page list
     */
    public function __construct(SystemEnvironmentInterface $env)
    {
        $this->env = $env;
        $this->pages = array();
        $configuration = $env->getBootstrap()->getConfiguration();
        foreach ($configuration['pages'] as $key => $value) {
            $page = $this->createPageObject($key, $value);
            $this->pages[$page->getId()] = $page;
        }
    }

    /**
     * @param string $key
     * @param string $value
     * @return \justso\justtexts\PageInterface
     */
    private function createPageObject($key, $value, RequestHelper $request = null)
    {
        return $this->env->getDIC()->get('\justso\justtexts\Page', [$key, $value, $request]);
    }

    /**
     * Returns a list of page names.
     *
     * @return string[]
     */
    public function getPages()
    {
        return array_keys($this->pages);
    }

    /**
     * Returns the Page object identified by its page name.
     *
     * @param string $name
     * @return Page
     * @throws \justso\justapi\InvalidParameterException
     */
    public function getPage($name)
    {
        if (!isset($this->pages[$name])) {
            throw new InvalidParameterException("Page not found");
        }
        return $this->pages[$name];
    }

    /**
     * Adds a new page with the given $id with data from the request.
     *
     * @param string        $id
     * @param RequestHelper $request
     * @return Page
     */
    public function addPageFromRequest($id, RequestHelper $request)
    {
        $page = $this->createPageObject(null, null, $request);
        $this->pages[$id] = $page;
        $this->persist();
        return $page;
    }

    /**
     * Changes a page's attributes according to data from the request.
     *
     * @param string        $id
     * @param RequestHelper $request
     * @return Page
     */
    public function changePageFromRequest($id, $request)
    {
        $this->getPage($id);
        $page = $this->createPageObject(null, null, $request);
        $this->pages[$id] = $page;
        $this->persist();
        return $page;
    }

    /**
     * Changes the id of a page.
     *
     * @param string $id
     * @param string $newName
     */
    public function renamePage($id, $newName)
    {
        $this->pages[$newName] = $this->getPage($id);
        unset($this->pages[$id]);
        $this->persist();
    }

    /**
     * Deletes a page.
     *
     * @param $id
     */
    public function deletePage($id)
    {
        $this->getPage($id);
        unset($this->pages[$id]);
        $this->persist();
    }

    /**
     * Persists page list in configuration file.
     */
    private function persist()
    {
        $bootstrap = Bootstrap::getInstance();
        $config = $bootstrap->getConfiguration();
        $config['pages'] = array();
        foreach ($this->pages as $page) {
            $page->appendConfig($config['pages']);
        }
        $bootstrap->setConfiguration($config);
    }
}


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

namespace cascade\components\dataInterface\connectors\db;

use canis\helpers\ArrayHelper;

/**
 * DataSource data source for database data source connectors.
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class DataSource extends \cascade\components\dataInterface\connectors\generic\DataSource
{
    /**
     * @inheritdoc
     */
    public $fieldMapClass = 'cascade\components\dataInterface\connectors\db\FieldMap';
    /**
     * @inheritdoc
     */
    public $dataItemClass = 'cascade\components\dataInterface\connectors\db\DataItem';
    /**
     * @inheritdoc
     */
    public $searchClass = 'cascade\components\dataInterface\connectors\db\Search';

    /**
     * @inheritdoc
     */
    public $keys = ['id' => 'primaryKey'];

    /**
     * Get foreign data model.
     *
     * @param int|string $key the foreign model's primary key
     *
     * @return Model foreign data model
     */
    public function getForeignDataModel($key)
    {
        $config = $this->settings['foreignPullParams'];
        if (!isset($config['where'])) {
            $config['where'] = [];
        }
        if (!empty($config['where'])) {
            $config['where'] = ['and', $config['where'], [$this->foreignModel->primaryKey() => $key]];
        } else {
            $config['where'][$this->foreignModel->primaryKey()] = $key;
        }
        //var_dump($this->foreignModel->find($config)->count('*', $this->module->db));
        return $this->foreignModel->findOne($config);
    }

    /**
     * Get unmapped foreign keys.
     *
     * @return array array without the mapped foreign keys
     */
    public function getUnmappedForeignKeys()
    {
        $mappedForeign = ArrayHelper::getColumn($this->_map, 'foreignKey');
        $u = array_diff(array_keys($this->foreignModel->meta->schema->columns), $mappedForeign);
        unset($u[$this->foreignPrimaryKeyName]);

        return $u;
    }

    /**
     * Load the foreign data items, either lazily or not.
     */
    protected function loadForeignDataItems()
    {
        $this->_foreignDataItems = [];
        if ($this->lazyForeign) {
            $primaryKeys = $this->foreignModel->findPrimaryKeys($this->settings['foreignPullParams']);
            foreach ($primaryKeys as $primaryKey) {
                $this->createForeignDataItem(null, ['foreignPrimaryKey' => $primaryKey]);
            }
        } else {
            $foreignModels = $this->foreignModel->findAll($this->settings['foreignPullParams']);
            foreach ($foreignModels as $key => $model) {
                $this->createForeignDataItem($model, []);
            }
        }
    }
}


<?php

/**
 * HTTP request object for use with Benri_Controller family.
 *
 * @link http://framework.zend.com/manual/1.12/en/zend.controller.request.html Zend_Controller_Request_Http
 */
class Benri_Controller_Request_Http extends Zend_Controller_Request_Http
{
    /**
     * Retrieve a parameter.
     *
     * Retrieves a parameter from the instance. Priority is in the order of
     * userland parameters (see {@link setParam()}), $_GET, $_POST. If a
     * parameter matching the $key is not found, null is returned.
     *
     * If the $key is an alias, the actual key aliased will be used.
     *
     * @param mixed $key
     * @param mixed $default Default value to use if key not found
     * @return mixed
     */
    public function getParam($key, $default = null)
    {
        $param = parent::getParam($key, $default);

        if (is_string($param)) {
            return trim($param);
        }

        return $param;
    }

    /**
     * Returns the REQUEST_METHOD header.
     *
     * @return string
     */
    public function getMethod()
    {
        return strtoupper(parent::getMethod());
    }

    /**
     * Returns the URL which this request was made to.
     *
     * @return string
     */
    final public function getCompleteUri()
    {
        return "{$this->getScheme()}://{$this->getHttpHost()}{$this->getRequestUri()}";
    }

    /**
     * Was the request made by GET?
     *
     * @return bool
     */
    public function isGet()
    {
        return 'GET' === $this->getMethod();
    }

    /**
     * Was the request made by DELETE?
     *
     * @return bool
     */
    public function isDelete()
    {
        return 'DELETE' === $this->getMethod();
    }

    /**
     * Was the request made by HEAD?
     *
     * @return bool
     */
    public function isHead()
    {
        return 'HEAD' === $this->getMethod();
    }

    /**
     * Was the request made by OPTIONS?
     *
     * @return bool
     */
    public function isOptions()
    {
        return 'OPTIONS' === $this->getMethod();
    }

    /**
     * Was the request made by PATCH?
     *
     * @return bool
     */
    public function isPatch()
    {
        return 'PATCH' === $this->getMethod();
    }

    /**
     * Is the request a Javascript XMLHttpRequest and has the PJAX header?
     *
     * Should work with jQuery, Prototype, possibly others.
     *
     * @return bool
     */
    public function isPjaxRequest()
    {
        return $this->isXmlHttpRequest() && $this->getHeader('X-PJAX');
    }

    /**
     * Was the request made by POST?
     *
     * @return bool
     */
    public function isPost()
    {
        return 'POST' === $this->getMethod();
    }

    /**
     * Was the request made by PUT?
     *
     * @return bool
     */
    public function isPut()
    {
        return 'PUT' === $this->getMethod();
    }
}


<?php

namespace Dwo\FlaggingBundle\Config;

use Dwo\Flagging\Factory\FeatureFactory;
use Dwo\Flagging\Model\FeatureInterface;
use Dwo\Flagging\Model\FeatureManagerInterface;

/**
 * @author Dave Www <davewwwo@gmail.com>
 */
class FeatureManager implements FeatureManagerInterface
{
    /**
     * @var array
     */
    protected $featuresRaw;

    /**
     * @var FeatureInterface[]
     */
    protected $features;

    /**
     * @param array $features
     */
    public function __construct(array $features = array())
    {
        $this->featuresRaw = $features;
    }

    /**
     * @param string $name
     *
     * @return FeatureInterface
     */
    public function findFeatureByName($name)
    {
        if (!isset($this->features[$name]) && isset($this->featuresRaw[$name])) {
            $this->features[$name] = FeatureFactory::buildFeature($name, $this->featuresRaw[$name]);
        }

        return isset($this->features[$name]) ? $this->features[$name] : null;
    }

    /**
     * @return FeatureInterface[]
     */
    public function findAllFeatures()
    {
        $features = [];
        foreach ($this->featuresRaw as $name => $data) {
            if (null !== $feature = $this->findFeatureByName($name)) {
                $features[$name] = $feature;
            }
        }

        return $features;
    }

    /**
     * @param FeatureInterface $feature
     */
    public function saveFeature(FeatureInterface $feature)
    {
        $this->features[$feature->getName()] = $feature;
    }
}


<?php
namespace eMacros\Runtime\Filter;

use eMacros\Runtime\GenericFunction;

class FilterVar extends GenericFunction {
	/**
	 * Filters a value according to a specified filter
	 * Usage: (var 'yes' 'boolean')
	 * Returns: mixed
	 * (non-PHPdoc)
	 * @see \eMacros\Runtime\GenericFunction::execute()
	 */
	public function execute(array $arguments) {
		if (empty($arguments)) throw new \BadFunctionCallException("FilterVar: No parameters found.");
		if (!isset($arguments[1])) throw new \BadFunctionCallException("FilterVar: No filter has been defined.");
		if (!in_array($arguments[1], filter_list()))
			throw new \InvalidArgumentException(sprintf("FilterVar: '%s' is not a valid filter.", strval($arguments[1])));
		return filter_var($arguments[0], filter_id($arguments[1]));
	}
}
?>


<?php

namespace Dothiv\Bundle\ContentfulBundle\Translation;

use Dothiv\Bundle\ContentfulBundle\Exception\InvalidArgumentException;
use Dothiv\Bundle\ContentfulBundle\Output\Content;
use Symfony\Component\Translation\Loader\LoaderInterface;
use Symfony\Component\Translation\MessageCatalogue;

class ContentfulStringsLoader implements LoaderInterface
{
    /**
     * @var Content
     */
    private $content;

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

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

    /**
     * @param Content $content
     * @param string  $contentType
     * @param string  $keyLocale
     */
    public function __construct(Content $content, $contentType, $keyLocale)
    {
        $this->content     = $content;
        $this->contentType = $contentType;
        $this->keyLocale   = $keyLocale;
    }

    /**
     * {@inheritdoc}
     */
    public function load($resource, $locale, $domain = 'messages')
    {
        $catalogue = new MessageCatalogue($locale);
        try {
            foreach ($this->content->buildEntries($this->contentType, $locale) as $string) {
                $value = isset($string->value) ? $string->value : '';
                $v     = $locale == $this->keyLocale ? $string->code : $value;
                $catalogue->set($string->code, $v, $domain);
            }
        } catch (InvalidArgumentException $e) {
            // pass.
        }
        return $catalogue;
    }
}


<?php
namespace eMacros\Runtime\Collection;

use eMacros\Runtime\GenericFunction;

class Car extends GenericFunction {
	/**
	 * Returns the head element on a list
	 * Usage: (Array:car (array 1 2 3))
	 * Returns: mixed
	 * (non-PHPdoc)
	 * @see \eMacros\Runtime\GenericFunction::execute()
	 */
    public function execute(array $arguments) {
    	if (empty($arguments)) throw new \BadFunctionCallException("Car: No parameters found.");
        list($list) = $arguments;

        if ($list instanceof \Iterator) {
            $list->rewind();
            $value = $list->valid() ? $list->current() : null;
        }
        elseif ($list instanceof \IteratorAggregate) {
            $iter = $list->getIterator();
            $iter->rewind();
            $value = $iter->valid() ? $iter->current() : null;
        }
        elseif (is_array($list))
        	$value = !empty($list) ? array_shift($list) : null;
        elseif ($list instanceof \ArrayAccess)
        	$value = isset($list[0]) ? $list[0] : null;
        else
        	throw new \InvalidArgumentException('Car: Parameter is not a list.');
        return $value;
    }
}


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

namespace Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress;

use Praxigento\BonusHybrid\Repo\Data\Downline as EBonDwnl;
use Praxigento\Downline\Repo\Data\Customer as ECustomer;

/**
 * Process to calculate Phase1 compression.
 */
class Phase1
    implements \Praxigento\Core\Api\App\Service\Process
{
    /** Calculation ID to reference in compressed PV transfers  */
    const IN_CALC_ID = 'calcId';
    /** Customers downline tree (plain) to the end of calculation period */
    const IN_DWNL_PLAIN = 'dwnlPlain';
    /**#@+ string: keys names for attributes in plain downline. */
    const IN_KEY_CALC_ID = 'keyCalcId';
    const IN_KEY_CUST_ID = 'keyCustId';
    const IN_KEY_DEPTH = 'keyDepth';
    const IN_KEY_PARENT_ID = 'keyParentId';
    const IN_KEY_PATH = 'keyPath';
    const IN_KEY_PV = 'keyPv';
    /**#@-  */
    /** PV by customer ID map */
    const IN_PV = 'pv';
    /** Calculation results, data for compression table */
    const OUT_COMPRESSED = 'compressed';
    /** Compressed PV transfers to save in DB */
    const OUT_PV_TRANSFERS = 'pvTransfers';

    /** @var \Praxigento\Downline\Repo\Dao\Customer */
    private $daoCustDwnl;
    /** @var  \Praxigento\BonusHybrid\Api\Helper\Scheme */
    private $hlpScheme;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Z\Helper\GetCustomersIds */
    private $hlpSignUpDebitCust;
    /** @var \Praxigento\Downline\Api\Helper\Tree */
    private $hlpTree;

    public function __construct(
        \Praxigento\BonusHybrid\Api\Helper\Scheme $hlpScheme,
        \Praxigento\Downline\Api\Helper\Tree $hlpTree,
        \Praxigento\BonusHybrid\Service\Calc\Z\Helper\GetCustomersIds $hlpSignUpDebitCust,
        \Praxigento\Downline\Repo\Dao\Customer $daoCustDwnl
    ) {
        $this->hlpScheme = $hlpScheme;
        $this->hlpTree = $hlpTree;
        $this->hlpSignUpDebitCust = $hlpSignUpDebitCust;
        $this->daoCustDwnl = $daoCustDwnl;
    }

    /**
     * @param array $compressionData array [$custId=>[$pv, $parentId], ... ] with compression data.
     * @return \Praxigento\Downline\Repo\Data\Snap[]
     */
    private function composeTree($compressionData)
    {
        /* prepare request data: convert to [$customer=>parent, ... ] form */
        $converted = [];
        foreach ($compressionData as $custId => $data) {
            /* 0 - PV, 1 - parentId */
            $converted[$custId] = $data[1];
        }
        $snap = $this->hlpTree->expandMinimal($converted);
        unset($converted);
        /* convert 2D array to array of entities */
        $result = [];
        foreach ($snap as $one) {
            $entity = new \Praxigento\Downline\Repo\Data\Snap($one);
            $result[] = $entity;
        }
        return $result;
    }

    public function exec(\Praxigento\Core\Data $ctx)
    {
        /* extract working variables from execution context */
        $calcId = $ctx->get(self::IN_CALC_ID);
        $mapPv = $ctx->get(self::IN_PV);
        $plain = $ctx->get(self::IN_DWNL_PLAIN);
        $keyCalcId = $ctx->get(self::IN_KEY_CALC_ID);
        $keyCustId = $ctx->get(self::IN_KEY_CUST_ID);
        $keyParentId = $ctx->get(self::IN_KEY_PARENT_ID);
        $keyDepth = $ctx->get(self::IN_KEY_DEPTH);
        $keyPath = $ctx->get(self::IN_KEY_PATH);
        $keyPv = $ctx->get(self::IN_KEY_PV);

        /* prepare result vars */
        $result = new \Praxigento\Core\Data();
        /* array with PV compression transfers results (see \Praxigento\BonusHybrid\Repo\Data\Entity\Compression\Phase1\Transfer\Pv) */
        $pvTransfers = [];

        /* define local working data */
        $qLevels = $this->hlpScheme->getQualificationLevels();
        $forcedCustomers = $this->hlpScheme->getForcedQualificationCustomersIds();
        $signupDebitCustomers = $this->hlpSignUpDebitCust->exec();

        /* prepare intermediary structures for calculation */
        $mapCustomer = $this->getCustomersMap();
        $mapPlain = $this->hlpTree->mapById($plain, $keyCustId);
        $mapDepth = $this->hlpTree->mapByTreeDepthDesc($plain, $keyCustId, $keyDepth);
        $mapTeams = $this->hlpTree->mapByTeams($plain, $keyCustId, $keyParentId);

        /**
         * perform processing
         */
        /* array for compression results: [$customerId => [$pvCompressed, $parentCompressed], ... ]*/
        $compression = [];
        foreach ($mapDepth as $depth => $levelCustomers) {
            foreach ($levelCustomers as $custId) {
                $pv = isset($mapPv[$custId]) ? $mapPv[$custId] : 0;
                $dwnlEntry = $mapPlain[$custId];
                $parentId = is_array($dwnlEntry) ? $dwnlEntry[$keyParentId] : $dwnlEntry->get($keyParentId);
                $custData = $mapCustomer[$custId];
                $scheme = $this->hlpScheme->getSchemeByCustomer($custData);
                $level = $qLevels[$scheme]; // qualification level for current customer
                $isForced = in_array($custId, $forcedCustomers);
                $isSignUpDebit = in_array($custId, $signupDebitCustomers);
                if (($pv >= $level) || $isForced || $isSignUpDebit) {
                    if (isset($compression[$custId])) {
                        $pvExist = $compression[$custId][0];
                        $pvNew = $pv + $pvExist;
                        $compression[$custId] = [$pvNew, $parentId];
                    } else {
                        $compression[$custId] = [$pv, $parentId];
                    }
                } else {
                    /* move PV up to the closest qualified parent (parent's level is used for qualification) */
                    $path = is_array($dwnlEntry) ? $dwnlEntry[$keyPath] : $dwnlEntry->get($keyPath);
                    $parents = $this->hlpTree->getParentsFromPathReversed($path);
                    $foundParentId = null;
                    foreach ($parents as $newParentId) {
                        $parentData = $mapCustomer[$newParentId];
                        $parentParentId = $parentData->getParentRef();
                        /* MOBI-942: use parent scheme to qualify parents */
                        $parentScheme = $this->hlpScheme->getSchemeByCustomer($parentData);
                        $parentLevel = $qLevels[$parentScheme]; // qualification level for current parent
                        $pvParent = isset($mapPv[$newParentId]) ? $mapPv[$newParentId] : 0;
                        if (
                            ($pvParent >= $parentLevel) ||
                            (in_array($newParentId, $forcedCustomers))
                        ) {
                            $foundParentId = $newParentId;
                            /* add PV to the closest qualified parent */
                            if ($pv > 0) {
                                if (isset($compression[$foundParentId])) {
                                    $pvExist = $compression[$foundParentId][0];
                                    $pvNew = $pv + $pvExist;
                                    $compression[$foundParentId][0] = $pvNew;
                                } else {
                                    $compression[$foundParentId] [0] = $pv;
                                    $compression[$foundParentId] [1] = $parentParentId;
                                }
                                // $pv PV are transferred from customer #$custId to his qualified parent #$foundParentId
                                $pvTransferItem = new \Praxigento\BonusHybrid\Repo\Data\Compression\Phase1\Transfer\Pv();
                                $pvTransferItem->setCalcRef($calcId);
                                $pvTransferItem->setCustFromRef($custId);
                                $pvTransferItem->setCustToRef($foundParentId);
                                $pvTransferItem->setPv($pv);
                                $pvTransfers[] = $pvTransferItem;
                            }
                            break;
                        }
                    }
                    unset($parents);

                    /* change parent for all siblings of the unqualified customer */
                    if (isset($mapTeams[$custId])) {
                        $team = $mapTeams[$custId];
                        foreach ($team as $memberId) {
                            if (isset($compression[$memberId])) {
                                /* if null set customer own id to indicate root node */
                                $compression[$memberId][1] = is_null($foundParentId) ? $memberId : $foundParentId;
                            }
                        }
                    }
                }
            }
        }
        unset($mapCustomer);
        unset($mapDepth);
        unset($mapTeams);
        /* compose compressed tree */
        /** @var \Praxigento\Downline\Repo\Data\Snap[] $cmprsSnap */
        $cmprsSnap = $this->composeTree($compression);

        /* re-build result tree (compressed) from source tree (plain) */
        $cmprsResultDirty = $this->rebuildTree($calcId, $cmprsSnap, $mapPlain, $keyCalcId, $keyParentId, $keyDepth, $keyPath);
        /* then unset items IDs after plain tree (MOBI-1502) */
        $cmprsResult = [];
        /**
         * @var int $key
         * @var EBonDwnl $item
         */
        foreach ($cmprsResultDirty as $key => $item) {
            if (is_array($item)) {
                $cloned = $item;
                $cloned[EBonDwnl::A_ID] = null;
            } else {
                $cloned = clone $item;
                $cloned->setId(null);
            }
            $cmprsResult[$key] = $cloned;
        }

        /* add compressed PV data */
        $cmprsSnap = $this->populateCompressedSnapWithPv($cmprsResult, $compression, $keyPv);

        /* put result data into output */
        $result->set(self::OUT_COMPRESSED, $cmprsSnap);
        $result->set(self::OUT_PV_TRANSFERS, $pvTransfers);
        return $result;
    }

    /**
     * Actual customers downline mapped by customer ID.
     *
     * @return \Praxigento\Downline\Repo\Data\Customer[]
     */
    private function getCustomersMap()
    {
        /** @var \Praxigento\Downline\Repo\Data\Customer[] $customers */
        $customers = $this->daoCustDwnl->get();
        $result = $this->hlpTree->mapById($customers, ECustomer::A_CUSTOMER_REF);
        return $result;
    }

    /**
     * Populate phase 1 compressed $tree with compressed PV data.
     *
     * @param array $tree compressed tree w/o PV data
     * @param array $compressionData compression data with compressed PV
     * @return array compressed tree with PV data
     */
    private function populateCompressedSnapWithPv($tree, $compressionData, $keyPv)
    {
        $result = $tree;
        foreach ($compressionData as $custId => $data) {
            /* 0 - PV, 1 - parentId */
            $pv = $data[0];
            $entry = $result[$custId];
            if (is_array($entry)) {
                $entry[$keyPv] = $pv;
            } else {
                $entry->set($keyPv, $pv);
            }
            $result[$custId] = $entry;
        }
        return $result;
    }

    /**
     * Rebuild target tree from source ($mapPlain) using compressed snap data.
     *
     * @param int $calcId phase1 compression calculation ID
     * @param \Praxigento\Downline\Repo\Data\Snap[] $compressed
     * @param array|\Praxigento\Core\Data[] $mapPlain
     * @param string $keyCalcId
     * @param string $keyParentId
     * @param string $keyDepth
     * @param string $keyPath
     * @return array|\Praxigento\Core\Data[]
     */
    private function rebuildTree($calcId, $compressed, $mapPlain, $keyCalcId, $keyParentId, $keyDepth, $keyPath)
    {
        $result = [];
        /** @var \Praxigento\Downline\Repo\Data\Snap $item */
        foreach ($compressed as $item) {
            $snapCustId = $item->getCustomerRef();
            $snapParentId = $item->getParentRef();
            $snapDepth = $item->getDepth();
            $snapPath = $item->getPath();
            $entry = $mapPlain[$snapCustId];
            if (is_array($entry)) {
                $entry[$keyCalcId] = $calcId;
                $entry[$keyParentId] = $snapParentId;
                $entry[$keyDepth] = $snapDepth;
                $entry[$keyPath] = $snapPath;
            } else {
                $entry->set($keyCalcId, $calcId);
                $entry->set($keyParentId, $snapParentId);
                $entry->set($keyDepth, $snapDepth);
                $entry->set($keyPath, $snapPath);
            }
            $result[$snapCustId] = $entry;
        }
        return $result;
    }
}


<?php

namespace Dothiv\Bundle\ContentfulBundle\Cache;

use Doctrine\Common\Cache\Cache;
use Dothiv\Bundle\ContentfulBundle\Event\ContentfulViewEvent;
use Dothiv\Bundle\ContentfulBundle\Entity\Config;
use Dothiv\Bundle\ContentfulBundle\Repository\ConfigRepositoryInterface;
use Dothiv\Bundle\ContentfulBundle\Event\ContentfulEntryEvent;
use PhpOption\Option;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Stores modification times for requests based on the
 * update date of content items rendered on the page.
 */
class RequestLastModifiedCache
{
    use LoggerAwareTrait;

    const CONFIG_NAME = 'last_modified_content.min_last_modified';

    /**
     * @var Cache
     */
    private $cache;

    /**
     * @var \DateTime
     */
    private $lastModifiedContent;

    /**
     * @var Config
     */
    private $lastMinModified;

    /**
     * @var \DateTime
     */
    private $lastMinModifiedDate;

    /**
     * @var array
     */
    private $itemIds = array();

    /**
     * @var ConfigRepositoryInterface
     */
    private $configRepo;

    /**
     * @param Cache                     $cache
     * @param ConfigRepositoryInterface $configRepo
     */
    public function __construct(Cache $cache, ConfigRepositoryInterface $configRepo)
    {
        $this->cache      = $cache;
        $this->configRepo = $configRepo;
    }

    /**
     * Collect ViewEvents to build lastModified date.
     *
     * @param ContentfulViewEvent $e
     */
    public function onViewCreate(ContentfulViewEvent $e)
    {
        $viewMeta                           = $e->getView()->cfMeta;
        $updated                            = $viewMeta['updatedAt'];
        $this->itemIds[$viewMeta['itemId']] = true;
        if ($this->lastModifiedContent === null) {
            $this->lastModifiedContent = $updated;
        } else {
            if ($this->lastModifiedContent < $updated) {
                $this->lastModifiedContent = $updated;
            }
        }
    }

    /**
     * Returns the last modified date for a request.
     *
     * @param Request $request
     *
     * @return \DateTime
     */
    public function getLastModified(Request $request)
    {
        $minModified          = $this->getLastMinModifiedDate();
        $optionalLastModified = Option::fromValue($this->cache->fetch($this->getCacheKeyRequest(sha1($request->getUri()), 'lastmodified')), false);
        if ($optionalLastModified->isEmpty()) {
            return $minModified;
        }
        return max($minModified, new \DateTime($optionalLastModified->get()));
    }

    /**
     * Stores the last modified date for a request.
     *
     * @param Request   $request
     * @param \DateTime $lastModified
     */
    public function setLastModified(Request $request, \DateTime $lastModified)
    {
        $this->cache->save($this->getCacheKeyRequest(sha1($request->getUri()), 'lastmodified'), $lastModified->format('r'));

        foreach ($this->itemIds as $itemId => $bool) {
            $key                             = $this->getCacheKeyItem($itemId, 'uri');
            $urisForItem                     = Option::fromValue($this->cache->fetch($key), false)->getOrElse(array());
            $urisForItem[$request->getUri()] = $bool;
            $this->cache->save($key, $urisForItem);
            Option::fromValue($this->logger)->map(function (LoggerInterface $logger) use ($request, $itemId) {
                $logger->debug(sprintf('[ContentfulBundle:RequestLastModifiedCache] "%s" is used on "%s".', $itemId, $request->getUri()));
            });
        }
    }

    /**
     * @param string $uri
     * @param string $type
     *
     * @return string
     */
    protected function getCacheKeyRequest($uri, $type)
    {
        $cacheKey = 'dothiv_contentful-request_uri-' . $type . '-' . $uri;
        return $cacheKey;
    }

    /**
     * @param string $itemId
     * @param string $type
     *
     * @return string
     */
    protected function getCacheKeyItem($itemId, $type)
    {
        $cacheKey = 'dothiv_contentful-item_uri-' . $itemId . '-' . $type;
        return $cacheKey;
    }

    /**
     * Returns the last modified for the content that has been loaded in the current scope.
     *
     * @return \DateTime
     */
    public function getLastModifiedContent()
    {
        $lastMinModifiedDate = $this->getLastMinModifiedDate();
        return max($this->lastModifiedContent, $lastMinModifiedDate);
    }

    /**
     * This method gets called when an Entry is update and updates the
     * last modified time cache entry for every page it is used.
     *
     * There is a problem with this implementation: adding _new_ child elements
     * is not picked up because they were never used before.
     *
     * @param ContentfulEntryEvent $e
     */
    public function onEntryUpdate(ContentfulEntryEvent $e)
    {
        $entry             = $e->getEntry();
        $key               = $this->getCacheKeyItem($entry->getId(), 'uri');
        $urisForItemOption = Option::fromValue($this->cache->fetch($key), false);
        if ($urisForItemOption->isEmpty()) {
            Option::fromValue($this->logger)->map(function (LoggerInterface $logger) use ($entry) {
                $logger->debug(sprintf('[ContentfulBundle:RequestLastModifiedCache] Entry "%s" is not used.', $entry->getId()));
            });
            return;
        }
        // Update
        $urisForItem = $urisForItemOption->get();
        foreach ($urisForItem as $uri => $bool) {
            $key          = $this->getCacheKeyRequest(sha1($uri), 'lastmodified');
            $lastModified = $this->cache->fetch($key);
            if ($lastModified >= $entry->getUpdatedAt()->format('r')) {
                Option::fromValue($this->logger)->map(function (LoggerInterface $logger) use ($lastModified, $uri) {
                    $logger->debug(sprintf('[ContentfulBundle:RequestLastModifiedCache] "%s" was last modified at "%s". Entry is older.', $uri, $lastModified));
                });
                continue;
            }
            $this->cache->save($key, $entry->getUpdatedAt()->format('r'));
            Option::fromValue($this->logger)->map(function (LoggerInterface $logger) use ($entry, $uri) {
                $logger->debug(sprintf('[ContentfulBundle:RequestLastModifiedCache] Setting last modified time for "%s" to "%s".', $uri, $entry->getUpdatedAt()->format('r')));
            });
        }
    }

    /**
     * @return \DateTime
     */
    protected function getLastMinModifiedDate()
    {
        if ($this->lastMinModified === null) {
            $this->lastMinModified     = $this->configRepo->get(static::CONFIG_NAME);
            $this->lastMinModifiedDate = new \DateTime($this->lastMinModified->getValue());
        }
        return $this->lastMinModifiedDate;
    }
}


<?php

namespace OpenOrchestra\ModelBundle\Document;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use OpenOrchestra\ModelInterface\Model\ReadSiteAliasInterface;
use OpenOrchestra\ModelInterface\Model\SiteAliasInterface;
use OpenOrchestra\Mapping\Annotations as ORCHESTRA;
use OpenOrchestra\ModelInterface\Model\SiteInterface;
use OpenOrchestra\MongoTrait\Sitemapable;
use OpenOrchestra\MongoTrait\SoftDeleteable;
use OpenOrchestra\ModelInterface\Exceptions\MainAliasNotExisting;

/**
 * Description of Site
 *
 * @ODM\Document(
 *   collection="site",
 *   repositoryClass="OpenOrchestra\ModelBundle\Repository\SiteRepository"
 * )
 * @ORCHESTRA\Document(
 *   generatedField="siteId",
 *   sourceField="name",
 *   serviceName="open_orchestra_model.repository.site",
 * )
 */
class Site implements SiteInterface
{
    use Sitemapable;
    use SoftDeleteable;

    /**
     * @var string $id
     *
     * @ODM\Id
     */
    protected $id;

    /**
     * @var string $siteId
     *
     * @ODM\Field(type="string")
     */
    protected $siteId;

    /**
     * @var array
     *
     * @ODM\Field(type="collection")
     */
    protected $blocks = array();

    /**
     * @var array
     *
     * @ODM\Field(type="collection")
     */
    protected $contentTypes = array();

    /**
     * @var string $metaAuthor
     *
     * @ODM\Field(type="string")
     */
    protected $metaAuthor;

    /**
     * @var string $robotsTxt
     *
     * @ODM\Field(type="string")
     */
    protected $robotsTxt;

    /**
     * @var string $name
     *
     * @ODM\Field(type="string")
     */
    protected $name;

    /**
     * @var string $templateSet
     *
     * @ODM\Field(type="string")
     */
    protected $templateSet;

    /**
     * @var string $templateNodeRoot
     *
     * @ODM\Field(type="string")
     */
    protected $templateNodeRoot;

    /**
     * @var Collection
     *
     * @ODM\EmbedMany(targetDocument="OpenOrchestra\ModelInterface\Model\SiteAliasInterface", strategy="set")
     */
    protected $aliases;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->robotsTxt = SiteInterface::ROBOTS_TXT_DEFAULT;
        $this->aliases = new ArrayCollection();
    }

    /**
     * @param SiteAliasInterface $alias
     */
    public function addAlias(SiteAliasInterface $alias)
    {
        $this->aliases->set(uniqid(SiteInterface::PREFIX_SITE_ALIAS), $alias);
    }

    /**
     * @param SiteAliasInterface $alias
     */
    public function removeAlias(SiteAliasInterface $alias)
    {
        $this->aliases->removeElement($alias);
    }

    /**
     * @return Collection
     */
    public function getAliases()
    {
        return $this->aliases;
    }

    /**
     * @param string $block
     */
    public function addBlock($block)
    {
        $this->blocks[] = $block;
    }

    /**
     * @param string $block
     */
    public function removeBlock($block)
    {
        $newBlocks = array();
        foreach ($this->blocks as $blockSite) {
            if ($blockSite !== $block) {
                $newBlocks[] = $blockSite;
            }
        }
        $this->blocks = $newBlocks;
    }

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

    /**
     * @param array $contentTypes
     */
    public function setContentTypes($contentTypes)
    {
        $this->contentTypes = $contentTypes;
    }

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

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

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

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

    /**
     * Set metaAuthor
     *
     * @param string $metaAuthor
     */
    public function setMetaAuthor($metaAuthor)
    {
        $this->metaAuthor = $metaAuthor;
    }

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

    /**
     * Set robotsTxt
     *
     * @param string $robotsTxt
     */
    public function setRobotsTxt($robotsTxt)
    {
        $this->robotsTxt = $robotsTxt;
    }

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

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

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

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

    /**
     * Set templateSet
     *
     * @param string $templateSet
     */
    public function setTemplateSet($templateSet)
    {
        $this->templateSet = $templateSet;
    }

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

    /**
     * Set templateNodeRoot
     *
     * @param string $templateNodeRoot
     */
    public function setTemplateNodeRoot($templateNodeRoot)
    {
        $this->templateNodeRoot = $templateNodeRoot;
    }

    /**
     * Get all languages of the site
     *
     * @return array
     */
    public function getLanguages()
    {
        $languages = array();

        /** @var SiteAliasInterface $siteAlias */
        foreach ($this->getAliases() as $siteAlias) {
            $language = $siteAlias->getLanguage();
            if (!in_array($language, $languages)) {
                $languages[] = $language;
            }
        }

        return $languages;
    }

    /**
     * Return one of the default site language
     *
     * @return string
     */
    public function getDefaultLanguage()
    {
        return $this->getMainAlias()->getLanguage();
    }

    /**
     * @return ReadSiteAliasInterface
     *
     * @throws MainAliasNotExisting
     */
    public function getMainAlias()
    {
        /** @var SiteAliasInterface $alias */
        foreach ($this->getAliases() as $alias) {
            if ($alias->isMain()) {
                return $alias;
            }
        }

        throw new MainAliasNotExisting();
    }

    /**
     * return int
     */
    public function getMainAliasId()
    {
        return $this->aliases->indexOf($this->getMainAlias());
    }

    /**
     * Return alias id for given language
     *
     * @param string $language
     *
     * @return int
     */
    public function getAliasIdForLanguage($language)
    {
        /** @var ReadSiteAliasInterface $alias */
        foreach ($this->aliases as $key => $alias) {
            if ($alias->getLanguage() == $language) {
                return $key;
            }
        }

        return null;
    }
}


<?php
/*
 * 模块加载器.
 *
 * This file is part of wulacms.
 *
 * (c) Leo Ning <windywany@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace wula\cms;

use wulaphp\app\App;
use wulaphp\app\Module;
use wulaphp\app\ModuleLoader;
use wulaphp\cache\RtCache;

class CmfModuleLoader extends ModuleLoader {
	private $modules = [];

	public function __construct() {
		if (WULACMF_INSTALLED) {
			$ms = RtCache::get('modules@cmf');
			if ($ms) {
				$this->modules = $ms;
			} else {
				$mt  = App::table('module');
				$mts = $mt->findAll(null, 'name,version,status,kernel');
				$ms  = [];
				foreach ($mts->toArray() as $m) {
					$ms[ $m['name'] ] = $m;
				}
				$this->modules = $ms;
				RtCache::add('modules@cmf', $ms);
				unset($mt);
			}
		}
	}

	/**
	 * @param \wulaphp\app\Module $module
	 *
	 * @return bool
	 */
	public function isEnabled(Module $module) {
		if (WULACMF_INSTALLED) {
			$name = $module->getNamespace();
			if (isset($this->modules[ $name ])) {
				$m                        = $this->modules[ $name ];
				$module->installed        = true;
				$module->installedVersion = $m['version'];
				$module->upgradable       = version_compare($module->getCurrentVersion(), $m['version'], '>');
				$module->enabled          = $m['status'] == 1;
				$module->isKernel         = $module->isKernel || $m['kernel'] == 1;

				return $module->enabled;
			} else if (!$module instanceof CmfModule) {
				$module->installed        = true;
				$module->enabled          = true;
				$module->installedVersion = $module->getCurrentVersion();
				$module->isKernel         = true;

				return true;
			}

			return false;
		} else {
			$name = $module->getNamespace();
			if ($name == 'system') {
				return true;
			}
		}

		return false;
	}
}


<?php

/**
 * Type validator
 *
 * @category    Venus
 * @package     Venus\lib\Validator
 * @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\Validator;

/**
 * Type validator
 *
 * @category    Venus
 * @package     Venus\lib\Validator
 * @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 Type extends Common
{
    /**
     * type
     * @var type
     */
    private $_sType = '';

    /**
     * constructor
     *
     * @access public
     * @param  string $sType type
     * @return Type
     */
    public function __construct(string $sType)
    {
        $this->_sType = $sType;
    }

    /**
     * validate the Type
     *
     * @access public
     * @param  string $sValue
     * @return bool
     */
    public function validate(string $sValue = null) : bool
    {
        if ($this->_sType == 'DateTime') {

            if (preg_match('#^[0-9]{4}/[0-9]{2}/[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}#', $sValue)) {

                return true;
            }
        }

        return false;
    }
}


<?php

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

namespace In2pire\Cli\Task;

use Symfony\Component\Process\Process;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use In2pire\Cli\Configuration;
use In2pire\Component\Utility\NestedArray;
use In2pire\Cli\Task\Container as TaskContainer;

abstract class CliTask
{
    /**
     * Error code.
     */
    const RETURN_ERROR = 1;

    /**
     * Success code.
     */
    const RETURN_SUCCESS = 0;

    /**
     * Task ID.
     *
     * @var string
     */
    protected $id = 'default';

    /**
     * Running command.
     *
     * @var In2pire\Cli\Command\CliCommand
     */
    protected $command;

    /**
     * Settings.
     *
     * @var mixed
     */
    protected $settings;

    /**
     * Task data.
     *
     * @var array
     */
    protected $data = [];

    /**
     * Return code.
     *
     * @var integer
     */
    protected $returnCode = 0;

    /**
     * Dependency Tasks.
     * @var array
     */
    protected $dependencies = [];

    /**
     * Constructor.
     *
     * @param In2pire\Cli\Command\CliCommand $command
     *   Running command.
     */
    public function __construct($command)
    {
        $this->command = $command;
        $this->settings = Configuration::getInstance()->getAll('task.' . $this->id, true);

        if (!empty($this->settings['dependencies']) && is_array($this->settings['dependencies'])) {
            $dependencies = $this->settings['dependencies'];
            $this->dependencies = array();

            foreach ($dependencies as $dependency) {
                if (is_array($dependency)) {
                    $this->dependencies[key($dependency)] = reset($dependency);
                } else {
                    $this->dependencies[$dependency] = array('mapping' => array());
                }
            }
        }
    }

    /**
     * Get Task ID.
     *
     * @return string
     *   ID
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Get running command.
     *
     * @return In2pire\Cli\Command\CliCommand
     *   Command.
     */
    public function getCommand()
    {
        return $this->command;
    }

    /**
     * Get all settings.
     *
     * @return array
     *   Settings.
     */
    public function getSettings()
    {
        return $this->settings;
    }

    /**
     * Get setting.
     *
     * @param string $name
     *   Setting name.
     * @param mixed $default
     *   (optional) Default value when setting is not in file.
     *
     * @return mixed
     *   Setting value.
     */
    public function getSetting($name, $default = null)
    {
        return array_key_exists($name, $this->settings) ? $this->settings[$name] : $default;
    }

    /**
     * Set Data for running.
     */
    public function setData($name, $value = null)
    {
        if (is_array($name)) {
            $this->data = $name;
        } else {
            $this->data[$name] = $value;
        }

        return $this;
    }

    /**
     * Is successful?
     *
     * @return boolean
     *   Return code.
     */
    public function isSuccessful()
    {
        return $this->returnCode == static::RETURN_SUCCESS;
    }

    protected function runDependency($task, $taskInfo, InputInterface $input, OutputInterface $output)
    {
        $data = $this->data;

        if (!empty($taskInfo['mapping'])) {
            foreach ($taskInfo['mapping'] as $newKey => $oldKey) {
                $data[$newKey] = NestedArray::getValueByNamespace($data, $oldKey);
            }
        }

        $resturn = $task->setData($data)->run($input, $output);
        return $task->isSuccessful();
    }

    protected function executeDependencies(InputInterface $input, OutputInterface $output)
    {
        $return = true;

        foreach ($this->dependencies as $taskId => $taskInfo) {
            $task = TaskContainer::create($taskId, $this->command);

            // Failed to execute task.
            if ($task && !$this->runDependency($task, $taskInfo, $input, $output)) {
                $return = false;
                break;
            }
        }

        return $return;
    }

    /**
     * Do post-run execution.
     *
     * @param InputInterface  $input
     *   Input.
     * @param OutputInterface $output
     *   Output.
     * @param int $code
     *   Return code.
     *
     * @return In2pire\Cli\Task\CliTask
     *   The called object.
     */
    protected function doPreRun(InputInterface $input, OutputInterface $output)
    {
        // Do nothing
        return $this;
    }

    /**
     * Do post-run execution.
     *
     * @param InputInterface  $input
     *   Input.
     * @param OutputInterface $output
     *   Output.
     * @param int $code
     *   Return code.
     *
     * @return In2pire\Cli\Task\CliTask
     *   The called object.
     */
    protected function doPostRun(InputInterface $input, OutputInterface $output, $code)
    {
        // Do nothing
        return $this;
    }

    /**
     * Execute task.
     *
     * @param InputInterface  $input
     *   Input.
     * @param OutputInterface $output
     *   Output.
     *
     * @return int $code
     *   Return code.
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        // Do nothing.
    }

    /**
     * Run task.
     *
     * @param InputInterface  $input
     *   Input.
     * @param OutputInterface $output
     *   Output.
     *
     * @return int $code
     *   Return code.
     */
    public function run(InputInterface $input, OutputInterface $output)
    {
        $this->returnCode = static::RETURN_SUCCESS;
        $this->doPreRun($input, $output);

        if (!$this->executeDependencies($input, $output)) {
            // Failed to run dependencies.
            $this->returnCode = static::RETURN_ERROR;
        } else {
            // Execute task.
            $this->returnCode = (int) $this->execute($input, $output);
        }

        $this->doPostRun($input, $output, $this->returnCode);

        return $this->returnCode;
    }
}


<?php

class SDIS62_Rest_Server extends Zend_Rest_Server
{

    private $_jsonResponse = true;

    /**
     * Change les headers par défaut
     *
     * @param array     $headers    Header sous forme de tableau
     */
    public function setHeaders($headers)
    {
        if ($headers && is_array($headers)) {
            $this->_headers = $headers;
        }

    }

    /**
     * Change la valeur de jsonResponse
     * (true : renvoie des informations json / false : n'en renvoie pas)
     *
     * @param bool      $isJsonResponse     La valeur de json Response
     */
    public function setJsonResponse($isJsonResponse)
    {
        $this->_jsonResponse = $isJsonResponse;
    }

    /**
     * Implement Zend_Server_Interface::handle()
     *
     * @param  array $request
     * @throws Zend_Rest_Server_Exception
     * @return string|void
     */
    public function handle($request = false)
    {
        // Si aucun header de préciser, on annonce qu'on va envoyer du Json
        // (Rétrocompatibilité)
        if ( ! $this->_headers || empty($this->_headers)) {
            $this->_headers = array('Content-Type: application/json');
        }

        // On paramètre le detecteur de mise en défaut
        $failed = false;

        // Copié collé de Zend_Rest_Server::handle() ... (mais un peu custom quand même !)
        if (!$request)
        {
            $request = $_REQUEST;
        }

        if (isset($request['method']))
        {
            $this->_method = $request['method'];

            if (isset($this->_functions[$this->_method]))
            {
                if ($this->_functions[$this->_method] instanceof Zend_Server_Reflection_Function || $this->_functions[$this->_method] instanceof Zend_Server_Reflection_Method && $this->_functions[$this->_method]->isPublic())
                {
                    $request_keys = array_keys($request);
                    array_walk($request_keys, array(__CLASS__, "lowerCase"));
                    $request = array_combine($request_keys, $request);

                    $func_args = $this->_functions[$this->_method]->getParameters();

                    $calling_args = array();
                    $missing_args = array();

                    foreach ($func_args as $arg)
                    {
                        if(isset($request[strtolower($arg->getName())]))
                        {
                            $calling_args[] = $request[strtolower($arg->getName())];
                        }
                        elseif($arg->isOptional())
                        {
                            $calling_args[] = $arg->getDefaultValue();
                        }
                        else
                        {
                            $missing_args[] = $arg->getName();
                        }
                    }

                    foreach ($request as $key => $value)
                    {
                        if (substr($key, 0, 3) == 'arg')
                        {
                            $key = str_replace('arg', '', $key);
                            $calling_args[$key] = $value;

                            if (($index = array_search($key, $missing_args)) !== false)
                            {
                                unset($missing_args[$index]);
                            }
                        }
                    }

                    // Sort arguments by key -- @see ZF-2279
                    ksort($calling_args);

                    $result = false;

                    if (count($calling_args) < count($func_args))
                    {
                        require_once 'Zend/Rest/Server/Exception.php';
                        $result = $this->fault(new Zend_Rest_Server_Exception('Invalid Method Call to ' . $this->_method . '. Missing argument(s): ' . implode(', ', $missing_args) . '.'), 400);
                        $failed = true;
                    }

                    if (!$result && $this->_functions[$this->_method] instanceof Zend_Server_Reflection_Method)
                    {
                        // Get class
                        $class = $this->_functions[$this->_method]->getDeclaringClass()->getName();

                        if ($this->_functions[$this->_method]->isStatic())
                        {
                            // for some reason, invokeArgs() does not work the same as
                            // invoke(), and expects the first argument to be an object.
                            // So, using a callback if the method is static.
                            $result = $this->_callStaticMethod($class, $calling_args);
                        }
                        else
                        {
                            // Object method
                            $result = $this->_callObjectMethod($class, $calling_args);
                        }
                    }
                    elseif(!$result)
                    {
                        try {
                            $result = call_user_func_array($this->_functions[$this->_method]->getName(), $calling_args); //$this->_functions[$this->_method]->invokeArgs($calling_args);
                        } catch (Exception $e) {
                            $result = $this->fault($e);
                            $failed = true;
                        }
                    }
                }
                else
                {
                    require_once "Zend/Rest/Server/Exception.php";
                    $result = $this->fault(new Zend_Rest_Server_Exception("Unknown Method '$this->_method'."), 404);
                    $failed = true;
                }
            } else {
                require_once "Zend/Rest/Server/Exception.php";
                $result = $this->fault(new Zend_Rest_Server_Exception("Unknown Method '$this->_method'."), 404);
                $failed = true;
            }
        } else {
            require_once "Zend/Rest/Server/Exception.php";
            $result = $this->fault(new Zend_Rest_Server_Exception("No Method Specified."), 404);
            $failed = true;
        }

        // Si la réponse attendu est en JSON, ou le résultat à failed,
        // on parse la réponse en json
        if ($failed || $this->_jsonResponse) {
                $response = Zend_Json::Encode(array(
                'response' => $result,
                'status' => $failed ? 'failed' : 'success'
            ));
        } else {
            $response = '';
        }

        // On gère la fonction returnResponse()
        if (!$this->returnResponse()) {
            if (!headers_sent()) {
                foreach ($this->_headers as $header) {
                    header($header);
                }
            }

            echo $response;
            return;
        }

        // On envoie le json
        return $response;
     }

    /**
     * Implement Zend_Server_Interface::fault()
     *
     * Creates XML error response, returning DOMDocument with response.
     *
     * @param string|Exception $fault Message
     * @param int $code Error Code
     * @return DOMDocument
     */
    public function fault($exception = null, $code = null)
    {
        // Copié collé de Zend_Server_Rest::fault() ...
        if (isset($this->_functions[$this->_method]))
        {
            $function = $this->_functions[$this->_method];
        }
        elseif (isset($this->_method))
        {
            $function = $this->_method;
        }
        else
        {
            $function = 'rest';
        }

        if ($function instanceof Zend_Server_Reflection_Method)
        {
            $class = $function->getDeclaringClass()->getName();
        }
        else
        {
            $class = false;
        }

        if ($function instanceof Zend_Server_Reflection_Function_Abstract)
        {
            $method = $function->getName();
        }
        else
        {
            $method = $function;
        }

        // Message et code d'erreur
        $exception_message = null;
        $code_message = null;

        if($exception instanceof Exception)
        {
            $code_message = $exception->getCode();
            $exception_message = $exception->getMessage();
        }
        elseif(($exception !== null) || 'rest' == $function)
        {
            $exception_message = 'An unknown error occured. Please try again.';
        }
        else
        {
            $exception_message = 'Call to ' . $method . ' failed.';
        }

        // Headers to send
        if ($code_message === null || (404 != $code_message))
        {
            $this->_headers[] = 'HTTP/1.0 400 Bad Request';
        }
        else
        {
            $this->_headers[] = 'HTTP/1.0 404 File Not Found';
        }

        // On envoie le message d'erreur
        return $exception_message;
    }

    /**
     * Implement Zend_Server_Interface::loadFunctions()
     *
     * @todo Implement
     * @param array $functions
     */
    public function loadFunctions($functions)
    {
        throw new Exception('Not implemented');
    }

    /**
     * Implement Zend_Server_Interface::setPersistence()
     *
     * @todo Implement
     * @param int $mode
     */
    public function setPersistence($mode)
    {
        throw new Exception('Not implemented');
    }
}


<?php
namespace Poirot\Queue\Queue;

use Poirot\Queue\Exception\exIOError;
use Poirot\Queue\Interfaces\iPayload;
use Poirot\Queue\Interfaces\iPayloadQueued;
use Poirot\Queue\Interfaces\iQueueDriver;
use Poirot\Queue\Payload\QueuedPayload;

class InMemoryQueue
    implements iQueueDriver
{
    protected $queues = [];

    /**
     * Push To Queue
     *
     * @param iPayload $payload Serializable payload
     * @param string   $queue
     *
     * @return iPayloadQueued
     * @throws exIOError
     */
    function push($payload, $queue = null)
    {
        $payload = clone $payload;

        if (null === $queue && $payload instanceof iPayloadQueued)
            $queue = $payload->getQueue();

        $qPayload = $payload;
        if (! $payload instanceof iPayloadQueued ) {
            $qPayload = new QueuedPayload($payload);
            $qPayload = $qPayload
                ->withUID( \Poirot\Std\generateUniqueIdentifier(24) )
            ;
        }

        /** @var QueuedPayload $qPayload */
        $qPayload = $qPayload->withQueue( $this->_normalizeQueueName($queue) );

        ## Persist Queued Payload
        #
        $uid      = $qPayload->getUID();
        $qName    = $qPayload->getQueue();
        $time     = $qPayload->getCreatedTimestamp();

        if (! isset($this->queues[$qName]) )
            $this->queues[$qName] = [];

        $ps = &$this->queues[$qName];
        $ps[$uid] = [
            'id'      => $uid,
            'queue'   => $qName,
            'payload' => $qPayload,
            'created_timestamp' => $time,
        ];

        return $qPayload;
    }

    /**
     * Pop From Queue
     *
     * note: when you pop a message from queue you have to
     *       release it when worker done with it.
     *
     *
     * @param string $queue
     *
     * @return iPayloadQueued|null
     * @throws exIOError
     */
    function pop($queue = null)
    {
        $queue = $this->_normalizeQueueName($queue);

        if (! isset($this->queues[$queue]) )
            return null;

        if ( null === $item = array_pop($this->queues[$queue]) )
            return null;

        $payload = $item['payload'];
        return $payload;
    }

    /**
     * Release an Specific From Queue By Removing It
     *
     * @param iPayloadQueued|string $id
     * @param null|string           $queue
     *
     * @return void
     * @throws exIOError
     */
    function release($id, $queue = null)
    {
        if ( $id instanceof iPayloadQueued ) {
            $arg   = $id;
            $id    = $arg->getUID();
            $queue = $arg->getQueue();
        }

        if (! isset($this->queues[$queue]) )
            return;

        if (! isset($this->queues[$queue][(string)$id]) )
            return;

        unset($this->queues[$queue][(string)$id]);
    }

    /**
     * Find Queued Payload By Given ID
     *
     * @param string $id
     * @param string $queue
     *
     * @return iPayloadQueued|null
     * @throws exIOError
     */
    function findByID($id, $queue = null)
    {
        $queue = $this->_normalizeQueueName($queue);

        if (! isset($this->queues[$queue]) )
            return null;

        if (! isset($this->queues[$queue][(string)$id]) )
            return null;

        $item = $this->queues[$queue][(string)$id];

        $payload = $item['payload'];
        return $payload;
    }

    /**
     * Get Queue Size
     *
     * @param string $queue
     *
     * @return int
     * @throws exIOError
     */
    function size($queue = null)
    {
        $queue = $this->_normalizeQueueName($queue);

        return (isset($this->queues[$queue])) ? count($this->queues[$queue]) : 0;
    }

    /**
     * Get Queues List
     *
     * @return string[]
     * @throws exIOError
     */
    function listQueues()
    {
        return array_keys($this->queues);
    }

    // ..

    /**
     * @param string $queue
     * @return string
     */
    protected function _normalizeQueueName($queue)
    {
        if ($queue === null)
            return $queue = 'general';

        return strtolower( (string) $queue );
    }
}


<?php
namespace Lead\Benchmark;

class Task
{
    /**
     * Task name.
     *
     * @var string
     */
    protected $_name = '';

    /**
     * Repeat number.
     *
     * @var integer
     */
    protected $_repeat = 1;

    /**
     * Duration time (in seconds).
     *
     * @var float
     */
    protected $_duration = 0;

    /**
     * The average taken time per task (in seconds).
     *
     * @var float
     */
    protected $_average = 0;

    /**
     * The time rate.
     *
     * @var float
     */
    protected $_rate = 0;

    /**
     * The memory usage (in bytes)
     *
     * @var integer
     */
    protected $_memory = 0;

    /**
     * Start time (in seconds).
     *
     * @var float
     */
    protected $_startTime = 0;

    /**
     * Start up memory usage (in bytes)
     *
     * @var integer
     */
    protected $_startMemory = 0;

    /**
     * Indicates if the task failed
     *
     * @var boolean
     */
    protected $_failed = false;

    /**
     * Starts the timer
     */
    public function start()
    {
        $this->_startTime = microtime(true);
        $this->_startMemory = memory_get_usage(true);
    }

    /**
     * Stops the timer.
     */
    public function end()
    {
        $this->_duration = microtime(true) - $this->_startTime;
        $this->_average = $this->_duration / $this->_repeat;
        $this->_rate = $this->_repeat / $this->_duration;
        $this->_memory = memory_get_usage(true) - $this->_startMemory;
    }

    /**
     * Gets/sets the name.
     *
     * @param  integer $repeat The task name to set or none the get the current one.
     * @return integer         The repeat value or `$this` on set.
     */
    public function name($name = null)
    {
        if (!func_num_args()) {
            return $this->_name;
        }
        $this->_name = $name;
        return $this;
    }

    /**
     * Gets/sets the repeat number.
     *
     * @param  integer $repeat The repeat value to set or none the get the current one.
     * @return integer         The repeat value or `$this` on set.
     */
    public function repeat($repeat = null)
    {
        if (!func_num_args()) {
            return $this->_repeat;
        }
        $this->clear();
        $this->_repeat = $repeat;
        return $this;
    }

    /**
     * Returns the average taken time.
     *
     * @return float The time taken per task, in average (in seconds).
     */
    public function average()
    {
        return $this->_average;
    }

    /**
     * Returns the time rate.
     *
     * @return float The time rate.
     */
    public function rate()
    {
        return $this->_rate;
    }

    /**
     * Returns the whole taken time.
     *
     * @return float The time taken (in seconds).
     */
    public function duration()
    {
        return $this->_duration;
    }

    /**
     * Returns the memory usage.
     *
     * @return integer The memory usage (in bytes).
     */
    public function memory()
    {
        return $this->_memory;
    }

    /**
     * Indicates whether the task failed or not.
     *
     * @var boolean $fail The failing value.
     */
    public function failed($fail = true)
    {
        if (!func_num_args()) {
            return $this->_failed;
        }
        $this->_failed = $fail;
        return $this;
    }

    /**
     * Clears the stats.
     */
    public function clear()
    {
        $this->_repeat = 1;
        $this->_startTime = 0;
        $this->_duration = 0;
        $this->_average = 0;
        $this->_rate = 0;
        $this->_startMem = 0;
        $this->_memory = 0;
    }
}


<?php
/**
 * This file is part of SoloProyectos common library.
 *
 * @author  Gonzalo Chumillas <gchumillas@email.com>
 * @license https://github.com/soloproyectos-php/http/blob/master/LICENSE The MIT License (MIT)
 * @link    https://github.com/soloproyectos-php/http
 */
namespace soloproyectos\http;
use soloproyectos\text\Text;

/**
 * Class Http.
 *
 * This class is used to send POST requests.
 *
 * @package Http
 * @author  Gonzalo Chumillas <gchumillas@email.com>
 * @license https://github.com/soloproyectos-php/http/blob/master/LICENSE The MIT License (MIT)
 * @link    https://github.com/soloproyectos-php/http
 */
class Http
{
    /**
     * Appends parameters to a given url.
     *
     * For example:
     * ```php
     * echo Http::addParams("http://www.mysite.php", array("username" => "John", "id" => 101));
     * ```
     *
     * @param string $url    URL
     * @param array  $params Associative array of parameters
     *
     * @return strings.
     */
    static public function addParams($url, $params)
    {
        $query = parse_url($url, PHP_URL_QUERY);
        $separator = (Text::isEmpty($query)? "?" : "&");
        return Text::concat($separator, $url, http_build_query($params));
    }

    /**
     * Encodes a text to be used in a XHTML document.
     *
     * @param string $text Arbitrary text
     *
     * @return string
     */
    static public function encode($text)
    {
        return htmlspecialchars($text);
    }

    /**
     * Decodes an HTML text segment.
     *
     * @param string $text HTML segment
     *
     * @return string
     */
    static public function decode($text)
    {
        return htmlspecialchars_decode($text);
    }
}


<?php
namespace HtSettingsModule\Factory;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use HtSettingsModule\Service\SettingsService;

class SettingsServiceFactory implements FactoryInterface
{
    /**
     * Gets settings service
     *
     * @param  ServiceLocatorInterface $serviceLocator
     * @return SettingsService
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $options = $serviceLocator->get('HtSettingsModule\Options\ModuleOptions');
        $settingsService = new SettingsService(
            $options,
            $serviceLocator->get('HtSettingsModule_SettingsMapper'),
            $serviceLocator->get('HtSettingsModule\Service\NamespaceHydratorProvider')
        );
        if ($options->getCacheOptions()->isEnabled()) {
            $settingsService->setCacheManager($serviceLocator->get('HtSettingsModule\Service\CacheManager'));
        }

        return $settingsService;
    }
}


<?php

namespace OpenOrchestra\ModelBundle\Repository;

use OpenOrchestra\ModelInterface\Model\StatusInterface;
use OpenOrchestra\ModelInterface\Repository\StatusRepositoryInterface;
use OpenOrchestra\Repository\AbstractAggregateRepository;
use OpenOrchestra\Pagination\Configuration\PaginateFinderConfiguration;
use Solution\MongoAggregation\Pipeline\Stage;

/**
 * Class StatusRepository
 */
class StatusRepository extends AbstractAggregateRepository implements StatusRepositoryInterface
{
    /**
     * @param string $id
     *
     * @return StatusInterface
     */
    public function findOneById($id)
    {
        return parent::findOneById($id);
    }

    /**
     * @parameter array $order
     *
     * @return array
     */
    public function findNotOutOfWorkflow(array $order = array('name' => 1))
    {
        $qa = $this->createAggregationQuery();
        $qa->match(array('outOfWorkflow' => false));
        $qa->sort($order);

        return $this->hydrateAggregateQuery($qa);
    }

    /**
     * @return StatusInterface
     */
    public function findOneByInitial()
    {
        $qa = $this->createAggregationQuery();
        $qa->match(array(
            'initialState' => true,
            'outOfWorkflow' => false
        ));

        return $this->singleHydrateAggregateQuery($qa);
    }

    /**
     * @return StatusInterface
     */
    public function findOneByPublished()
    {
        $qa = $this->createAggregationQuery();
        $qa->match(array(
            'publishedState' => true,
            'outOfWorkflow' => false
        ));

        return $this->singleHydrateAggregateQuery($qa);
    }

    /**
     * @return array
     */
    public function findByAutoPublishFrom()
    {
        $qa = $this->createAggregationQuery();
        $qa->match(array(
            'autoPublishFromState' => true,
            'outOfWorkflow' => false
        ));

        return $this->hydrateAggregateQuery($qa);
    }

    /**
     * @return StatusInterface
     */
    public function findOnebyAutoUnpublishTo()
    {
        $qa = $this->createAggregationQuery();
        $qa->match(array(
            'autoUnpublishToState' => true,
            'outOfWorkflow' => false
        ));

        return $this->singleHydrateAggregateQuery($qa);
    }

    /**
     * @return StatusInterface
     */
    public function findOneByTranslationState()
    {
        $qa = $this->createAggregationQuery();
        $qa->match(array(
            'translationState' => true,
            'outOfWorkflow' => false
        ));

        return $this->singleHydrateAggregateQuery($qa);
    }

    /**
     * @return StatusInterface
     */
    public function findOneByOutOfWorkflow()
    {
        $qa = $this->createAggregationQuery();
        $qa->match(array('outOfWorkflow' => true));

        return $this->singleHydrateAggregateQuery($qa);
    }

    /**
     * @param PaginateFinderConfiguration $configuration
     *
     * @return array
     */
    public function findForPaginate(PaginateFinderConfiguration $configuration)
    {
        $qa = $this->createAggregationQuery();

        $this->filterSearch($configuration, $qa);

        $order = $configuration->getOrder();
        if (!empty($order)) {
            $qa->sort($order);
        }

        $qa->skip($configuration->getSkip());
        $qa->limit($configuration->getLimit());

        return $this->hydrateAggregateQuery($qa);
    }

    /**
     * @return int
     */
    public function countNotOutOfWorkflow()
    {
        $qa = $this->createAggregationQuery();
        $qa->match(array('outOfWorkflow' => false));

        return $this->countDocumentAggregateQuery($qa);
    }

    /**
     * @param PaginateFinderConfiguration $configuration
     *
     * @return int
     */
    public function countWithFilter(PaginateFinderConfiguration $configuration)
    {
        $qa = $this->createAggregationQuery();
        $this->filterSearch($configuration, $qa);

        return $this->countDocumentAggregateQuery($qa);
    }

    /**
     * @param PaginateFinderConfiguration $configuration
     * @param Stage                       $qa
     *
     * @return array
     */
    protected function filterSearch(PaginateFinderConfiguration $configuration, Stage $qa)
    {
        $label = $configuration->getSearchIndex('label');
        $language = $configuration->getSearchIndex('language');

        if (null !== $label && '' !== $label && null !== $language && '' !== $language) {
            $qa->match(array('labels.' . $language => new \MongoRegex('/.*'.$label.'.*/i')));
        }
        $qa->match(array('outOfWorkflow' => false));

        return $qa;
    }

    /**
     * @param array $statusIds
     *
     * @throws \Exception
     */
    public function removeStatuses(array $statusIds)
    {
        $statusMongoIds = array();
        foreach ($statusIds as $statusId) {
            $statusMongoIds[] = new \MongoId($statusId);
        }

        $qb = $this->createQueryBuilder();
        $qb->remove()
            ->field('id')->in($statusMongoIds)
            ->getQuery()
            ->execute();
    }
}