<?php

namespace Mediawiki\Db\Service;

use Mediawiki\DataModel\Redirect;
use Mediawiki\DataModel\Title;
use PDO;

class RedirectListGetter {

	/**
	 * @var PDO
	 */
	protected $db;

	/**
	 * @param PDO $db
	 */
	public function __construct( PDO $db ) {
		$this->db = $db;
	}

	/**
	 * @todo option to and from namespaces!
	 *
	 * @param int $namespace the namespace you want to get redirect from
	 *
	 * @return Redirect[]
	 */
	public function getRedirects( $namespace = 0 ) {
		$statement = $this->db->prepare( $this->getQuery() );
		$statement->execute( array( ':namespace' => $namespace ) );
		$rows = $statement->fetchAll();

		$redirects = array();
		foreach( $rows as $row ) {
			$redirects[] = new Redirect(
				new Title( $row['title'], intval( $row['namespace'] ) ),
				new Title( $row['rd_title'], intval( $row['rd_namespace'] ) )
			);
		}

		return $redirects;
	}

	/**
	 * @todo we probably want to build the queries rather than having then so hardcoded....
	 *
	 * @return string
	 */
	private function getQuery() {
		return "SELECT p1.page_title AS title, rd_title,
p1.page_namespace as namespace, rd_namespace
FROM page as p1
LEFT JOIN redirect ON ((rd_from=p1.page_id))
LEFT JOIN page as p2 ON ((p2.page_namespace=rd_namespace) AND (p2.page_title=rd_title))
WHERE p1.page_is_redirect = '1'
AND p1.page_namespace = :namespace";
	}

}


<?php
/**
 * This file is part of Formular.
 *
 * (c) Philippe Gerber
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace bigwhoop\Formular\Template;

use bigwhoop\Formular\Filtering\ZendEscaperAdapter;
use bigwhoop\Formular\TemplateFactory\TemplateFactoryInterface;
use bigwhoop\Formular\Filtering\EscaperInterface;

/**
 * @author Philippe Gerber <philippe@bigwhoop.ch>
 */
abstract class AbstractTemplate
{
    /** @var array */
    protected $attributes = [];

    /** @var TemplateFactoryInterface|null */
    private $templateFactory = null;

    /** @var EscaperInterface|null */
    private $escaper = null;

    /**
     * @param array $attributes
     * @return $this
     */
    public function setAttributes(array $attributes)
    {
        $this->attributes = $attributes;
        return $this;
    }

    /**
     * @param TemplateFactoryInterface $locator
     * @return $this
     */
    public function setTemplateFactory(TemplateFactoryInterface $locator)
    {
        $this->templateFactory = $locator;
        return $this;
    }

    /**
     * @return EscaperInterface
     */
    public function getEscaper()
    {
        if (!$this->escaper) {
            $this->escaper = new ZendEscaperAdapter();
        }
        return $this->escaper;
    }

    /**
     * @param EscaperInterface $escaper
     * @return $this
     */
    public function setEscaper(EscaperInterface $escaper)
    {
        $this->escaper = $escaper;
        return $this;
    }

    /**
     * @param array $attributes
     * @return string
     */
    public function render(array $attributes = [])
    {
        $this->setAttributes($attributes);
        return $this->renderTemplate();
    }

    /**
     * @return string
     */
    abstract protected function renderTemplate();

    /**
     * Renders the all the given keys as HTML element attributes.
     *
     * @param array|string $keys
     * @return string
     */
    public function attr($keys = [])
    {
        if (!is_array($keys)) {
            $keys = [$keys];
        }

        $out = '';
        foreach ($keys as $key) {
            $value = $this->getValue($key)->attr();
            if (!empty($value)) {
                $out .= ' ' . $value;
            }
        }
        return ltrim($out, ' ');
    }

    /**
     * Renders the all the given keys as HTML element properties.
     *
     * @param array|string $keys
     * @return string
     */
    public function prop($keys = [])
    {
        if (!is_array($keys)) {
            $keys = [$keys];
        }

        $out = '';
        foreach ($keys as $key) {
            $value = $this->getValue($key)->prop();
            if (!empty($value)) {
                $out .= ' ' . $value;
            }
        }
        return ltrim($out, ' ');
    }

    /**
     * @param string $templateName
     * @return string
     * @throws \RuntimeException
     */
    public function partial($templateName)
    {
        if (!$this->templateFactory) {
            throw new \RuntimeException("Template factory must be set to render partials.");
        }
        $template = $this->templateFactory->createTemplate($templateName);
        return $template->render($this->attributes);
    }

    /**
     * @param string $key
     * @return Value
     */
    private function getValue($key)
    {
        return $this->createValue($key, $this->dereferenceValue($key));
    }

    /**
     * @param string $key
     * @return mixed
     */
    private function dereferenceValue($key)
    {
        $value = '';
        if (array_key_exists($key, $this->attributes)) {
            $value = $this->attributes[$key];
            if (is_callable($value)) {
                $value = $value();
            }
        }
        return $value;
    }

    /**
     * @param string $key
     * @param mixed $value
     * @return Value
     */
    private function createValue($key, $value)
    {
        $val = new Value($key, $value);
        $val->setEscaper($this->getEscaper());
        return $val;
    }

    /**
     * @param string $key
     * @return Value
     */
    public function __get($key)
    {
        return $this->getValue($key);
    }
}


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

namespace RedKiteCms\EventSystem\Listener\PageCollection;

use RedKiteCms\Content\PageCollection\PagesCollectionParser;
use RedKiteCms\Content\PageCollection\PermalinkManager;
use RedKiteCms\EventSystem\Event\PageCollection\PageCollectionRemovedEvent;

/**
 * Class PageRemovedListener listens to PageCollectionRemovedEvent to remove the permalinks from PermalinkManager object
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\EventSystem\Listener\Page
 */
class PageRemovedListener
{
    /**
     * @type \RedKiteCms\Content\PageCollection\PagesCollectionParser
     */
    private $pagesParser;
    /**
     * @type \RedKiteCms\Content\PageCollection\PermalinkManager
     */
    private $permalinkManager;

    /**
     * Constructor
     *
     * @param \RedKiteCms\Content\PageCollection\PagesCollectionParser $pagesParser
     * @param \RedKiteCms\Content\PageCollection\PermalinkManager $permalinkManager
     */
    public function __construct(PagesCollectionParser $pagesParser, PermalinkManager $permalinkManager)
    {
        $this->pagesParser = $pagesParser;
        $this->permalinkManager = $permalinkManager;
    }

    /**
     * Removes the page from PermalinkManager object
     *
     * @param \RedKiteCms\EventSystem\Event\PageCollection\PageCollectionRemovedEvent $event
     */
    public function onPageRemoved(PageCollectionRemovedEvent $event)
    {
        $pageName = basename($event->getFilePath());
        $page = $this->pagesParser
            ->contributor($event->getUsername())
            ->parse()
            ->page($pageName);
        if (null === $page) {
            return;
        }

        foreach ($page["seo"] as $seo) {
            $permalink = $seo["permalink"];
            $this->permalinkManager->remove($permalink);
        }

        $this->permalinkManager->save();
    }
}


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

namespace RedKiteCms\Tools;

use RedKiteCms\Bridge\Translation\Translator;

/**
 * Class Utils collects several generic methods
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Tools
 */
class Utils
{
    /**
     * Slugifies a path
     *
     * Based on http://php.vrana.cz/vytvoreni-pratelskeho-url.php
     *
     * @param  string $text
     * @return string
     */
    public static function slugify($text)
    {
        // replace non letter or digits by -
        $text = preg_replace('~[^\\pL\d]+~u', '-', $text);

        // trim
        $text = trim($text, '-');

        // transliterate
        $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);

        // lowercase
        $text = strtolower($text);

        // remove unwanted characters
        $text = preg_replace('~[^-\w]+~', '', $text);

        if (empty($text)) {
            return 'n-a';
        }

        return $text;
    }

    public static function translateException($message, \Exception $exception = null)
    {
        $jsonMessage = json_decode($message, true);
        if (!is_array($jsonMessage)) {
            $jsonMessage = array(
                'message' => $message,
            );
        }

        $parameters = array(
            'message' => '',
            'parameters' => array(),
            'domain' => 'RedKiteCms',
            'locale' => null,
        );
        $cleanedParameters = array_intersect_key($jsonMessage, $parameters);
        $parameters = array_merge($parameters, $cleanedParameters);

        $message = Translator::translate(
            $parameters["message"],
            $parameters["parameters"],
            $parameters["domain"],
            $parameters["locale"]
        );

        if (null !== $exception && array_key_exists("show_exception", $jsonMessage) && $jsonMessage["show_exception"]) {
            $message = substr(strrchr(get_class($exception), '\\'), 1) . ": " . $message;
        }

        return $message;
    }

    /**
     * Finds recursively differences in two arrays
     *
     * @param $aArray1
     * @param $aArray2
     *
     * @return array
     */
    public static function arrayRecursiveDiff($aArray1, $aArray2) {
        $aReturn = array();

        foreach ($aArray1 as $mKey => $mValue) {
            if (array_key_exists($mKey, $aArray2)) {
                if (is_array($mValue)) {
                    $aRecursiveDiff = self::arrayRecursiveDiff($mValue, $aArray2[$mKey]);
                    if (count($aRecursiveDiff)) { $aReturn[$mKey] = $aRecursiveDiff; }
                } else {
                    if ($mValue != $aArray2[$mKey]) {
                        $aReturn[$mKey] = $mValue;
                    }
                }
            } else {
                $aReturn[$mKey] = $mValue;
            }
        }

        return $aReturn;
    }
}


<?php

namespace Versatile\Search;

use Versatile\Search\Contracts\Filter as FilterContract;
use Versatile\Search\Contracts\Expression as ExpressionContract;
use Versatile\Search\Contracts\Queryable;

use ArrayIterator;
use OutOfBoundsException;

class Expression implements ExpressionContract
{

    protected $key;

    protected $operator;

    protected $value;

    protected $bool = Queryable::AND_;

    public function __construct($key=null, $operator=null, $value=null, $boolean=Queryable::AND_)
    {
        $this->where($key, $operator, $value, $boolean);
    }

    /**
     * Returns the key for this expression
     *
     * @return string
     **/
    public function key()
    {
        return $this->key;
    }

    /**
     * Returns the operator
     *
     * @return string
     **/
    public function operator()
    {
        return $this->operator;
    }

    /**
     * Returns the right part of the expression
     *
     * @return mixed
     **/
    public function value()
    {
        return $this->value;
    }

    /**
     * Returns the connection of this expression relative to the last added
     * expression can be and|or
     *
     * @return string
     **/
    public function bool()
    {
        return $this->bool;
    }

    /**
     * {@inheritdoc} Sets all values and returns itself
     *
     * @param string $key
     * @param string $operator
     * @param mixed $value
     * @param string $boolean
     * @return self
     **/
    public function where($key, $operator, $value=null, $boolean=Queryable::AND_)
    {

        if ($value !== null) {
            $this->key = $key;
            $this->operator = $operator;
            $this->value = $value;
            $this->bool = $boolean;
            return $this;
        }

        if (is_array($operator)) {
            $this->key = $key;
            $this->operator = 'in';
            $this->value = $operator;
            $this->bool = $boolean;
            return $this;
        }

        $this->key = $key;
        $this->operator = '=';
        $this->value = $operator;
        $this->bool = $boolean;
        return $this;

    }

}


<?php
namespace DasRed\Translation\Command\Executor\Translation;

use Zend\Console\ColorInterface;
use DasRed\Translation\Command\Executor\TranslationAbstract;

class Sort extends TranslationAbstract
{

	/*
	 * (non-PHPdoc)
	 * @see \DasRed\Translation\Command\ExecutorAbstract::execute()
	 */
	public function execute()
	{
		try
		{
			$directory = new \RecursiveDirectoryIterator($this->getArguments()[0]);
			$iterator = new \RecursiveIteratorIterator($directory);
			$regex = new \RegexIterator($iterator, '/^.+\.php$/i', \RecursiveRegexIterator::GET_MATCH);

			foreach ($regex as $file)
			{
				$translations = require $file[0];
				ksort($translations, SORT_NATURAL);

				$fHandle = fopen($file[0], 'w');
				fwrite($fHandle, "<?php\n");
				fwrite($fHandle, "\n");
				fwrite($fHandle, "return [\n");

				foreach ($translations as $key => $entry)
				{
					fwrite($fHandle, sprintf('	\'%s\' => \'%s\',', $key, addcslashes($entry, '\'')) . "\n");
				}

				fwrite($fHandle, "];\n");
				fclose($fHandle);
			}

			$this->getConsole()->writeLine('Translations sorted.', ColorInterface::BLACK, ColorInterface::LIGHT_GREEN);
		}
		catch (\Exception $exception)
		{
			$this->getConsole()->writeLine('Translations can not be sorted. Maybe the path is wrong.', ColorInterface::LIGHT_YELLOW, ColorInterface::LIGHT_RED);
			return false;
		}

		return true;
	}

	/*
	 * (non-PHPdoc)
	 * @see \DasRed\Translation\Command\ExecutorAbstract::validateArguments()
	 */
	protected function validateArguments($arguments)
	{
		if (count($arguments) !== 1)
		{
			return false;
		}

		return parent::validateArguments($arguments);
	}
}


<?php namespace Ordercloud\Cart\Entities;

use Ordercloud\Entities\Products\Product;

class CartItem
{
    /** @var string */
    private $puid;
    /** @var Product */
    private $product;
    /** @var int */
    private $quantity;
    /** @var array|CartItemOption[] */
    private $options;
    /** @var array|CartItemExtra[] */
    private $extras;
    /**
     * @var string
     */
    private $note;

    /**
     * @param Product                $product
     * @param int                    $quantity
     * @param array|CartItemOption[] $options
     * @param array|CartItemExtra[]  $extras
     * @param string                 $note
     */
    public function __construct(Product $product, $quantity = 1, array $options = [], array $extras = [], $note = null)
    {
        $this->puid = uniqid(); //TODO create based on selected product+extras+options
        $this->product = $product;
        $this->quantity = $quantity;
        $this->options = CartItemOption::createFromArray($options, $product);
        $this->extras = CartItemExtra::createFromArray($extras, $product);
        $this->note = $note;
    }

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

    /**
     * @return Product
     */
    public function getProduct()
    {
        return $this->product;
    }

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

    /**
     * @param int $quantity
     */
    public function setQuantity($quantity)
    {
        $this->quantity = $quantity;
    }

    /**
     * @return array|CartItemOption[]
     */
    public function getOptions()
    {
        return $this->options;
    }

    /**
     * @return bool
     */
    public function hasOptions()
    {
        $options = $this->getOptions();

        return ! empty($options);
    }

    /**
     * @return array|CartItemExtra[]
     */
    public function getExtras()
    {
        return $this->extras;
    }

    /**
     * @return bool
     */
    public function hasExtras()
    {
        $extras = $this->getExtras();

        return ! empty($extras);
    }

    /**
     * The fully calculated item total. This includes
     * the options, extras & quantity.
     *
     * @return float
     */
    public function getAmount()
    {
        $amount = $this->getPerUnitAmount();

        $totalAmount = bcmul($amount, $this->getQuantity(), 2);

        return floatval($totalAmount);
    }

    /**
     * The calculated item total. This includes the
     * options & extras, but excludes quantity.
     *
     * @return float
     */
    public function getPerUnitAmount()
    {
        $amount = $this->getProduct()->getPrice();

        foreach ($this->getOptions() as $cartOption) {
            $amount = bcadd($amount, $cartOption->getOption()->getPrice(), 2);
        }

        foreach ($this->getExtras() as $cartExtra) {
            $amount = bcadd($amount, $cartExtra->getExtra()->getPrice(), 2);
        }

        return floatval($amount);
    }

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


<?php

/*
 * This file is part of the P13/DateTime package.
 *
 * (c) Wagner Sicca <wssicca@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace p13\datetime;

/**
 * Classe que representa uma semana segundo a definição ISO-8601. Nela,
 * as semanas começam nas segundas (dia 1) e terminam no domingo (dia 7).
 *
 *
 * @author Wagner Sicca <wssicca@gmail.com>
 * @namespace p13\datetime
 * @package p13\datetime
 * @link http://pt.wikipedia.org/wiki/ISO_8601 Link com uma breve descrição
 */
class Week extends DateRange
{

    /**
     * Número da semana segundo o padrão ISO-8601
     * @var int
     */
    public $week;

    /**
     * Número do ano
     * @var int
     */
    public $year;

    /**
     *
     * @param int $week ISO-8601 week number of year, weeks starting on Monday
     * @param int $year
     */
    public function __construct($week, $year)
    {
        $this->week = (int) $week;
        $this->year = (int) $year;

        $startDate = new DateTime();
        $startDate->setISODate($this->year, $this->week);

        $endDate = clone $startDate;
        $endDate->add(DateInterval::createFromDateString('6 days'));

        parent::__construct($startDate, $endDate);
    }

    /**
     * Retorna uma representação textual da semana
     * @return string
     */
    public function __toString()
    {
        return sprintf(
                "Semana %d (%s a %s)", $this->week, $this->startDate->format('d/m/Y'), $this->endDate->format('d/m/Y')
        );
    }

    /**
     * Compara dois objetos Week. Retorna:
     * - um número menos que zero se o primeiro for menor que o segundo;
     * - um número maior que zero se o primeiro for maior que o segundo;
     * - zero se ambos forem iguais
     * @param \p13\datetime\Week $a
     * @param \p13\datetime\Week $b
     * @return int
     */
    public static function compare(Week $a, Week $b)
    {
        if ($a == $b) {
            return 0;
        } else if ($a->year == $b->year) {
            if ($a->week < $b->week) {
                return -1;
            } else if ($a->week > $b->week) {
                return 1;
            } else {
                return 0;
            }
        } else {
            if ($a->year < $b->year) {
                return -1;
            } else if ($a->year > $b->year) {
                return 1;
            } else {
                return 0;
            }
        }
    }

}


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

namespace RedKiteCms\EventSystem\Listener\Page;

use RedKiteCms\Bridge\Monolog\DataLogger;
use RedKiteCms\Configuration\ConfigurationHandler;
use RedKiteCms\Content\PageCollection\PermalinkManager;
use RedKiteCms\EventSystem\Event\Page\PermalinkChangedEvent;
use RedKiteCms\Tools\FilesystemTools;

/**
 * Class PermalinkChangedListener listens to PermalinkChangedEvent to update permalinks on the blocks where the permalink
 * was used
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\EventSystem\Listener\Seo
 */
class PermalinkChangedListener
{
    /**
     * @type \RedKiteCms\Configuration\ConfigurationHandler
     */
    private $configurationHandler;
    /**
     * @type \RedKiteCms\Content\PageCollection\PermalinkManager
     */
    private $permalinkManager;

    /**
     * Constructor
     *
     * @param \RedKiteCms\Configuration\ConfigurationHandler $configurationHandler
     * @param \RedKiteCms\Content\PageCollection\PermalinkManager $permalinkManager
     */
    public function __construct(ConfigurationHandler $configurationHandler, PermalinkManager $permalinkManager)
    {
        $this->configurationHandler = $configurationHandler;
        $this->permalinkManager = $permalinkManager;
    }

    /**
     * Update permalinks on the blocks where the permalink was used
     *
     * @param \RedKiteCms\EventSystem\Event\Page\PermalinkChangedEvent $event
     */
    public function onPermalinkChanged(PermalinkChangedEvent $event)
    {
        $previousPermalink = $event->getOriginalText();
        $newPermalink = $event->getChangedText();

        $this->updatePermalinkOnBlocks($previousPermalink, $newPermalink);
        $this->updateHomepagePermalink($previousPermalink, $newPermalink);
    }

    private function updatePermalinkOnBlocks($previousPermalink, $newPermalink)
    {
        $blockFiles = $this->permalinkManager->getPermalink($previousPermalink);
        if (empty($blockFiles)) {
            return;
        }

        foreach ($blockFiles as $blockFile) {
            $blockContent = file_get_contents($blockFile);
            $updatedBlockContent = str_replace($previousPermalink, $newPermalink, $blockContent);
            $result = @file_put_contents($blockFile, $updatedBlockContent);
            $not = '';
            if (!$result) {
                $not = 'not ';
            }

            DataLogger::log(
                sprintf(
                    'Permalink "%s" has %sbeen updated for the block stored into the filename "%s"',
                    $newPermalink,
                    $not,
                    realpath($blockFile)
                )
            );
        }

        $this->permalinkManager
            ->update($previousPermalink, $newPermalink)
            ->save()
        ;
    }

    private function updateHomepagePermalink($previousPermalink, $newPermalink)
    {
        if ($this->configurationHandler->homepagePermalink() == $previousPermalink) {
            $siteFile = $this->configurationHandler->siteDir() . '/site.json';
            $siteInfo = json_decode(FilesystemTools::readFile($siteFile), true);
            $siteInfo["homepage_permalink"] = $newPermalink;
            FilesystemTools::writeFile($siteFile, json_encode($siteInfo));
        }
    }
}


<?php

declare(strict_types=1);

namespace Ruwork\RunetIdBundle\Basket\Basket\Filter;

use RunetId\Client\Result\Pay\ItemResult;
use RunetId\Client\Result\Pay\OrderResult;

final class OwnerRunetIdFilter extends AbstractBinaryFilter
{
    private $runetId;

    public function __construct(int $runetId, int $priority = 1)
    {
        $this->runetId = $runetId;
        parent::__construct($priority);
    }

    /**
     * {@inheritdoc}
     */
    protected function vote(ItemResult $item, ?OrderResult $order): bool
    {
        return $this->runetId === $item->Owner->RunetId;
    }
}


<?php namespace Austinw\Pdfdf;

use Illuminate\Support\ServiceProvider;
use Wesnick\FdfUtility\PdfForm;
use Wesnick\FdfUtility\Parser\PdftkDumpParser;
use Wesnick\FdfUtility\FdfWriter;
use Shuble\Slurpy\Factory as PDFTKFactory;

class PdfdfServiceProvider extends ServiceProvider {

    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = true;

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->package('austinw/pdfdf');
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('pdfdf.factory', function($app) {
            $factoryPath = $app['config']->get('pdfdf::pdftk');

            return new PDFTKFactory($factoryPath);
        });

        $this->app->bind('pdftkDumpParser', function($app, $file) {
            return new PdftkDumpParser($file);
        });

        $this->app['pdfdf'] = $this->app->share(function($app) {
            $pdfdf = new Pdfdf(new PdfForm, new FdfWriter);
            $pdfdf->registerFactory($app['pdfdf.factory']);

            $pdfdf->setConfiguration(array(
                'tmp'            => $app['config']->get('pdfdf::storage.tmp'),
                'pdf'            => $app['config']->get('pdfdf::storage.pdf'),
                'erase_temp_fdf' => $app['config']->get('pdfdf::erase_temp_fdf'),
            ));

            return $pdfdf;
        });
    }

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

}


<?php
/**
 * CoolMS2 User Module (http://www.coolms.com/)
 *
 * @link      http://github.com/coolms/user for the canonical source repository
 * @copyright Copyright (c) 2006-2015 Altgraphic, ALC (http://www.altgraphic.com)
 * @license   http://www.coolms.com/license/new-bsd New BSD License
 * @author    Dmitry Popov <d.popov@altgraphic.com>
 */

namespace CmsUser\Factory\Persistence;

use Zend\ServiceManager\DelegatorFactoryInterface,
    Zend\ServiceManager\ServiceLocatorInterface,
    CmsCommon\Persistence\MapperInterface,
    CmsUser\Options\ModuleOptions,
    CmsUser\Persistence\UserMapperInterface;

class UserMapperDelegatorFactory implements DelegatorFactoryInterface
{
    /**
     * {@inheritDoc}
     *
     * @return MapperInterface
     */
    public function createDelegatorWithName(
        ServiceLocatorInterface $serviceLocator,
        $name,
        $requestedName,
        $callback
    ) {
        $mapper = $callback();

        if (!$mapper instanceof UserMapperInterface) {
            return $mapper;
        }

        $services = $serviceLocator->getServiceLocator();

        /* @var $options ModuleOptions */
        $options = $services->get(ModuleOptions::class);

        $mapper->setIdentityFields($options->getIdentityFields());

        /* @var $passwordService \Zend\Crypt\Password\PasswordInterface */
        $passwordService = $services->get($options->getPasswordService());
        $mapper->setPasswordService($passwordService);

        return $mapper;
    }
}


<?php
namespace HtSettingsModule\Factory;

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

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

        return $settingsProvider;
    }
}


<?php
/**
 * This file is part of the "Easy System" package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @author Damon Smith <damon.easy.system@gmail.com>
 */
namespace Es\Modules\Listener;

use Es\Loader\Normalizer;
use Es\Modules\ModulesEvent;
use Es\Services\ServicesTrait;
use Es\System\ConfigTrait;
use InvalidArgumentException;

/**
 * Provides merging of system configurations from configuration files in
 * specified directory. By default, this directory is "config/autoload/".
 */
class ConfigReaderAutoloadListener
{
    use ConfigTrait, ServicesTrait;

    /**
     * The directory for autoloading of configuration files.
     *
     * @var string
     */
    protected $autoloadDir = 'config/autoload/';

    /**
     * Sets the directory for autoloading of configuration files.
     *
     * @param string $dir The path to directory
     *
     * @throws \InvalidArgumentException If the received directory is not
     *                                   non-empty string or if this directory
     *                                   not exists
     */
    public function setAutoloadDir($dir)
    {
        if (! is_string($dir) || empty($dir)) {
            throw new InvalidArgumentException(sprintf(
                'Invalid directory for autoload of configuration provided; '
                . 'must be a non-empty string, "%s" received.',
                is_object($dir) ? get_class($dir) : gettype($dir)
            ));
        }

        $dir = Normalizer::path($dir);

        if (! file_exists($dir) || ! is_dir($dir)) {
            throw new InvalidArgumentException(sprintf(
                'The directory "%s", specified for autoload of configurations, '
                . 'does not exists.',
                $dir
            ));
        }
        $this->autoloadDir = $dir;
    }

    /**
     * Gets the directory for autoloading of configuration files.
     *
     * @return string The path to directory
     */
    public function getAutoloadDir()
    {
        return $this->autoloadDir;
    }

    /**
     * Merges of system configurations from configuration files in specified
     * directory.
     *
     * @param ModulesEvent $event The modules event
     */
    public function __invoke(ModulesEvent $event)
    {
        $config = $this->getConfig();
        $dir    = $this->getAutoloadDir();
        $path   = $dir . '{{,*.}global,{,*.}local}.php';
        foreach (glob($path, GLOB_BRACE) as $file) {
            $item = require $file;
            $config->merge((array) $item);
        }
    }
}


<?php
declare(ticks=1);
namespace MQK\Process;

use Monolog\Logger;

class MasterProcess implements Master
{
    /**
     * self pipe
     *
     * @var int[]
     */
    private $pipe;

    /**
     * Signal queue
     *
     * @var array
     */
    private $signals = [];

    /**
     * 当前状态为退出
     *
     * @var boolean
     */
    private $quiting = false;

    /**
     * Worker list
     *
     * @var AbstractWorker[]
     */
    protected $workers = [];

    /**
     * 强制退出
     *
     * @var boolean
     */
    protected $forceQuit = false;

    /**
     * 开启的进程数量
     *
     * @var integer
     */
    protected $processes = 5;

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

    /**
     * @var boolean
     */
    protected $burst = false;

    /**
     * @var Logger
     */
    protected $logger;

    /**
     * select 的超时时间，单位是微妙
     * @var int
     */
    protected $selectTimeout = 500000;

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

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

    /**
     * 信号和信号执行方法的映射
     *
     * @var array
     */
    private $signalMappingToMethod = [
        SIGCHLD => "signalChildHandle",
        SIGINT => "signalIntHandle",
        SIGTERM => 'signalTerminalHandle',
        SIGTTIN => "signalIncreaseHandle",
        SIGTTOU => 'signalDecreaseHandle',
        SIGHUP => 'signalReloadHandle',
        SIGQUIT => 'signalQuitHandle'
    ];

    private $signalNames = [
        SIGCHLD => 'SIGCHLD',
        SIGINT => 'SIGINT',
        SIGTTIN => 'SIGTTIN',
        SIGTTOU => 'SIGTTOU',
        SIGHUP => 'SIGHUP',
        SIGQUIT => 'SIGQUIT'
    ];

    /**
     * 进程证在退出
     *
     * @var boolean
     */
    protected $quitting = false;

    public function __construct(
        $workerClassOrFactory,
        $processes = 5,
        $burst = false,
        Logger $logger = null) {

        $this->workerClassOrFactory = $workerClassOrFactory;
        $this->processes = $processes;
        $this->burst = $burst;
        if (null == $logger)
            $logger = new Logger(__CLASS__);
        $this->logger = $logger;
    }

    /**
     * 开始启动主进程
     *
     * @return void
     */
    public function run()
    {
        $this->createdAt = time();
        $pid = getmypid();
        $this->logger->debug("master process id is {$pid}");
        $this->spawn();

        $this->pipe = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);

        stream_set_blocking($this->pipe[0], true);
        stream_set_blocking($this->pipe[1], true);

        foreach (array_keys($this->signalMappingToMethod) as $signal)
            pcntl_signal($signal, array(&$this, "signalHandle"));

        $watchFileDescriptors = $this->fileDescriptors;
        $watchFileDescriptors[] = $this->pipe[1];
        while (true) {
            $r = $watchFileDescriptors;
            $w = [];
            $e = [];

            try {
                $this->willSelect();
                $this->select($r, $w, $e, $this->selectTimeout);
                $this->didSelect();
            } catch (\Exception $e) {
                $this->logger->error($e->getMessage());
                $this->dispatch_signals();
            }
        }
    }

    /**
     * Select 之前调用
     * @return void
     */
    protected function willSelect()
    {

    }

    /**
     * Select 之后调用
     *
     * 可以在 willSelect 或者 didSelect 方法内扩展子进程的逻辑。如健康检查或者一些需要心跳的事情。
     */
    protected function didSelect()
    {

    }

    /**
     * 默认信号处理器
     *
     * 该处理器将信号队列
     *
     * @param int $signo
     * @return void
     */
    function signalHandle($signo)
    {
        $this->logger->debug("push {$this->signalNames[$signo]} to signal queue");
        $this->signals[] = $signo;
//        fwrite($this->pipe[0], '.');
    }

    /**
     * SIGCHLD 信号处理器
     *
     * @return void
     */
    function signalChildHandle()
    {
        $this->logger->debug("signal child handle");

        $this->reap();
        if (!$this->quiting && !$this->burst) {
            $this->logger->debug("child exit and spawn worker");
            $this->spawn();
        }

        if ($this->burst && empty($this->workers)) {
            $this->logger->debug("master process will exit");
            $this->willQuit();
            exit(0);
        }
    }

    /**
     * SIGTERM 信号处理器
     *
     * 平滑退出进程。两次按 Ctrl+C 则强制退出。
     *
     * @return void
     */
    function signalTerminalHandle()
    {
        $this->logger->debug("signal terminal handle");
        $this->stop(false);
    }

    function signalIntHandle()
    {
        $this->logger->debug("signal int handle");
        $this->stop(false);
    }

    /**
     * SIGQUIT 信号处理器
     *
     * 强制退出进程
     *
     * @return void
     */
    function signalQuitHandle()
    {
        $this->stop(true);
    }

    /**
     * 新增子进程
     *
     * @return void
     */
    function signalIncreaseHandle()
    {
        $this->processes += 1;
        $this->spawn();
    }

    /**
     * 减少子进程
     *
     * @return void
     */
    function signalDecreaseHandle()
    {
        if ($this->processes <= 1)
            return;
        $this->processes -= 1;
        $this->manageWorkers();
    }

    /**
     * 重新启动进程
     *
     * @return void
     */
    function signalReloadHandle()
    {
        $this->logger->debug('got hup signal');
        $this->reload();
    }

    /**
     * 执行信号队列
     *
     * @return void
     */
    function dispatch_signals()
    {
        if (empty($this->signals))
            return;

        $signalsExported = join(" ", array_map(function($signal) {
            return isset($this->signalNames[$signal]) ? $this->signalNames[$signal] : $signal;
        }, $this->signals));
        $this->logger->debug("dispatch signals $signalsExported");
        while ($signalNumber = array_shift($this->signals)) {
            $handleFunction = $this->signalMappingToMethod[$signalNumber];
            call_user_func([&$this, $handleFunction], [$signalNumber]);
        }
    }

    /**
     * REAP进程防治产生僵尸进程
     *
     * @return void
     */
    function reap()
    {
        for ($i = 0; $i < 100; $i++) {
            $pid = pcntl_waitpid(-1, $status, WNOHANG);
            if (-1 == $pid) {
                break;
            } else if ($pid > 0) {
                $this->logger->debug("did reape process {$pid}");
                $this->removeWorkerById($pid);
                continue;
            }
            $this->logger->debug("waitpid return pid is 0");
            break;
        }
    }

    /**
     * 启动新进程
     *
     * @return void
     */
    public function spawn()
    {
        $needToStart = $this->processes - count($this->workers);
        $this->logger->debug("will start {$needToStart} processes");
        for ($i = 0; $i < $needToStart; $i++) {
            $worker = $this->spawnWorker();
            $this->didSpawnWorker($worker, $i);
            $worker->start();
            $this->workers[] = $worker;
        }
    }

    /**
     * 启动一个新进程
     *
     * @return AbstractWorker
     */
    public function spawnWorker()
    {
        if ($this->workerClassOrFactory instanceof WorkerFactory) {
            $worker = $this->workerClassOrFactory->create();
        } else
            $worker = new $this->workerClassOrFactory();
        return $worker;
    }

    protected function didSpawnWorker(AbstractWorker $worker, $index)
    {

    }

    /**
     * 杀掉多余的进程
     *
     * @return void
     */
    function manageWorkers()
    {
        $this->logger->debug("manage workers");
        $workers = $this->workers;
        while ($this->processes < count($workers)) {
            $worker = array_shift($workers);
            $this->logger->debug("kill {$worker->id()}");
            $this->kill($worker->id(), SIGQUIT);
        }
    }

    public function select($r, $w, $e, $timeout)
    {
        set_error_handler(array(&$this, "error_handler"));

        try {
            stream_select($r, $w, $e, 0, $timeout);
        } catch (\Exception $e) {
            pcntl_signal_dispatch();
            throw $e;
        } finally {
            restore_error_handler();
        }
    }

    function error_handler($errno, $errstr, $errfile, $errline, $errcontext = null)
    {
        $last_error = compact('errno', 'errstr', 'errfile', 'errline', 'errcontext');

        // fwrite notice that the stream isn't ready
        if (strstr($errstr, 'Resource temporarily unavailable')) {
            // it's allowed to retry
            return;
        }
        // stream_select warning that it has been interrupted by a signal
        if (strstr($errstr, 'Interrupted system call')) {
            throw new \Exception("Interrupted system call");
            // it's allowed while processing signals
            return;
        }
        // raise all other issues to exceptions
        throw new \Exception($errstr, 0, $errno, $errfile, $errline);
    }

    /**
     * 移除子进程
     *
     * @param int $id 进程ID
     * @return void
     */
    function removeWorkerById($id)
    {
        $this->logger->debug("will remove worker by id is $id");
        $found = -1;
        foreach ($this->workers as $i => $worker) {
            if ($worker->id() == $id) {
                $found = $i;
                break;
            }
        }

        if ($found > -1) {
            $worker = $this->workers[$found];
            $this->logger->debug("did removed worker by id is {$worker->id()}");

            unset($this->workers[$found]);
        }
    }

    /**
     * 重启Worker
     */
    protected function reload()
    {
        for ($i = 0, $size = $this->processes; $i < $size; $i++) {
            $worker = $this->spawnWorker();
            $worker->start();
            $this->workers[] = $worker;
        }

        $this->manageWorkers();
    }

    /**
     * 停止所有进程并退出
     *
     * @param boolean $graceful
     * @return void
     */
    public function stop($graceful = false)
    {
        if ($graceful)
            $this->logger->debug("application will graceful quit");
        else
            $this->logger->debug("application will quit");
        $this->quiting = true;
        $signal = $graceful ? SIGQUIT : SIGTERM;
        $limit = time() + 10;

        $this->killall($signal);

        while (time() < $limit) {
            $this->dispatch_signals();
            if (count($this->workers) == 0) {
                break;
            }
            // 偶尔存在SIGCHLD 没有REAP到的进程
            $this->reap();
            usleep(100000);
        }

        if ($graceful)
            $this->killall(SIGKILL);

       $this->logger->debug("master process quit.");
       $this->willQuit();
       exit(0);
    }

    /**
     * 杀掉所有进程
     *
     * @param int $signal 使用的信号
     * @return void
     */
    protected function killall($signal)
    {
        $signalAction = $signal == SIGTERM ? "exit" : "quit";
        /**
         * @var $worker Worker
         */
        foreach ($this->workers as $worker) {

            $this->kill($worker->id(), $signal);
        }
    }

    /**
     * 杀掉单一进程
     *
     * @param int $pid
     * @param int $signal
     * @return void
     */
    protected function kill($pid, $signal)
    {
        $this->logger->debug("{$signal} process {$pid}");
        if (!posix_kill($pid, $signal)) {
             $this->logger->error("{$signal} process failure {$pid}");
        }
    }

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

    public function setBurst($burst)
    {
        $this->burst = $burst;
    }

    protected function willQuit()
    {

    }
}


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

namespace cascade\commands;

use cascade\components\dataInterface\ConsoleAction;
use canis\helpers\ArrayHelper;
use canis\helpers\Console;
use Yii;
use yii\console\Exception;

ini_set('memory_limit', -1);

/**
 * InterfaceController Run data interface commands.
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class InterfaceController extends \canis\console\Controller
{
    /**
     * @var Item the currently running interface
     */
    protected $_interface;
    /**
     * @var bool output debug and info messages
     */
    public $verbose;
    /**
     * Run a data interface.
     */
    public function actionIndex()
    {
        $this->actionRunOne();
    }

    /**
     * Run one data interface.
     */
    public function actionRunOne()
    {
        $this->out("Run Interface " . $this->dataInterface->object->name, Console::UNDERLINE, Console::FG_GREEN);
        $this->hr();
        $this->dataInterface->run(null, new ConsoleAction());
    }

    /**
     * Get interface.
     *
     * @return Item The data interface
     */
    public function getDataInterface()
    {
        if (!$this->started) {
            return $this->_interface;
        }
        if (is_null($this->_interface)) {
            $interfaces = ArrayHelper::map(Yii::$app->collectors['dataInterfaces']->getAll(), 'systemId', 'object.name');
            $this->dataInterface = $this->select("Choose interface", $interfaces);
        }

        return $this->_interface;
    }

    /**
     * Set interface.
     *
     * @param string $value system ID of data interface
     *
     * @throws Exception on invalid interface selection
     */
    public function setDataInterface($value)
    {
        if (($interfaceItem = Yii::$app->collectors['dataInterfaces']->getOne($value)) && ($interface = $interfaceItem->object)) {
            $this->_interface = $interfaceItem;
        } else {
            throw new Exception("Invalid interface!");
        }
    }

    /**
     * @inheritdoc
     */
    public function options($id)
    {
        return array_merge(parent::options($id), ['dataInterface', 'verbose']);
    }
}


<?php

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

namespace Chill\CustomFieldsBundle\Entity;

use \Doctrine\Common\Collections\Collection;

/**
 * CustomFieldGroup
 */
class CustomFieldsGroup
{
    /**
     * @var integer
     */
    private $id;

    /**
     * @var array
     */
    private $name;

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

    /**
     * @var \Doctrine\Common\Collections\Collection $customFields: The custom
     * fields of the group. The custom fields are asc-ordered regarding to their
     * property "ordering".
     */
    private $customFields;

    /**
     * @var array(customField) | null $activeCustomFields: The custom fields
     * of the group that are active. This variable if null, if this
     * informations has not been computed.
     */
    private $activeCustomFields = null;

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

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->customFields = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add customField
     *
     * @param \Chill\CustomFieldsBundle\Entity\CustomField $customField
     *
     * @return CustomFieldsGroup
     */
    public function addCustomField(\Chill\CustomFieldsBundle\Entity\CustomField $customField)
    {
        $this->customFields[] = $customField;

        return $this;
    }

    /**
     * Remove customField
     *
     * @param \Chill\CustomFieldsBundle\Entity\CustomField $customField
     */
    public function removeCustomField(\Chill\CustomFieldsBundle\Entity\CustomField $customField)
    {
        $this->customFields->removeElement($customField);
    }

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

    /**
     * Get all the custom
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getActiveCustomFields()
    {
        if($this->activeCustomFields === null) {
            $this->activeCustomFields = array();
            foreach ($this->customFields as $cf) {
                if($cf->isActive()) {
                    array_push($this->activeCustomFields, $cf);
                }
            }
        }

        return $this->activeCustomFields;
    }

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

    /**
     * Set name
     *
     * @param array $name
     *
     * @return CustomFieldsGroup
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return array
     */
    public function getName($language = null)
    {
       //TODO set this in a service, PLUS twig function
       if ($language) {
          if (isset($this->name[$language])) {
             return $this->name[$language];
          } else {
             foreach ($this->name as $name) {
                if (!empty($name)) {
                   return $name;
                }
             }
          }

          return '';

       } else {
          return $this->name;
       }
    }

    /**
     * Set entity
     *
     * @param string $entity
     *
     * @return CustomFieldsGroup
     */
    public function setEntity($entity)
    {
        $this->entity = $entity;

        return $this;
    }

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

    /**
     * get options array
     *
     * @return array
     */
    public function getOptions()
    {
        return $this->options;
    }

    /**
     * set options array
     *
     * @param array $options
     * @return \Chill\CustomFieldsBundle\Entity\CustomFieldsGroup
     */
    public function setOptions(array $options)
    {
        $this->options = $options;
        return $this;
    }
}


<?php

namespace OpenOrchestra\ModelBundle\Validator\Constraints;

use OpenOrchestra\ModelInterface\Model\SiteInterface;
use OpenOrchestra\ModelInterface\Repository\SiteRepositoryInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Class UniqueSiteIdValidator
 */
class UniqueSiteIdValidator extends ConstraintValidator
{
    protected $repository;

    /**
     * @param SiteRepositoryInterface $repository
     */
    public function __construct(SiteRepositoryInterface $repository)
    {
        $this->repository = $repository;
    }

    /**
     * Checks if the passed value is valid.
     *
     * @param SiteInterface              $value      The value that should be validated
     * @param UniqueMainAlias|Constraint $constraint The constraint for the validation
     *
     * @api
     */
    public function validate($value, Constraint $constraint)
    {
        $result = $this->repository->findOneBySiteId($value->getSiteId());

        if (null !== $result && $result->getId() !== $value->getId()) {
            $this->context->buildViolation($constraint->message)
                ->atPath('siteId')
                ->addViolation();
        }
    }
}


<?php

namespace OpenOrchestra\ModelBundle\DataFixtures\MongoDB;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use OpenOrchestra\ModelBundle\Document\ContentType;
use OpenOrchestra\ModelBundle\Document\FieldType;
use OpenOrchestra\ModelBundle\Document\FieldOption;
use OpenOrchestra\ModelInterface\DataFixtures\OrchestraFunctionalFixturesInterface;

/**
 * Class LoadContentTypeData
 */
class LoadContentTypeData extends AbstractFixture implements OrderedFixtureInterface, OrchestraFunctionalFixturesInterface
{
    /**
     * Load data fixtures with the passed EntityManager
     *
     * @param ObjectManager $manager
     */
    public function load(ObjectManager $manager)
    {
        $new = $this->generateContentTypeNews();
        $manager->persist($new);

        $car = $this->generateContentTypeCar();
        $manager->persist($car);

        $customer = $this->generateContentTypeCustomer();
        $manager->persist($customer);

        $manager->flush();
    }

    /**
     * Get the order of this fixture
     *
     * @return integer
     */
    public function getOrder()
    {
        return 500;
    }

    /**
     * @return array
     */
    protected function genereteDefaultListable()
    {
        return array(
            'name'           => true,
            'status_label'   => false,
            'linked_to_site' => true,
            'created_at'     => true,
            'created_by'     => true,
            'updated_at'     => false,
            'updated_by'     => false,
        );
    }

    /**
     * Generate a field type
     *
     * @param string $fieldType
     * @param string $fieldId
     * @param array $labels
     *
     * @return FieldType
     */
    protected function generateField($fieldType, $fieldId, array $labels)
    {
        $field = new FieldType();
        $field->setType($fieldType);
        $field->setFieldId($fieldId);
        $field->setDefaultValue(null);
        $field->setSearchable(true);
        $field->setLabels($labels);

        return $field;
    }

    /**
     * Generate a field option
     *
     * @param string $key
     * @param string|int|array $value
     *
     * @return FieldOption
     */
    protected function generateOption($key, $value)
    {
        $option = new FieldOption();
        $option->setKey($key);
        $option->setValue($value);

        return $option;
    }

    /**
     * @return ContentType
     */
    protected function generateContentTypeNews()
    {
        $maxLengthOption = $this->generateOption('max_length', 25);
        $required = $this->generateOption('required', true);
        $dateWidgetOption = $this->generateOption('widget', 'single_text');
        $dateInputOption = $this->generateOption('input', 'string');
        $formatOption = $this->generateOption('format', 'yyyy-MM-dd');

        /* TITLE */

        $newsTitle = $this->generateField('text', 'title', array('en' => 'Title', 'fr' => 'Titre'));
        $newsTitle->setFieldTypeSearchable('text');
        $newsTitle->addOption($maxLengthOption);
        $newsTitle->addOption($required);

        /* BEGINING DATE */

        $newBeginning = $this->generateField('date', 'publish_start', array('en' => 'Publicated from (yyyy-MM-dd)', 'fr' => 'Publié du (aaaa-MM-jj)'));
        $newBeginning->addOption($required);
        $newBeginning->addOption($dateWidgetOption);
        $newBeginning->addOption($dateInputOption);
        $newBeginning->addOption($formatOption);
        $newBeginning->setFieldTypeSearchable('date');

        /* ENDING DATE */

        $newEnding = $this->generateField('date', 'publish_end', array('en' => 'till (yyyy-MM-dd)', 'fr' => 'au (aaaa-MM-jj)'));
        $newEnding->addOption($required);
        $newEnding->addOption($dateWidgetOption);
        $newEnding->addOption($dateInputOption);
        $newEnding->addOption($formatOption);
        $newEnding->setFieldTypeSearchable('date');

        /* IMAGE */

        $newImage = $this->generateField('orchestra_media', 'image', array('en' => 'Image', 'fr' => 'Image'));
        $newImage->setFieldTypeSearchable('text');

        /* INTRODUCTION */

        $newsIntro = $this->generateField('text', 'intro', array('en' => 'Introduction', 'fr' => 'Introduction'));
        $newsIntro->addOption($maxLengthOption);
        $newsIntro->addOption($required);
        $newsIntro->setFieldTypeSearchable('text');

        /* TEXT */

        $newsText = $this->generateField('tinymce', 'text', array('en' => 'Text', 'fr' => 'Texte'));
        $newsText->setFieldTypeSearchable('text');

        /* CONTENT TYPE */

        $news = new ContentType();
        $news->setContentTypeId('news');
        $news->addName('en', 'News');
        $news->addName('fr', 'Actualités');
        $news->setDefiningStatusable(true);
        $news->setDefiningVersionable(true);
        $news->setDeleted(false);
        $news->setVersion('1');
        $news->setDefaultListable($this->genereteDefaultListable());

        $news->addFieldType($newsTitle);
        $news->addFieldType($newBeginning);
        $news->addFieldType($newEnding);
        $news->addFieldType($newImage);
        $news->addFieldType($newsIntro);
        $news->addFieldType($newsText);

        return $news;
    }

    /**
     * @return ContentType
     */
    protected function generateContentTypeCar()
    {
        $maxLengthOption = $this->generateOption('max_length', 25);

        $required = $this->generateOption('required', true);

        $carName = new FieldType();
        $carName->setFieldId('car_name');
        $carName->addLabel('en', 'Name');
        $carName->addLabel('fr', 'Nom');
        $carName->setDefaultValue('');
        $carName->setSearchable(true);
        $carName->setType('text');
        $carName->addOption($maxLengthOption);
        $carName->addOption($required);
        $carName->setFieldTypeSearchable('text');

        $carDescription = new FieldType();
        $carDescription->setFieldId('description');
        $carDescription->addLabel('en', 'Description');
        $carDescription->addLabel('fr', 'Description');
        $carDescription->setDefaultValue('');
        $carDescription->setSearchable(true);
        $carDescription->setType('text');
        $carDescription->addOption($maxLengthOption);
        $carDescription->addOption($required);
        $carDescription->setFieldTypeSearchable('text');

        $car = new ContentType();
        $car->setContentTypeId('car');
        $car->addName('en', 'Cars');
        $car->addName('fr', 'Voitures');
        $car->setDefiningStatusable(true);
        $car->setDefiningVersionable(true);
        $car->setDeleted(false);
        $car->setVersion('2');
        $car->setDefaultListable($this->genereteDefaultListable());

        $car->addFieldType($carName);
        $car->addFieldType($carDescription);

        return $car;
    }

    /**
     * @return ContentType
     */
    protected function generateContentTypeCustomer()
    {
        $maxLengthOption = $this->generateOption('max_length', 25);
        $required = $this->generateOption('required', true);

        $customerFirstName = new FieldType();
        $customerFirstName->setFieldId('firstname');
        $customerFirstName->addLabel('en', 'Firstname');
        $customerFirstName->addLabel('fr', 'Prénom');
        $customerFirstName->setDefaultValue('');
        $customerFirstName->setSearchable(true);
        $customerFirstName->setType('text');
        $customerFirstName->addOption($maxLengthOption);
        $customerFirstName->addOption($required);
        $customerFirstName->setFieldTypeSearchable('text');

        $customerLastName = new FieldType();
        $customerLastName->setFieldId('lastname');
        $customerLastName->addLabel('en', 'Lastname');
        $customerLastName->addLabel('fr', 'Nom de famille');
        $customerLastName->setDefaultValue('');
        $customerLastName->setSearchable(true);
        $customerLastName->setType('text');
        $customerLastName->addOption($maxLengthOption);
        $customerLastName->addOption($required);
        $customerLastName->setFieldTypeSearchable('text');

        $customerIdentifier = new FieldType();
        $customerIdentifier->setFieldId('identifier');
        $customerIdentifier->addLabel('en', 'Identifier');
        $customerIdentifier->addLabel('fr', 'Identifiant');
        $customerIdentifier->setDefaultValue(0);
        $customerIdentifier->setSearchable(false);
        $customerIdentifier->setType('integer');
        $customerIdentifier->addOption($maxLengthOption);
        $customerIdentifier->addOption($required);
        $customerIdentifier->setFieldTypeSearchable('number');

        $customer = new ContentType();
        $customer->setContentTypeId('customer');
        $customer->addName('en', 'Customers');
        $customer->addName('fr', 'Clients');
        $customer->setDefiningStatusable(true);
        $customer->setDefiningVersionable(true);
        $customer->setDeleted(false);
        $customer->setVersion('1');
        $customer->setDefaultListable($this->genereteDefaultListable());
        $customer->setDefiningStatusable(false);

        $customer->addFieldType($customerFirstName);
        $customer->addFieldType($customerLastName);
        $customer->addFieldType($customerIdentifier);

        return $customer;
    }
}


<?php

namespace Prob\Router;

use Psr\Http\Message\RequestInterface;
use Prob\Handler\ParameterMap;
use Prob\Handler\ProcInterface;
use Prob\Handler\Proc\MethodProc;
use Prob\Router\Exception\RoutePathNotFound;

class Dispatcher
{
    /**
     * @var Matcher
     */
    private $matcher;

    /**
     * Dispatcher constructor.
     * @param Map $map
     */
    public function __construct(Map $map)
    {
        $this->matcher = new Matcher($map);
    }

    /**
     * If $map argument is null,
     * Dispatcher call a handler with a argument about array of url matching result.
     * otherwise,
     * Dispatcher call a handler with matcing arguments by ParameterMap
     *
     * @param RequestInterface $request
     * @param ParameterMap $map
     * @return mixed return value of dispatch handler
     * @throws RoutePathNotFound
     */
    public function dispatch(RequestInterface $request, ParameterMap $map = null)
    {
        $this->validateRoutePath($request);

        /**
         * Maching result of reqeust handler
         * @var array|bool
         */
        $requestMatching = $this->matcher->match($request);

        if ($map === null) {
            if ($requestMatching['handler'] instanceof MethodProc) {
                $requestMatching['handler']->execConstructor();
            }
            return $requestMatching['handler']->exec($requestMatching['urlNameMatching']);
        }

        if ($requestMatching['handler'] instanceof MethodProc) {
            $requestMatching['handler']->execConstructorWithParameterMap($map);
        }
        return $requestMatching['handler']->execWithParameterMap($map);
    }

    private function validateRoutePath(RequestInterface $request)
    {
        if ($this->matcher->match($request) === false) {
            throw new RoutePathNotFound(
                sprintf('Route path not found: %s (%s)',
                            $request->getUri()->getPath(),
                            $request->getMethod()
                )
            );
        }
    }
}


<?php
/**
 * This file is part of VinceTAdminBundle for Symfony2
 *
 * @category VinceT
 * @package  VinceTAdminBundle
 * @author   Vincent Touzet <vincent.touzet@gmail.com>
 * @license  MIT License view the LICENSE file that was distributed with this source code.
 * @link     https://github.com/vincenttouzet/AdminBundle
 */

namespace VinceT\AdminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

/**
 * This file is part of VinceTBaseBundle for Symfony2
 *
 * @category VinceT
 * @package  VinceTAdminBundle
 * @author   Vincent Touzet <vincent.touzet@gmail.com>
 * @license  MIT License view the LICENSE file that was distributed with this source code.
 * @link     https://github.com/vincenttouzet/AdminBundle
 */
abstract class AdminController extends Controller
{
    /**
     * Render a view
     *
     * @param string   $view       Twig view
     * @param array    $parameters View parameters
     * @param Response $response   Response
     *
     * @return Response
     */
    public function render($view, array $parameters = array(), Response $response = null)
    {
        $parameters['base_template'] = isset($parameters['base_template']) ? $parameters['base_template'] : $this->getBaseTemplate();
        $parameters['admin_pool']    = $this->get('sonata.admin.pool');

        return parent::render($view, $parameters);
    }

    /**
     * return the base template name
     *
     * @return string the template name
     */
    public function getBaseTemplate()
    {
        if ($this->get('request')->isXmlHttpRequest()) {
            return 'SonataAdminBundle::ajax_layout.html.twig';
        }

        return 'SonataAdminBundle::standard_layout.html.twig';
    }
}


<?php

namespace ebussola\common\datatype;

use Doctrine\Common\Inflector\Inflector;

/**
 * Thanks to Miguel Elias Santos <migueleliasweb at gmail dot com>
 *
 * Alternative implementation of PHP's native
 * It magically (__call) routes all 'array_' native function correnctly
 *
 * @method ArrayList changeKeyCase    Changes all keys in an array
 * @method ArrayList chunk              Split an array into chunks
 * @method ArrayList combine            Creates an array by using one array for keys and another for its values
 * @method ArrayList countValues       Counts all the values of an array
 * @method ArrayList diffAssoc         Computes the difference of arrays with additional index check
 * @method ArrayList diffKey           Computes the difference of arrays using keys for comparison
 * @method ArrayList diffUassoc        Computes the difference of arrays with additional index check which is performed by a user supplied callback function
 * @method ArrayList diffUkey          Computes the difference of arrays using a callback function on the keys for comparison
 * @method ArrayList diff               Computes the difference of arrays
 * @method ArrayList fillKeys          Fill an array with values, specifying keys
 * @method ArrayList fill               Fill an array with values
 * @method ArrayList filter             Filters elements of an array using a callback function
 * @method ArrayList flip               Exchanges all keys with their associated values in an array
 * @method ArrayList intersectAssoc    Computes the intersection of arrays with additional index check
 * @method ArrayList intersectKey      Computes the intersection of arrays using keys for comparison
 * @method ArrayList intersectUassoc   Computes the intersection of arrays with additional index check, compares indexes by a callback function
 * @method ArrayList intersectUkey     Computes the intersection of arrays using a callback function on the keys for comparison
 * @method ArrayList intersect          Computes the intersection of arrays
 * @method ArrayList keyExists         Checks if the given key or index exists in the array
 * @method ArrayList keys               Return all the keys or a subset of the keys of an array
 * @method ArrayList map                Applies the callback to the elements of the given arrays
 * @method ArrayList mergeRecursive    Merge two or more arrays recursively
 * @method ArrayList merge              Merge one or more arrays
 * @method ArrayList multisort          Sort multiple or multi-dimensional arrays
 * @method ArrayList pad                Pad array to the specified length with a value
 * @method ArrayList pop                Pop the element off the end of array
 * @method ArrayList product            Calculate the product of values in an array
 * @method ArrayList push               Push one or more elements onto the end of array
 * @method ArrayList rand               Pick one or more random entries out of an array
 * @method ArrayList reduce             Iteratively reduce the array to a single value using a callback function
 * @method ArrayList replaceRecursive  Replaces elements from passed arrays into the first array recursively
 * @method ArrayList replace            Replaces elements from passed arrays into the first array
 * @method ArrayList reverse            Return an array with elements in reverse order
 * @method ArrayList search             Searches the array for a given value and returns the corresponding key if successful
 * @method ArrayList shift              Shift an element off the beginning of array
 * @method ArrayList slice              Extract a slice of the array
 * @method ArrayList splice             Remove a portion of the array and replace it with something else
 * @method ArrayList sum                Calculate the sum of values in an array
 * @method ArrayList udiffAssoc        Computes the difference of arrays with additional index check, compares data by a callback function
 * @method ArrayList udiffUassoc       Computes the difference of arrays with additional index check, compares data and indexes by a callback function
 * @method ArrayList udiff              Computes the difference of arrays by using a callback function for data comparison
 * @method ArrayList uintersectAssoc   Computes the intersection of arrays with additional index check, compares data by a callback function
 * @method ArrayList uintersectUassoc  Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions
 * @method ArrayList uintersect         Computes the intersection of arrays, compares data by a callback function
 * @method ArrayList unique             Removes duplicate values from an array
 * @method ArrayList unshift            Prepend one or more elements to the beginning of an array
 * @method ArrayList values             Return all the values of an array
 * @method ArrayList walkRecursive     Apply a user function recursively to every member of an array
 */
class ArrayList extends \ArrayObject
{

    public function __call($func, $argv)
    {
        $func = 'array_' . Inflector::tableize($func);
        if (!is_callable($func)) {
            throw new \BadMethodCallException(__CLASS__ . '->' . $func);
        }

        // some functions don't follow the others array functions argument pattern ¬¬
        if (in_array($func, array('array_map', 'array_search'))) {
            $args = array_merge($argv, array($this->getArrayCopy()));
        } else {
            $args = array_merge(array($this->getArrayCopy()), $argv);
        }
        $result = call_user_func_array($func, $args);

        if (is_array($result)) {
            // some array functions dont return an array
            // eg.: array_reduce
            $result = new self($result);
        }

        return $result;
    }

    /**
     * Apply a user function to every member of an array
     *
     * @param Callable $callback
     * @return bool
     */
    public function walk(Callable $callback)
    {
        $arrayCopy = $this->getArrayCopy();
        $result = array_walk($arrayCopy, $callback);
        $this->exchangeArray($arrayCopy);
        return $result;
    }

}


<?php

namespace OpenOrchestra\ModelBundle\DataFixtures\MongoDB;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use OpenOrchestra\ModelBundle\Document\Content;
use OpenOrchestra\ModelBundle\Document\ContentAttribute;
use OpenOrchestra\ModelInterface\DataFixtures\OrchestraFunctionalFixturesInterface;
use OpenOrchestra\ModelInterface\Model\ContentInterface;

/**
 * Class LoadContentData
 */
class LoadContentData extends AbstractFixture implements OrderedFixtureInterface, OrchestraFunctionalFixturesInterface
{
    protected $objectManager;

    /**
     * @param ObjectManager $objectManager
     */
    public function load(ObjectManager $objectManager)
    {
        $this->objectManager = $objectManager;
        $languages = array('fr', "en");
        $this->persistMultiLanguageContent("generateCarR5", $languages);
        $this->persistMultiLanguageContent("generateCar206", $languages);
        $this->persistMultiLanguageContent("generateCarDs3", $languages);
        $this->persistMultiLanguageContent("generateCustomerConvenant", $languages);

        $objectManager->flush();
    }

    /**
     * Get the order of this fixture
     *
     * @return integer
     */
    public function getOrder()
    {
        return 510;
    }

    /**
     * @param string $methodName
     * @param array  $languages
     */
    protected  function persistMultiLanguageContent($methodName, array $languages)
    {
        foreach ($languages as $language) {
            $this->objectManager->persist($this->$methodName($language));
        }
    }

    /**
     * Generate a content attribute
     *
     * @param string $name
     * @param string $value
     * @param string $type
     *
     * @return ContentAttribute
     */
    protected function generateContentAttribute($name, $value, $type = 'text')
    {
        $attribute = new ContentAttribute();
        $attribute->setName($name);
        $attribute->setValue($value);
        $attribute->setStringValue($value);
        $attribute->setType($type);

        return $attribute;
    }

    /**
     * @param string $language
     *
     * @return Content
     */
    public function generateCarR5($language)
    {
        $content = $this->addBaseContent("r5_3_portes", "car", 1);

        $attribute1 = $this->generateContentAttribute('car_name', 'R5');
        $attribute2 = $this->generateContentAttribute('description',
            'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean non feugiat sem.
             Aliquam a mauris tellus. In hac habitasse platea dictumst. Nunc eget interdum
             ante, id mollis diam. Suspendisse sed magna lectus. Aenean fringilla elementum
             lorem id suscipit. Phasellus feugiat tellus sapien, id tempus nisi ultrices ut.');

        $content->setName("R5 3 portes " . $language);
        $content->setLanguage($language);
        $content->setVersion('2');
        $content->addKeyword($this->getReference('keyword-lorem'));
        $content->setLinkedToSite(false);
        $content->setSiteId('2');
        $content->setVersionName($this->getVersionName($content));

        $content->addAttribute($attribute1);
        $content->addAttribute($attribute2);

        return $content;
    }

    /**
     * @param string $language
     *
     * @return Content
     */
    public function generateCarDs3($language)
    {
        $content = $this->addBaseContent("ds_3", "car", 1);
        $content->setDeleted(false);
        $content->setName("DS 3 " . $language);
        $content->setLanguage($language);
        $content->setVersion('1');
        $content->addKeyword($this->getReference('keyword-lorem'));
        $content->setLinkedToSite(true);
        $content->setSiteId('2');
        $content->setVersionName($this->getVersionName($content));

        $attribute1 = $this->generateContentAttribute('car_name', 'Ds3');
        $attribute2 = $this->generateContentAttribute('description',
            'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean non feugiat sem.
             Aliquam a mauris tellus. In hac habitasse platea dictumst. Nunc eget interdum
             ante, id mollis diam. Suspendisse sed magna lectus. Aenean fringilla elementum
             lorem id suscipit. Phasellus feugiat tellus sapien, id tempus nisi ultrices ut.');

        $content->addAttribute($attribute1);
        $content->addAttribute($attribute2);
        $this->setReference("ds_3_".$language, $content);

        return $content;
    }

    /**
     * @param string $language
     *
     * @return Content
     */
    public function generateCar206($language)
    {
        $content = $this->addBaseContent("206_3_portes", "car", 1);
        $content->setName("206 3 portes " . $language);
        $content->setLanguage($language);
        $content->setVersion('2');
        $content->addKeyword($this->getReference('keyword-lorem'));
        $content->addKeyword($this->getReference('keyword-sit'));
        $content->setLinkedToSite(false);
        $content->setSiteId('2');
        $content->setVersionName($this->getVersionName($content));

        $attribute1 = $this->generateContentAttribute('car_name', '206');
        $attribute2 = $this->generateContentAttribute('description',
            'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean non feugiat sem.
            Aliquam a mauris tellus. In hac habitasse platea dictumst. Nunc eget interdum ante,
             id mollis diam. Suspendisse sed magna lectus. Aenean fringilla elementum lorem id
             suscipit. Phasellus feugiat tellus sapien, id tempus nisi ultrices ut.');

        $content->addAttribute($attribute1);
        $content->addAttribute($attribute2);

        return $content;
    }

    /**
     * @param string $language
     *
     * @return Content
     */
    public function generateCustomerConvenant($language)
    {
        $content = $this->addBaseContent("jean_paul", 'customer', 1);
        $content->setName("Jean-Paul");
        $content->setLanguage($language);
        $content->setVersion('2');
        $content->addKeyword($this->getReference('keyword-lorem'));
        $content->addKeyword($this->getReference('keyword-sit'));
        $content->setLinkedToSite(false);
        $content->setSiteId('2');
        $content->setVersionName($this->getVersionName($content));

        $attribute1 = $this->generateContentAttribute('firstname', 'Jean-Claude');
        $attribute2 = $this->generateContentAttribute('lastname', 'Convenant');
        $attribute3 = $this->generateContentAttribute('identifier', 28, 'integer');

        $content->addAttribute($attribute1);
        $content->addAttribute($attribute2);
        $content->addAttribute($attribute3);

        return $content;
    }

    /**
     * @param string $id
     * @param string $type
     * @param int    $typeVersion
     *
     * @return Content
     */
    protected function addBaseContent($id, $type, $typeVersion)
    {
        $content = new Content();
        $content->setContentId($id);
        $content->setContentType($type);
        $content->setDeleted(false);
        $content->setCreatedBy('admin');
        $content->setStatus($this->getReference('status-published'));

        return $content;
    }

    /**
     * @param ContentInterface $content
     *
     * @return string
     */
    protected function getVersionName(ContentInterface $content)
    {
        $date = new \DateTime("now");

        return $content->getName().'_'. $content->getVersion(). '_'. $date->format("Y-m-d_H:i:s");
    }
}


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

namespace cascade\components\dataInterface\connectors\db;

use Yii;
use yii\db\Query;

/**
 * Model for foreign data items in a database connection.
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class Model extends \cascade\components\dataInterface\connectors\generic\Model
{
    /**
     * @var string table name for model
     */
    protected $_tableName;
    /**
     * @var Meta meta object
     */
    protected $_meta;
    /**
     * @var array keys from model
     */
    protected $_keys;

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
        $metaConfig = [];
        if (isset($this->_meta)) {
            $metaConfig = $this->_meta;
        }
        $this->_meta = Meta::get($this->interface, $this->tableName);
        Yii::configure($this->_meta, $metaConfig);
    }

    /**
     * @inheritdoc
     */
    public function hasAttribute($attribute)
    {
        return isset($this->meta) && is_object($this->meta) && $this->meta->hasAttribute($attribute);
    }
    /**
     * Set table name.
     *
     * @param string $value the table name
     */
    public function setTableName($value)
    {
        $this->_tableName = $value;
    }

    /**
     * Get children.
     *
     * @return array child objects for this model
     */
    public function getChildren()
    {
        if (is_null($this->_children)) {
            $children = [];
            // for this application, there is no distinction between hasOne and hasMany on the database level
            $hasMany = array_merge($this->meta->hasMany, $this->meta->hasOne);
            foreach ($hasMany as $r) {
                if (!isset($r['foreignModel'])) {
                    var_dump($r);
                    exit;
                    continue;
                }
                if (is_string($r['foreignModel'])
                    && (!isset($this->interface->foreignModels[$r['foreignModel']])
                    || !($r['foreignModel'] = $this->interface->foreignModels[$r['foreignModel']]))) {
                    continue;
                }
                $params = isset($r['params']) ? $r['params'] : [];
                $params[':foreignKeyId'] = $this->primaryKey;

                $where = isset($r['where']) ? $r['where'] : [];
                if (!empty($where)) {
                    $where = ['and', $where, $r['foreignKey'] . '=:foreignKeyId'];
                } else {
                    $where = $r['foreignKey'] . '=:foreignKeyId';
                }
                $query = [
                    'where' => $where,
                    'params' => $params,
                ];
                if (isset($r['join'])) {
                    $query['join'] = $r['join'];
                }
                $children[$r['foreignModel']->tableName] = $r['foreignModel']->findPrimaryKeys($query);
            }

            $this->_children = $children;
        }

        return $this->_children;
    }
    /**
     * Retrieve the primary key column for the model item.
     *
     * @return string the primary key
     */
    public function primaryKey()
    {
        $pk = $this->meta->schema->primaryKey;
        if (is_array($pk)) {
            $ppk = [];
            foreach ($pk as $key) {
                $ppk[] = $key;
            }

            return implode('.', $ppk);
        }

        return $pk;
    }

    /**
     * Get primary key.
     *
     * @return string the primary key
     */
    public function getPrimaryKey()
    {
        $pk = $this->meta->schema->primaryKey;
        if (is_array($pk)) {
            $ppk = [];
            foreach ($pk as $key) {
                if (!isset($this->attributes[$key])) {
                    $ppk[] = null;
                } else {
                    $ppk[] = $this->attributes[$key];
                }
            }

            return implode('.', $ppk);
        }
        if (!isset($this->attributes[$pk])) {
            return;
        }

        return $this->attributes[$pk];
    }

    /**
     * Get attributes.
     *
     * @return array of the attribute values
     */
    public function getAttributes()
    {
        $a = [];
        foreach ($this->meta->attributeKeys as $k) {
            $a[$k] = null;
            if (is_array($this->_attributes) && isset($this->_attributes[$k])) {
                $a[$k] = $this->_attributes[$k];
            }
        }

        return $a;
    }

    /**
     * Get meta.
     *
     * @return Meta the model meta
     */
    public function getMeta()
    {
        return $this->_meta;
    }

    /**
     * Set meta.
     *
     * @param Meta $value the meta object
     */
    public function setMeta($value)
    {
        $this->_meta = $value;
    }

    /**
     * Find the models for a foreign data source.
     *
     * @param array $params the query parameters
     *
     * @return Query the foreign data query
     */
    protected function find($params)
    {
        $debug = false;
        $q = new Query();
        $q->select('*');
        $q->from($this->_tableName);
        foreach ($params as $k => $v) {
            if ($k === 'join') {
                foreach ($v as $join) {
                    if (!isset($join['type'])) {
                        $join['type'] = 'INNER JOIN';
                    }
                    if (!isset($join['params'])) {
                        $join['params'] = [];
                    }
                    $q->join($join['type'], $join['table'], $join['on'], $join['params']);
                }
                $debug = true;
            } elseif (in_array($k, ['where'])) {
                $q->{$k}($v);
            } else {
                $q->{$k} = $v;
            }
        }
        if ($debug) {
            //var_dump($q->createCommand()->rawSql);exit;
        }

        return $q;
    }

    /**
     * Find all the foreign database records.
     *
     * @param array $params find params for the query [optional]
     *
     * @return array of foreign data records
     */
    public function findAll($params = [])
    {
        $return = $this->populateRecords($this->find($params)->all($this->interface->db));

        return $return;
    }

    /**
     * Find one foreign database record.
     *
     * @param array $params find params for the query [optional]
     *
     * @return Model database record
     */
    public function findOne($params = [])
    {
        return $this->populateRecord($this->find($params)->one($this->interface->db));
    }

    /**
     * Return the primary keys (used in lazy loading).
     *
     * @param array $params find params for the query [optional]
     *
     * @return array keys from the data source items
     */
    public function findPrimaryKeys($params = [])
    {
        $q = $this->find($params);
        $q->select($this->_tableName . '.' . $this->meta->schema->primaryKey[0]);

        return $q->column($this->interface->db);
    }

    /**
     * Get table name.
     *
     * @return string name of the table
     */
    public function getTableName()
    {
        return $this->_tableName;
    }
}


<?php

namespace Isolate\LazyObjects;

use Isolate\LazyObjects\Exception\InvalidArgumentException;
use Isolate\LazyObjects\Proxy\Definition;
use Isolate\LazyObjects\Proxy\Factory;
use Isolate\LazyObjects\Exception\RuntimeException;

/**
 * @api
 */
class Wrapper
{
    /**
     * @var array|Definition[]
     */
    private $definitions;

    /**
     * @var Factory
     */
    private $factory;

    /**
     * @param Factory $factory
     * @param array $definitions
     * @throws InvalidArgumentException
     */
    public function __construct(Factory $factory, $definitions = [])
    {
        $this->definitions = [];

        if (!is_array($definitions) && !$definitions instanceof \Traversable) {
            throw new InvalidArgumentException("Lazy objects definitions collection must be traversable.");
        }

        foreach ($definitions as $definition) {
            if (!$definition instanceof Definition) {
                throw new InvalidArgumentException("Lazy object definition must be an instance of Isolate\\LazyObjects\\Proxy\\Definition");
            }

            $this->definitions[] = $definition;
        }

        $this->factory = $factory;
    }

    /**
     * @param $object
     * @return bool
     *
     * @api
     */
    public function canWrap($object)
    {
        foreach ($this->definitions as $proxyDefinition) {
            if ($proxyDefinition->describeProxyFor($object)) {
                return true;
            }
        }

        return false;
    }

    /**
     * @param $object
     * @return WrappedObject
     * @throws RuntimeException
     *
     * @api
     */
    public function wrap($object)
    {
        foreach ($this->definitions as $proxyDefinition) {
            if ($proxyDefinition->describeProxyFor($object)) {
                return $this->factory->createProxy($object, $proxyDefinition);
            }
        }

        throw new RuntimeException("Can\"t wrap objects that does\"t fit any proxy definition.");
    }
}


<?php

/**
 * Url Manager
 *
 * @category  	core
 * @package   	core\
 * @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\core;

/**
 * Url Manager
 *
 * @category  	core
 * @package   	core\
 * @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 UrlManager
{
    /**
     * The base Uri to construct the route
     * @var string
     */
    private $_sBaseUri = '';

    /**
     * create an URL
     *
     * @access public
     * @param  string $sCode code of the url between "routes" and "route" in Route.conf
     * @param  array $aParams parameters to create the url
     * @return string
     *
     * @tutorial	If I have this route I could make my URL:
     *
     * 				"menu_edit": {
     *					"route": "[/:language]/menu[/:id]/edit/",
     *					"controller": "\\src\\BackOffice\\Controller\\MenuManager",
     *					"action": "edit",
     *					"constraints": {
     * 						"language": "[a-z]{0,2}",
     * 						"id": "[0-9]+"
     *					},
     *					"content_type": "html"
     *				},
     *
     *				I must write this:
     *
     *				$oUrlManager = new \Venus\core\UrlManager;
     *				$sUrl = $oUrlManager->getUrl('menu_edit', array('language' => 'vn', 'id' => 125));
     */
    public function getUrl(string $sCode, array $aParams = array()) : string
    {
        if (isset($_SERVER) && isset($_SERVER['HTTP_HOST'])) {

            foreach (Config::get('route') as $sHost => $oHost) {

                if ((!strstr($sHost, '/') && $sHost == $_SERVER['HTTP_HOST'])
                    || (strstr($sHost, '/')
                    && strstr($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'], $sHost))) {

                    if (strstr($sHost, '/')
                        && strstr($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'], $sHost)) {

                        $this->_sBaseUri = preg_replace('#^[^/]+#', '', $sHost);
                    }

                    if (isset($oHost->routes)) {

                        foreach($oHost->routes as $sKey => $oRoute) {

                            if ($sKey === $sCode) {

                                $sRoute = $this->_sBaseUri.$oRoute->route;

                                if (isset($oRoute->constraints)) {

                                    foreach ($oRoute->constraints as $sName => $sType) {

                                        if (!isset($aParams[$sName])) { $aParams[$sName] = ''; }

                                        if (preg_match('#'.$sType.'#', $aParams[$sName])) {

                                            if ($aParams[$sName]) { $sRoute = str_replace('[/:'.$sName.']', '/'.$aParams[$sName], $sRoute); } else { $sRoute = str_replace('[/:'.$sName.']', '', $sRoute); }
                                            $sRoute = str_replace('[:'.$sName.']', $aParams[$sName], $sRoute);
                                            continue;
                                        } else if (isset($oRoute->defaults_constraints)
                                            && isset($oRoute->defaults_constraints->{$sName})
                                            && preg_match('#'.$sType.'#', $oRoute->defaults_constraints->{$sName})) {

                                            continue;
                                        }

                                        throw new \Exception('For the route '.$sCode.' the parameter '.$sName.' is not good!');
                                    }
                                }

                                return $sRoute;
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * encode text for the url
     *
     * @access public
     * @param  string $sStringToEncode text
     * @return string
     */
    public function encodeToUrl(string $sStringToEncode) : string
    {
        if (!is_string($sStringToEncode)) {

            throw new \Exception();
        }

        $sStringToEncode = str_replace(['à','á','â','ã','ä','ç','è','é','ê','ë','ì','í','î','ï','ñ','ò','ó','ô','õ','ö','ù','ú','û','ü','ý','ÿ','À','Á','Â','Ã','Ä','Ç','È','É','Ê','Ë','Ì','Í','Î','Ï','Ñ','Ò','Ó','Ô','Õ','Ö','Ù','Ú','Û','Ü','Ý'],
            ['a','a','a','a','a','c','e','e','e','e','i','i','i','i','n','o','o','o','o','o','u','u','u','u','y','y','A','A','A','A','A','C','E','E','E','E','I','I','I','I','N','O','O','O','O','O','U','U','U','U','Y'],
                $sStringToEncode);

        $sStringToEncode = preg_replace('/[^a-zA-Z0-9_]+/', '_', preg_quote($sStringToEncode));
        return strtolower($sStringToEncode);
    }
}


<?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\Action;

use ItePHP\Mapper\MapperAbstract;
use ItePHP\Core\ExecuteActionEvent;
use ItePHP\Core\InvalidConfigValueException;
use ItePHP\Core\Request;
use ItePHP\Core\Container;
use ItePHP\Validator\ValidatorAbstract;
use Pactum\ConfigContainer;

/**
 * Event to forward http param ($_POST[],$_GET[],url) to controller method.
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
class ArgumentEvent{

	/**
	 *
	 * @var Container
	 */
	private $container;

	/**
	 *
	 * @param Container $container
	 */
	public function __construct(Container $container){
		$this->container=$container;
	}

	/**
	 * Detect config argument.
	 *
	 * @param ExecuteActionEvent $event
	 */
	public function onExecuteAction(ExecuteActionEvent $event){
		$request=$event->getRequest();
		$position=1;
		foreach($request->getConfig()->getArray('argument') as $argument){
			$this->validateArgument($request,$argument,$position++);
		}
	}

	/**
	 * Validate argument.
	 *
	 * @param Request $request
	 * @param ConfigContainer $config argument
	 * @param int $position
	 * @throws InvalidConfigValueException
	 * @throws InvalidArgumentException
	 */
	private function validateArgument(Request $request , ConfigContainer $config , $position){
		$value=null;
		switch($config->getValue('storage')){
			case 'url':
				$value=$this->validateUrl($request , $config , $position);
			break;
			case 'post':
				$value=$this->validateGetPost($request->getData() , $config , $position);
			break;
			case 'get':
				$value=$this->validateGetPost($request->getQuery() , $config , $position);
			break;
			default:
				throw new InvalidConfigValueException('storage',$config->getValue('storage'));

		}

		$validatorName=$config->getValue('validator');
		if($validatorName!==''){
            /**
             * @var ValidatorAbstract $validatorObject
             */
			$validatorObject=new $validatorName();
			$error=$validatorObject->validate($value);
			if($error){
				throw new InvalidArgumentException($position,$config->getValue('name'),$error);
			}
		}

		$mapperName=$config->getValue('mapper');
		if($mapperName!==''){
            /**
             * @var MapperAbstract $mapper
             */
			$mapper=new $mapperName($this->container);
			$value=$mapper->cast($value);
		}
		$request->setArgument($config->getValue('name'),$value);

	}

	/**
	 * Validate url.
	 *
	 * @param Request $request
	 * @param ConfigContainer $config argument
	 * @param int $position
	 * @return string
	 * @throws RequiredArgumentException
	 */
	private function validateUrl(Request $request , ConfigContainer $config , $position){
		$url=$request->getUrl();
		$default=$config->getValue('default');
		if(preg_match('/^'.$config->getValue('pattern').'$/',$url,$matches) && isset($matches[1])){
			return $matches[1];
		}
		else if($default!==false){
			return $config->getValue('default');
		}
		else{
			throw new RequiredArgumentException($position,$config->getValue('name'));
		}
	}

	/**
	 * Validate GET.
	 *
	 * @param string[] $data http post/get data
	 * @param ConfigContainer $config argument
	 * @param int $position
	 * @return string
	 * @throws RequiredArgumentException
	 */
	private function validateGetPost($data , ConfigContainer $config , $position){
		$argumentName=$config->getValue('name');
		$default=$config->getValue('default');
		if(!isset($data[$argumentName])){
			if($default!==false){
				return $default;
			}
			else{
				throw new RequiredArgumentException($position,$argumentName);
			}
		}

		return $data[$argumentName];
	}

}


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

use JMS\Serializer\Annotation\Type;
use JMS\Serializer\Annotation\Exclude;
use RedKiteCms\Content\Block\ExtendableBlock;

/**
 * Class ImageBlock is the object deputed to handle an image
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Block\Image\Core
 */
class ImageBlock extends ExtendableBlock
{
    /**
     * @Type("string")
     */
    protected $type = "Image";
    /**
     * @Type("string")
     */
    protected $href = "";
    /**
     * @Type("array")
     */
    protected $tags = array(
        'src' => '/plugins/image/images/sample.jpg',
        'title' => '',
        'alt' => '',
        'class' => 'img-responsive',
    );
    /**
     * @Type("string")
     */
    protected $customTag = "rkcms-image";

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

    /**
     * {@inheritdoc}
     */
    public function updateSource()
    {
        $source = array(
            "value" => $this->value,
            "tags" => $this->tags,
            "href" => $this->href,
            "type" => $this->type,
        );

        $this->source = \Symfony\Component\Yaml\Yaml::dump($source, 100, 2);
    }

    /**
     * {@inheritdoc}
     */
    protected function getTranslatorOptions()
    {
        return array(
            "domain" => "RedKiteCms",
            "fields" => array(),
        );
    }
}