<?php
/*
 * This file is part of the Qimnet update tracker Bundle.
 *
 * (c) Antoine Guigan <aguigan@qimnet.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */
namespace Qimnet\UpdateTrackerBundle\Response;

use Qimnet\UpdateTrackerBundle\UpdateTracker\UpdateManagerInterface;
use Symfony\Component\HttpFoundation\Response;

/**
 * Generates public cached HTTP responses for a given update tracker namespace.
 *
 * The following cache properties are set by the factory:
 *   - public
 *   - maxAge
 *   - sharedMaxAge
 *   - lastModified
 */
class HTTPCachedResponseFactory
{
    protected $manager;
    protected $maxAge;
    protected $sharedMaxAge;

    /**
     * Constructor
     *
     * @param UpdateManagerInterface $manager
     * @param int                    $maxAge
     * @param int                    $sharedMaxAge
     */
    public function __construct(UpdateManagerInterface $manager, $maxAge=60, $sharedMaxAge=60)
    {
        $this->manager = $manager;
        $this->maxAge = $maxAge;
        $this->sharedMaxAge = $sharedMaxAge;
    }
    /**
     * Generate a Response object
     *
     * @param  mixed    $date     a single namespace, an array of namespaces, or a \DateTime object
     * @param  Response $response
     * @return Response
     */
    public function generate($date='global', Response $response=null)
    {
        if (!$response) $response = new Response;
        if ($this->maxAge) $response->setMaxAge ($this->maxAge);
        if ($this->sharedMaxAge) $response->setSharedMaxAge ($this->sharedMaxAge);
        if ($date instanceof \DateTime) {
            $response->setLastModified($date);
        } else {
            $response->setLastModified($this->manager->getLastUpdate($date));
        }

        return $response;
    }
}


<?php

namespace Laasti\Pagination;

trait PaginationFactoryTrait
{

    /**
     * Create a new pagination object
     *
     * @param int $currentPage
     * @param int $total
     * @param int $perPage
     * @param string $baseUrl
     * @param int $neighbours
     * @return Pagination
     */
    public function createPagination($currentPage, $total, $perPage = null, $baseUrl = null, $neighbours = null)
    {
        if (isset($this->container) && $this->container instanceof \League\Container\ContainerInterface) {
            return $this->getContainer()->get('Laasti\Pagination\Pagination', [$currentPage, $total, $perPage, $baseUrl, $neighbours]);
        }

        $perPage = $perPage ?: 10;
        $baseUrl = $baseUrl ?: '';
        $neighbours = $neighbours ?: 3;

        return new Pagination($currentPage, $total, $perPage, $baseUrl, $neighbours);
    }

}


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

use JMS\Serializer\SerializerInterface;
use RedKiteCms\Contribution\ContributionManagerInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class Slot is the object assigned to handle a website slot
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\FilesystemEntity
 */
class Slot extends Entity implements RenderableInterface
{
    /**
     * @type string
     */
    private $slotName = null;
    /**
     * @type string
     */
    private $username = null;
    /**
     * @type string
     */
    private $sourceDir = null;
    /**
     * @type \RedKiteCms\FilesystemEntity\SlotParser
     */
    private $slotParser;

    private $next = 1;

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

    /**
     * Constructor
     *
     * @param \JMS\Serializer\SerializerInterface $serializer
     * @param \Symfony\Component\OptionsResolver\OptionsResolver $optionsResolver
     * @param \RedKiteCms\FilesystemEntity\SlotParser $slotParser
     */
    public function __construct(
        SerializerInterface $serializer,
        OptionsResolver $optionsResolver,
        SlotParser $slotParser
    ) {
        parent::__construct($serializer, $optionsResolver);

        $this->slotParser = $slotParser;
    }

    /**
     * Returns the slot name
     *
     * @return string
     */
    public function getSlotName()
    {
        return $this->slotName;
    }

    /**
     * Refreshes the slot entity
     */
    public function refresh()
    {
        if (null === $this->options || null === $this->sourceDir) {
            return;
        }

        $this->render($this->sourceDir, $this->options, $this->username);
    }

    /**
     * {@inheridoc}
     */
    public function render($sourceDir, array $options, $username = null)
    {
        $this->sourceDir = $sourceDir;
        $this->options = $options;
        $this->username = $username;
        $this->slotName = $options["slot"];
        $this->init($sourceDir, $options, $username);

        $slot = $this->slotParser->fetchBlocks(
            $this->productionDir,
            $this->productionDir,
            $this->slotName
        );
        $this->productionEntities = $slot["blocks"];

        $slot = $this->slotParser->fetchBlocks(
            $this->productionDir,
            $this->contributorDir,
            $this->slotName
        );

        $this->next = $slot["next"];
        $this->contributorEntities = $slot["blocks"];
    }
}


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

namespace cascade\components\web\widgets\section;

use canis\helpers\Html;
use Yii;

/**
 * SingleSection [[@doctodo class_description:cascade\components\web\widgets\section\SingleSection]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class SingleSection extends Section
{
    /**
     * @inheritdoc
     */
    public $section;
    /**
     * @var [[@doctodo var_type:_singleWidget]] [[@doctodo var_description:_singleWidget]]
     */
    protected $_singleWidget;

    /**
     * Get cell.
     *
     * @return [[@doctodo return_type:getCell]] [[@doctodo return_description:getCell]]
     */
    public function getCell()
    {
        $widgetCell = $this->singleWidget;
        if ($widgetCell) {
            $widgetCell->prepend(Html::tag('div', '', ['id' => 'section-' . $this->systemId, 'class' => 'scroll-mark']));

            return $widgetCell;
        }

        return false;
    }

    /**
     * Get single widget.
     *
     * @return [[@doctodo return_type:getSingleWidget]] [[@doctodo return_description:getSingleWidget]]
     */
    public function getSingleWidget()
    {
        if (is_null($this->_singleWidget)) {
            $this->_singleWidget = false;
            $widgets = $this->collectorItem->getAll();
            if (!empty($widgets)) {
                $widget = array_shift($widgets);
                $this->_singleWidget = Yii::$app->collectors['widgets']->build($this, $widget->object);
            }
        }

        return $this->_singleWidget;
    }

    /**
     * @inheritdoc
     */
    public function getTitle()
    {
        $singleWidget = $this->singleWidget;
        if ($singleWidget && isset($singleWidget->content->panelTitle)) {
            return $singleWidget->content->panelTitle;
        }

        return parent::getTitle();
    }
}


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

namespace Praxigento\BonusHybrid\Service\Calc\SignUpDebit\A;

use Praxigento\Accounting\Repo\Data\Transaction as Trans;
use Praxigento\BonusBase\Repo\Data\Log\Customers as LogCust;
use Praxigento\BonusBase\Repo\Data\Log\Opers as LogOpers;
use Praxigento\BonusBase\Repo\Data\Log\Sales as LogSales;
use Praxigento\BonusHybrid\Config as Cfg;
use Praxigento\BonusHybrid\Repo\Data\Registry\SignUpDebit as RegSignup;
use Praxigento\BonusHybrid\Service\Calc\SignUpDebit\A\Repo\Query\GetOrders as QGetOrders;

/**
 * Debit 100 PV from customer & add 34.00 AMNT to parent's bonus.
 */
class ProcessOrders
{
    const OPT_CALC_ID = 'calc_id';
    const OPT_DATE_APPLIED = 'date_applied';
    const OPT_ORDERS = 'orders';

    /**
     * Prefixes to map transactions to orders to log relations on operation post.
     * Should be 2 chars length.
     */
    const PREFIX_PV = 'pv';
    const PREFIX_BONUS_FATHER = 'wf';
    const PREFIX_BONUS_GRAND = 'wg';

    /** @var \Praxigento\BonusBase\Repo\Dao\Log\Customers */
    private $daoLogCust;
    /** @var \Praxigento\BonusBase\Repo\Dao\Log\Opers */
    private $daoLogOper;
    /** @var \Praxigento\BonusBase\Repo\Dao\Log\Sales */
    private $daoLogSale;
    /** @var \Praxigento\BonusHybrid\Repo\Dao\Registry\SignUpDebit */
    private $daoRegSignUpDebit;
    /** @var  \Praxigento\BonusHybrid\Api\Helper\Scheme */
    private $hlpScheme;
    /** @var \Praxigento\Accounting\Api\Service\Account\Get */
    private $servAccount;
    /** @var \Praxigento\Accounting\Api\Service\Operation\Create */
    private $servOper;

    public function __construct(
        \Praxigento\BonusHybrid\Api\Helper\Scheme $hlpScheme,
        \Praxigento\BonusBase\Repo\Dao\Log\Customers $daoLogCust,
        \Praxigento\BonusBase\Repo\Dao\Log\Opers $daoLogOper,
        \Praxigento\BonusBase\Repo\Dao\Log\Sales $daoLogSale,
        \Praxigento\BonusHybrid\Repo\Dao\Registry\SignUpDebit $daoRegSignUpDebit,
        \Praxigento\Accounting\Api\Service\Account\Get $servAccount,
        \Praxigento\Accounting\Api\Service\Operation\Create $servOper
    ) {
        $this->hlpScheme = $hlpScheme;
        $this->daoLogCust = $daoLogCust;
        $this->daoLogOper = $daoLogOper;
        $this->daoRegSignUpDebit = $daoRegSignUpDebit;
        $this->daoLogSale = $daoLogSale;
        $this->servAccount = $servAccount;
        $this->servOper = $servOper;
    }

    /**
     * @param array $orders
     * @param string $dateApplied
     * @param int $calcId
     * @throws \Exception
     */
    public function exec($orders, $dateApplied, $calcId)
    {
        /* get system accounts */
        $accPvSys = $this->getAccSys(Cfg::CODE_TYPE_ASSET_PV);
        $accBonusSys = $this->getAccSys(Cfg::CODE_TYPE_ASSET_BONUS);
        /* Create one operation for all transactions */
        $req = new \Praxigento\Accounting\Api\Service\Operation\Create\Request();
        $req->setOperationTypeCode(Cfg::CODE_TYPE_OPER_BONUS_SIGNUP_DEBIT);
        $period = substr($dateApplied, 0, 7);
        $period = str_replace('-', '', $period);
        $note = "Sign Up Debit ($period)";
        $req->setOperationNote($note);
        $transRef = 'ref';
        $req->setAsTransRef($transRef);
        /* prepare transactions */
        $trans = [];
        foreach ($orders as $one) {
            $custId = $one[QGetOrders::A_CUST_ID];
            $parentId = $one[QGetOrders::A_PARENT_ID];
            $grandId = $one[QGetOrders::A_PARENT_GRAND_ID];
            $orderId = $one[QGetOrders::A_SALE_ID];
            $scheme = $this->hlpScheme->getSchemeByCustomer($one);
            /** Sign Up Debit bonus is applied for EU customers only */
            if ($scheme == Cfg::SCHEMA_EU) {
                /* prepare data for transactions */
                $accPvCust = $this->getAccCust(Cfg::CODE_TYPE_ASSET_PV, $custId);
                $accBonusParent = $this->getAccCust(Cfg::CODE_TYPE_ASSET_BONUS, $parentId);
                $accBonusGrand = $this->getAccCust(Cfg::CODE_TYPE_ASSET_BONUS, $grandId);
                $note = 'Sign Up Debit bonus for order #' . $orderId;
                /* add PV transaction */
                $tranPvOff = [
                    Trans::A_DEBIT_ACC_ID => $accPvCust,
                    Trans::A_CREDIT_ACC_ID => $accPvSys,
                    Trans::A_DATE_APPLIED => $dateApplied,
                    Trans::A_VALUE => Cfg::SIGNUP_DEBIT_PV,
                    Trans::A_NOTE => $note,
                    $transRef => self::PREFIX_PV . $orderId
                ];
                $trans[] = $tranPvOff;
                /* add BONUS transaction for "father" */
                $tranBonusFatherOn = [
                    Trans::A_DEBIT_ACC_ID => $accBonusSys,
                    Trans::A_CREDIT_ACC_ID => $accBonusParent,
                    Trans::A_DATE_APPLIED => $dateApplied,
                    Trans::A_VALUE => Cfg::SIGNUP_DEBIT_BONUS_FATHER,
                    Trans::A_NOTE => $note . ' (level 1)',
                    $transRef => self::PREFIX_BONUS_FATHER . $orderId
                ];
                $trans[] = $tranBonusFatherOn;
                /* add BONUS transaction for "grand" */
                $tranBonusFatherOn = [
                    Trans::A_DEBIT_ACC_ID => $accBonusSys,
                    Trans::A_CREDIT_ACC_ID => $accBonusGrand,
                    Trans::A_DATE_APPLIED => $dateApplied,
                    Trans::A_VALUE => Cfg::SIGNUP_DEBIT_BONUS_GRAND,
                    Trans::A_NOTE => $note . ' (level 2)',
                    $transRef => self::PREFIX_BONUS_GRAND . $orderId
                ];
                $trans[] = $tranBonusFatherOn;
            }
        }
        $req->setTransactions($trans);
        $resp = $this->servOper->exec($req);
        /* log transactions into Customer & Order logs */
        $ids = $resp->getTransactionsIds();
        $this->saveTransLogs($orders, $ids);
        /* log operation */
        $operId = $resp->getOperationId();
        $this->daoLogOper->create([
            LogOpers::A_CALC_ID => $calcId,
            LogOpers::A_OPER_ID => $operId
        ]);
        /* save customers into Sign Up Registry */
        foreach ($orders as $one) {
            $custId = $one[QGetOrders::A_CUST_ID];
            $orderId = $one[QGetOrders::A_SALE_ID];
            $this->daoRegSignUpDebit->create([
                RegSignup::A_CALC_REF => $calcId,
                RegSignup::A_CUST_REF => $custId,
                RegSignup::A_SALE_REF => $orderId
            ]);

        }
    }

    /**
     * @param string $assetTypeCode
     * @param int $custId
     * @return int
     */
    private function getAccCust($assetTypeCode, $custId)
    {
        $req = new \Praxigento\Accounting\Api\Service\Account\Get\Request();
        $req->setAssetTypeCode($assetTypeCode);
        $req->setCustomerId($custId);
        $resp = $this->servAccount->exec($req);
        $result = $resp->getId();
        return $result;
    }

    /**
     * Get system account ID by asset type ID.
     *
     * @param string $assetTypeCode
     * @return int
     */
    private function getAccSys($assetTypeCode)
    {
        $req = new \Praxigento\Accounting\Api\Service\Account\Get\Request();
        $req->setIsSystem(TRUE);
        $req->setAssetTypeCode($assetTypeCode);
        $resp = $this->servAccount->exec($req);
        $result = $resp->getId();
        return $result;
    }

    /**
     * Save transaction-customer & transaction-order relations to log.
     *
     * @param array $orders
     * @param array $transIds
     */
    private function saveTransLogs($orders, $transIds)
    {
        /* re-map orders from with saleId key */
        $bySaleId = [];
        foreach ($orders as $custId => $order) {
            $saleId = $order[QGetOrders::A_SALE_ID];
            $bySaleId[$saleId] = $order;
        }
        foreach ($transIds as $tranId => $one) {
            $pref = substr($one, 0, 2);
            $orderId = str_replace($pref, '', $one);
            if ($pref == self::PREFIX_PV) {
                /* log PV off & order itself*/
                $custId = $bySaleId[$orderId][QGetOrders::A_CUST_ID];
                $this->daoLogCust->create([
                    LogCust::A_TRANS_ID => $tranId,
                    LogCust::A_CUSTOMER_ID => $custId
                ]);
                $this->daoLogSale->create([
                    LogSales::A_TRANS_ID => $tranId,
                    LogSales::A_SALE_ORDER_ID => $orderId
                ]);
            } elseif ($pref == self::PREFIX_BONUS_FATHER) {
                /* log BONUS Father On */
                $custId = $bySaleId[$orderId][QGetOrders::A_PARENT_ID];
                $this->daoLogCust->create([
                    LogCust::A_TRANS_ID => $tranId,
                    LogCust::A_CUSTOMER_ID => $custId
                ]);
            } else {
                /* log BONUS Grand On */
                $custId = $bySaleId[$orderId][QGetOrders::A_PARENT_GRAND_ID];
                $this->daoLogCust->create([
                    LogCust::A_TRANS_ID => $tranId,
                    LogCust::A_CUSTOMER_ID => $custId
                ]);
            }
        }
    }
}


<?php

namespace nadir2\core;

/**
 * This is composite class of the View (the view in a broad sense), which
 * entities may contains the atomic view units - the snippets.
 * @author Leonid Selikhov
 */
abstract class AbstractCompositeView extends AbstractView
{
    /** @var \nadir2\core\Snippet[] The snippet map. */
    protected $snippets = [];

    /**
     * It adds snippet to the view object.
     * @param string $snptName
     * @return void
     */
    public function addSnippet(string $snptName): void
    {
        $this->snippets[$snptName] = ViewFactory::createSnippet($snptName);
    }

    /**
     * It returns assigned snippet object by the name. If the name not presents,
     * then it returns the map with all View-assigned snippets.
     * @param string $snptName
     * @return \nadir2\core\Snippet|\nadir2\core\Snippet[]|null
     */
    public function getSnippet(string $snptName = '')
    {
        if (empty($snptName)) {
            return $this->snippets;
        } else {
            return isset($this->snippets[$snptName]) ? $this->snippets[$snptName]
                    : null;
        }
    }

    /**
     * The method returns the View-assigned snippet map.
     * @return \nadir2\core\Snippet[]
     */
    public function getAllSnippets(): array
    {
        return $this->getSnippet();
    }
}


<?php
namespace eMacros\Runtime\Regex;

use eMacros\Applicable;
use eMacros\Scope;
use eMacros\GenericList;
use eMacros\Symbol;

class RegexMatchAll implements Applicable {
	/**
	 * Returns the amount of matches found on the given subject
	 * Usage: (Regex::match-all "/([\d]{2})/" "34,4,12,52" _matches Regex::SET_ORDER 3)
	 * Returns: int
	 * (non-PHPdoc)
	 * @see \eMacros\Runtime\GenericFunction::apply()
	 */
	public function apply(Scope $scope, GenericList $arguments) {
		$nargs = count($arguments);

		if ($nargs < 2) throw new \BadFunctionCallException("RegexMatchAll: Function expects at least 2 parameters.");
		if ($nargs == 2) return preg_match_all($arguments[0]->evaluate($scope), $arguments[1]->evaluate($scope));
		else {
			$target = $arguments[2];
			if (!($target instanceof Symbol))
				throw new \InvalidArgumentException(sprintf("RegexMatchAll: Expected symbol as third argument but %s was found instead.", substr(strtolower(strstr(get_class($arguments[2]), '\\')), 1)));
			$ref = $target->symbol;
			if ($nargs == 3) return preg_match_all($arguments[0]->evaluate($scope), $arguments[1]->evaluate($scope), $scope->symbols[$ref]);
			elseif ($nargs == 4) return preg_match_all($arguments[0]->evaluate($scope), $arguments[1]->evaluate($scope), $scope->symbols[$ref], $arguments[3]->evaluate($scope));
			return preg_match_all($arguments[0]->evaluate($scope), $arguments[1]->evaluate($scope), $scope->symbols[$ref], $arguments[3]->evaluate($scope), $arguments[4]->evaluate($scope));
		}
	}
}
?>


<?php

namespace NettePropel2\Connection;

use Propel\Runtime\Connection\ProfilerConnectionWrapper;

class PanelConnectionWrapper extends ProfilerConnectionWrapper {

    private $statement;

    /**
     * {@inheritDoc}
     */
    public function prepare($sql, $driver_options = array()) {
        $this->statement = parent::prepare($sql, $driver_options);
        return $this->statement;
    }

    /**
     * {@inheritDoc}
     */
    public function log($msg) {
        if ($this->statement == null) {
            return;
        }
        $rowCount = $this->statement->rowCount();

        $msg = "Affected Rows: $rowCount | $msg";

        $msg = parent::log($msg);
    }

}


<?php namespace ForeverPHP\Core;

use ForeverPHP\Core\{ClassLoader, AppException, ViewException, Setup};

/**
 * Funciones comunes para las aplicaciones
 *
 * @author      Daniel Nuñez S. <dnunez@emarva.com>
 * @since       Version 0.1.0
 */

/*
 * Deberia funcionar de otra forma deberia cargar las apps y correctar con
 * App::run($app);
 * o
 * $application = new Application();
 * $application->add(new GreetCommand);
 * $application->run();
 *
 * Los import los debe hacer setup
 * y la carga de modelos y vistas
 * ademas de los contextos globales
 */
class App {
    /**
     * Nombre de la aplicación actual.
     *
     * @var string
     */
    private $appName;

    /**
     * Almacena los middlewares agregados.
     *
     * @var array
     */
    private $middlewares = array();

    /**
     * Contiene la instancia singleton de App.
     *
     * @var \ForeverPHP\Core\App
     */
    private static $instance;

    public function __construct() {}

    /**
     * Obtiene o crea la instancia singleton de App.
     *
     * @return \ForeverPHP\Core\App
     */
    public static function getInstance() {
        if (is_null(static::$instance)) {
            static::$instance = new static();
        }

        return static::$instance;
    }

    public function exists($app) {
        $apps = Settings::getInstance()->get('apps');

        if (in_array($app, $apps)) {
            return true;
        }

        return false;
    }

    private function loadOptional($optional) {
        $optionalPath = APPS_ROOT . DS . $optional . '.php';

        if (file_exists($optionalPath)) {
            require_once $optionalPath;
        }
    }

    public function load($app) {
        $this->appName = $app;

        // Carga los archivos opcionales de las apps
        $this->loadOptional('contexts');
        $this->loadOptional('middlewares');

        // Agrego los directorias al cargador de clases
        ClassLoader::addDirectories(array(
            APPS_ROOT . DS . $this->appName . DS . 'models',
            APPS_ROOT . DS . $this->appName . DS . 'views'
        ));
    }

    /**
     * Valida si existe un middleware.
     *
     * @param  string $name
     * @return bool
     */
    public function existsMiddleware($name) {
        if (array_key_exists($name, $this->middlewares)) {
            return true;
        }

        return false;
    }

    /**
     * Agrega un middleware.
     *
     * @param string $name
     * @param clousure
     * @return boolean
     */
    public function setMiddleware($name, $function) {
        if (!is_callable($function)) {
            return false;
        }

        $this->middlewares[$name] = $function;
    }

    /**
     * Ejecuta un middleware.
     *
     * @param  string $name
     * @param  array  $arguments
     * @return mixed
     */
    public function getMiddleware($name, $arguments = null) {
        if ($this->existsMiddleware($name)) {
            return $this->middlewares[$name]();
        }

        return false;
    }

    private function makeResponse($response) {
        /*
         * Valida si el valor de retorno de la funcion, es un objeto que
         * implemente ResponseInterface
         */
        if ($response instanceof \ForeverPHP\Http\ResponseInterface) {
            $response->make();
        }
    }

    /**
     * Ejecuta la vista solicitada.
     *
     * @param  mixed $route
     * @return void
     */
    public function run($route) {
        if (!is_array($route)) {
            $this->makeResponse($route);
        }

        // Se separa la vista por ".", si es que la vista esta en subcarpetas
        // NOTA: En ForeverPHP los niveles de directorios se separan por "."
        $viewSegments = explode('.', $route['view']);

        // Nombre del metodo a ejecutar
        $method = $route['method'];

        Setup::toDefine('TEMPLATES_PATH', APPS_ROOT . DS . $this->appName . DS . 'Templates' . DS);
        Setup::toDefine('STATIC_PATH', APPS_ROOT . DS . 'static' . DS);

        $viewPath = '';
        $view = $viewSegments[0];

        if (count($viewSegments) > 1) {
            $view = $viewSegments[count($viewSegments) - 1];

            // Se elimina el ultimo segmento de la vista, que es el nombre del archivo vista
            array_pop($viewSegments);

            // Se unen los segmentos de la vista con el separador de nombres de espacio
            $viewPath = implode('\\', $viewSegments);
            $viewPath .= '\\';
        }

        // Verifico que la vista hereda de View
        if ($view instanceof \ForeverPHP\View\View) {
            throw new ViewException("La vista ($view) no hereda de View.");
        }

        // Creo la vista y la ejecuto y le asigno el request a la vista para manipulacion interna
        if (Settings::getInstance()->get('usingNamespaces')) {
            $view = '\\Apps\\' . $this->appName . '\\Views\\' . $viewPath . $view;
        }

        $v = new $view();

        // Ejecuta la funcion y almacena su valor de retorno
        $returnValue = $v->$method();

        // Se construye la respuesta
        $this->makeResponse($returnValue);
    }

    /**
     * Retorna el nombre de la aplicación actual.
     *
     * @return string
     */
    public function getAppName() {
        return $this->appName;
    }

    /**
     * Importa una vista de aplicación en ejecución o una externa.
     *
     * @param  string $view
     * @param  string $appName
     */
    public function importView($view, $appName = null) {
        $appName = ($appName === null) ? $this->appName : $appName;
        $importPath = APPS_ROOT . DS . $appName . DS . 'views' . DS . $view . '.php';

        if (file_exists($importPath)) {
            include_once $importPath;
        } else {
            throw new AppException("The object to import ($view) not exists.");
        }
    }
}


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

use Knp\Menu\MenuItem as BaseItem;

/**
 * MenuItem
 *
 * @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
 */
class MenuItem extends BaseItem
{
    protected $translationDomain = null;
    protected $displayLink = true;
    protected $displayLabel = true;
    protected $nbDividers = 0;

    /**
     * Gets TranslationDomain
     *
     * @return [type]
     */
    public function getTranslationDomain()
    {
        return $this->translationDomain;
    }

    /**
     * Sets TranslationDomain
     *
     * @param [type] $translationDomain TranslationDomain
     *
     * @return [type]
     */
    public function setTranslationDomain($translationDomain)
    {
        $this->translationDomain = $translationDomain;
        return $this;
    }

    /**
     * Gets DisplayLink
     *
     * @return [type]
     */
    public function isLinkDisplayed()
    {
        return $this->displayLink;
    }

    /**
     * Sets DisplayLink
     *
     * @param [type] $displayLink DisplayLink
     *
     * @return [type]
     */
    public function setDisplayLink($displayLink)
    {
        $this->displayLink = $displayLink;
        return $this;
    }

    /**
     * Gets DisplayLabel
     *
     * @return [type]
     */
    public function isLabelDisplayed()
    {
        return $this->displayLabel;
    }

    /**
     * Sets DisplayLabel
     *
     * @param [type] $displayLabel DisplayLabel
     *
     * @return [type]
     */
    public function setDisplayLabel($displayLabel)
    {
        $this->displayLabel = $displayLabel;
        return $this;
    }

    /**
     * Add a divider
     *
     * @return VinceT\AdminBundle\Menu\MenuItem
     */
    public function addDivider()
    {
        $name = $this->getName().'_divider_'.$this->nbDividers;
        $child = $this->factory->createItem($name);

        $child->setParent($this);
        $child->setCurrentUri($this->getCurrentUri());

        $child->setChildrenAttribute('class', 'divider');
        $child->setDisplayLink(false);
        $child->setDisplayLabel(false);

        $this->children[$child->getName()] = $child;

        $this->nbDividers++;
        return $child;
    }

    /**
     * Add a divider
     *
     * @param string $name Nav header label
     *
     * @return VinceT\AdminBundle\Menu\MenuItem
     */
    public function addNavHeader($name)
    {
        $child = $this->factory->createItem($name);

        $child->setParent($this);
        $child->setCurrentUri($this->getCurrentUri());

        $child->setChildrenAttribute('class', 'nav-header');
        $child->setDisplayLink(false);

        $this->children[$child->getName()] = $child;

        return $child;
    }

    /**
     * Remove and return a menu
     *
     * @param string $name [description]
     *
     * @return VinceT\AdminBundle\Menu\MenuItem
     */
    public function pop($name)
    {
        $menu = $this[$name];
        $this->removeChild($name);
        return $menu;
    }

}


<?php
namespace eMacros\Runtime\Type;

use eMacros\Runtime\GenericFunction;

class IsType extends GenericFunction {
	/**
	 * Callback to invoke
	 * @var callable
	 */
	public $callback;

	public function __construct($callback) {
		$this->callback = $callback;
	}

	/**
	 * Determines if a value is of a given type
	 * Usage: (integer? 'hey') (string? _val) (null? _val1 _val2)
	 * Returns: boolean
	 * (non-PHPdoc)
	 * @see \eMacros\Runtime\GenericFunction::execute()
	 */
	public function execute(array $arguments) {
		//check number of parameters
		if (empty($arguments)) throw new \BadFunctionCallException("IsType: No arguments found.");

		foreach ($arguments as $arg) {
			if (call_user_func($this->callback, $arg) === false) return false;
		}

		return true;
	}
}
?>


<?php
/**
 * BSD 3-Clause License
 *
 * Copyright (c) 2019, TASoft Applications
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 *
 *  Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 *  Neither the name of the copyright holder nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

namespace Skyline\Compiler\Predef;

use Generator;
use Skyline\Compiler\AbstractCompiler;
use Skyline\Compiler\CompilerConfiguration as CC;
use Skyline\Compiler\CompilerConfiguration;
use Skyline\Compiler\CompilerContext;
use Skyline\Compiler\Context\Logger\LoggerInterface;
use Skyline\Compiler\Project\Attribute\SearchPathAttribute;
use TASoft\Config\Compiler\BadSourceException;
use TASoft\Config\Compiler\Source\FileSource;
use TASoft\Config\Compiler\Source\SourceContainer;
use TASoft\Config\Compiler\StandardCompiler;
use Traversable;

class ConfigurationCompiler extends AbstractCompiler
{
    private $info;

    const INFO_TARGET_FILENAME_KEY = 'target';
    const INFO_PATTERN_KEY = 'pattern';
    const INFO_CUSTOM_FILENAME_KEY = 'default';
    const INFO_DEV_FILENAME_KEY = 'dev';
    const INFO_TEST_FILENAME_KEY = 'test';

    public function compile(CompilerContext $context)
    {
        $sourceContainer = new SourceContainer();

        $addFile = function($file) use ($sourceContainer, $context) {
            if(is_file($file)) {
                $context->getLogger()->logText("Source for %s found: %s", LoggerInterface::VERBOSITY_VERY_VERBOSE, NULL, $this->getCompilerID(), $file);

                try {
                    $sourceContainer->addSource(new FileSource($file));
                } catch (BadSourceException $e) {
                    $context->getLogger()->logWarning("Source Error: %s", NULL, $e->getMessage());
                }
            } else {
                $context->getLogger()->logWarning("Source not found: %s", NULL, $file);
            }
        };

        foreach($this->yieldConfigurationFiles($context) as $file) {
            $file = (string) $file;
            $addFile($file);
        }

        if($defaultFile = $this->info[ static::INFO_CUSTOM_FILENAME_KEY ] ?? NULL) {
            foreach($context->getProjectSearchPaths(SearchPathAttribute::SEARCH_PATH_USER_CONFIG) as $configPath) {
                if(is_file($f = "$configPath/$defaultFile")) {
                    $context->getLogger()->logText("DEFAULT for %s: %s", LoggerInterface::VERBOSITY_VERY_VERBOSE, NULL, $this->getCompilerID(), $f);
                    $addFile($f);
                    break;
                }
            }
        }

        if(CC::get($context->getConfiguration(), CC::COMPILER_DEBUG) && ($defaultFile = $this->info[ static::INFO_DEV_FILENAME_KEY ] ?? NULL)) {
            foreach($context->getProjectSearchPaths(SearchPathAttribute::SEARCH_PATH_USER_CONFIG) as $configPath) {
                if(is_file($f = "$configPath/$defaultFile")) {
                    $context->getLogger()->logText("DEV for %s: %s", LoggerInterface::VERBOSITY_VERY_VERBOSE, NULL, $this->getCompilerID(), $f);
                    $addFile($f);
                    break;
                }
            }
        }

        if(CC::get($context->getConfiguration(), CC::COMPILER_TEST) && ($defaultFile = $this->info[ static::INFO_TEST_FILENAME_KEY ] ?? NULL)) {
            foreach($context->getProjectSearchPaths(SearchPathAttribute::SEARCH_PATH_USER_CONFIG) as $configPath) {
                if(is_file($f = "$configPath/$defaultFile")) {
                    $context->getLogger()->logText("TEST for %s: %s", LoggerInterface::VERBOSITY_VERY_VERBOSE, NULL, $this->getCompilerID(), $f);
                    $addFile($f);
                    break;
                }
            }
        }

        $target = $this->info[ static::INFO_TARGET_FILENAME_KEY ];
        $cdir = $context->getSkylineAppDirectory(CompilerConfiguration::SKYLINE_DIR_COMPILED);

        $this->compileConfiguration($sourceContainer, "$cdir/$target", $context);
    }

    /**
     * Compile the configuration now
     *
     * @param Traversable $source
     * @param string $target
     * @param CompilerContext $context
     */
    protected function compileConfiguration(Traversable $source, string $target, CompilerContext $context) {
        $compiler = new StandardCompiler();
        $compiler->setSource($source);

        $compiler->setTarget($target);
        $compiler->compile();
    }

    /**
     * Override to adjust configuration files and order
     *
     * @param CompilerContext $context
     * @return Generator
     */
    protected function yieldConfigurationFiles(CompilerContext $context): Generator{
        $configDirs = [];
        foreach($context->getProjectSearchPaths(SearchPathAttribute::SEARCH_PATH_USER_CONFIG) as $configDir) {
            $configDirs[] = (string)$configDir;
        }

        $pattern = $this->info[ static::INFO_PATTERN_KEY ];
        $defaultFile = $this->info[ static::INFO_CUSTOM_FILENAME_KEY ] ?? NULL;

        foreach($context->getSourceCodeManager()->yieldSourceFiles($pattern, $configDirs) as $fileName => $file) {
            if(basename($fileName) == $defaultFile)
                continue;

            yield $fileName => $file;
        }
    }

    /**
     * ConfigurationCompiler constructor.
     * @param string $compilerID
     * @param $info
     */
    public function __construct(string $compilerID, $info)
    {
        parent::__construct($compilerID);
        $this->info = $info;
    }
}


<?php
/*
 * Resources class
 * Handles all css and javascript resources
 */
namespace FelixOnline\Base;

use FelixOnline\Exceptions\InternalException;

use Assetic\Asset\AssetCollection;
use Assetic\Asset\FileAsset;
use Assetic\Asset\GlobAsset;
use Assetic\Filter\LessphpFilter;
use Assetic\Filter\ScssphpFilter;
use Assetic\Filter\CssMinFilter;
use Assetic\Filter\JSqueezeFilter;

class ResourceManager
{
    private $css; // array of css files
    private $js; // array of js files
    private $theme;

    public function __construct(Theme $theme, $css = false, $js = false)
    {
        $this->theme = $theme;

        if ($css) {
            $this->addCSS($css);
        }
        if ($js) {
            $this->addJS($js);
        }
        $this->css = array();
        $this->js = array();
    }

    /*
     * Public: Add css files
     *
     * $css - array of css files to load
     *
     * Returns css array
     */
    public function addCSS($css)
    {
        if (is_array($css)) {
            foreach ($css as $key => $value) {
                if ($this->isLess($css)) {
                    $this->css[] = new FileAsset($css, array(LessphpFilter));
                } elseif ($this->isScss($css)) {
                    $this->css[] = new FileAsset($css, array(ScssphpFilter));
                } else {
                    $this->css[] = new FileAsset($css);
                }
            }
            return $this;
        } else {
            throw new InternalException("CSS files to add is not an array");
        }
    }

    /*
     * Public: Add js files
     *
     * $js - array of js files to load
     *
     * Returns js array
     */
    public function addJS($js)
    {
        if (is_array($js)) {
            foreach ($js as $key => $value) {
                $this->js[] = new FileAsset($js);
            }
            return $this;
        } else {
            throw new InternalException("JS files to add is not an array");
        }
    }

    /*
     * Public: Replace css files
     */
    public function replaceCSS($css)
    {
        if (is_array($css)) {
            $this->css = array();
            return $this->addCSS($css);
        } else {
            throw new InternalException("CSS files to add is not an array");
        }
    }

    /*
     * Public: Replace js files
     */
    public function replaceJS($js)
    {
        if (is_array($js)) {
            $this->js = array();
            return $this->addJS($js);
        } else {
            throw new InternalException("JS files to add is not an array");
        }
    }

    /*
     * Public: Get built css files
     *
     * Returns css file path
     */
    public function getCSS()
    {
        return $this->build($this->css, 'css');
    }

    /*
     * Public: Get js files
     *
     * Returns array of js files paths
     */
    public function getJS()
    {
        // Strip out externals
        $js = array();
        $jsExt = array();

        foreach ($this->js as $jsItem) {
            if ($this->isExternal($jsItem)) {
                $jsExt[] = $jsItem;
            } else {
                $js[] = $jsItem;
            }
        }

        return array_merge($this->build($js, 'js'), $jsExt);
    }

    /*
     * Check if file is external
     */
    private function isExternal($file)
    {
        if (strpos($file, 'http://') !== false
        || strpos($file, 'https://') !== false) {
            return true;
        } else {
            return false;
        }
    }

    /*
     * Build data
     */
    private function build($data, $type)
    {
        if ($type != 'css' && $type != 'js') {
            throw new InternalException('Trying to build invalid type');
        }

        if ($type == 'css') {
            $fileName = $this->getFilename('built.css', 'css', 'dir');
            $fileName2 = $this->getFilename('built.css', 'css');

            $filter = new CssMinFilter();
        } else {
            $fileName = $this->getFilename('built.css', 'js', 'dir');
            $fileName2 = $this->getFilename('built.css', 'js');

            $filter = new JSqueezeFilter();
        }

        if (PRODUCTION_FLAG == true) { // if in production
            $data = new AssetCollection($data, array($filter));
        } else {
            $data = new AssetCollection($data);
        }

        // Abstract out
        if (
            (
                PRODUCTION_FLAG == true &&
                !file_exists($fileName) &&
                // Age
                true
            ) || PRODUCTION_FLAG == false
        ) {
            $css = $css->dump();

            if (!is_writable($fileName)) {
                throw new InternalException('The file '.$fileName.', or the folder it is in, is not writable.');
            }

            file_put_contents($fileName, $content);
        }

        return $fileName2;
    }

    /*
     * Get path to file
     */
    private function getFilename($file, $type, $version = 'url')
    {
        if ($version == 'url') {
            $root = $this->theme->getURL();
        } elseif ($version == 'dir') {
            $root = $this->theme->getDirectory();
        }
        switch ($type) {
            case 'css':
                return $root.'/css'.$file;
                break;
            case 'js':
                return $root.'/js'.$file;
                break;
        }
    }

    /*
     * If file is a less file
     */
    private function isLess($file)
    {
        if (substr(strrchr($file, '.'), 1) == 'less') {
            return true;
        } else {
            return false;
        }
    }

    /*
     * If file is a less file
     */
    private function isScss($file)
    {
        if (substr(strrchr($file, '.'), 1) == 'scss') {
            return true;
        } else {
            return false;
        }
    }
}


<?php

namespace Phapi\Middleware\Mistake;

use Phapi\Contract\Di\Container;
use Phapi\Contract\Middleware\ErrorMiddleware;
use Phapi\Exception;
use Phapi\Exception\InternalServerError;
use Zend\Diactoros\Stream;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface as RequestInterface;

/**
 * Mistake Middleware
 *
 * The Mistake middleware handles errors and exceptions and makes
 * sure that the middleware pipeline is reset to only execute the
 * needed middleware for sending the response to the client.
 *
 * Before that is done the error and exception is logged using the
 * configured logger.
 *
 * @category Phapi
 * @package  Phapi\Middleware\Mistake
 * @author   Peter Ahinko <peter@ahinko.se>
 * @license  MIT (http://opensource.org/licenses/MIT)
 * @link     https://github.com/phapi/middleware-mistake
 */
class Mistake implements ErrorMiddleware
{

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

    /**
     * List of fatal errors
     *
     * @var int
     */
    private $fatalErrors;

    /**
     * Should errors be displayed?
     *
     * @var bool
     */
    private $displayErrors = false;

    /**
     * Array of status codes that should
     * be excluded from logging
     *
     * @var array
     */
    private $doNotLog;

    /**
     * Construct the mistake middleware
     *
     * @param bool|false $displayErrors
     * @param array $doNotLog Array of status codes that should be excluded from logging
     */
    public function __construct($displayErrors = false, array $doNotLog = [])
    {
        $this->displayErrors = $displayErrors;
        $this->doNotLog = $doNotLog;

        // Register handlers
        $this->register();

        $this->fatalErrors = E_ERROR | E_USER_ERROR | E_COMPILE_ERROR | E_CORE_ERROR | E_PARSE;
    }

    /**
     * Register error, exception and shutdown handlers
     */
    private function register()
    {
        // Don't display any errors since we want this error handler to handle all
        // errors. Error messages sent to the client will be serialized.
        ini_set('display_errors', false);

        // In development however it is beneficiary to display errors.
        if ($this->displayErrors) {
            ini_set('display_errors', true);
        }

        // Register handlers
        register_shutdown_function([$this, 'shutdownHandler']);
        set_error_handler([$this, 'errorHandler']);
        set_exception_handler([$this, 'exceptionHandler']);
    }

    /**
     * Catch errors in the shutdown process
     */
    public function shutdownHandler()
    {
        $error = error_get_last();
        if ($error && $error['type'] & $this->fatalErrors) {
            $this->errorHandler(
                $error['type'],
                $error['message'],
                $error['file'],
                $error['line']
            );
        }
    }

    /**
     * Set a custom error handler to make sure that errors are logged.
     * Allows any non-fatal errors to be logged.
     *
     * @param $errno
     * @param $errstr
     * @param $errfile
     * @param $errline
     * @param array $errcontext
     * @throws \RuntimeException always when an error occurred to trigger the exception handler
     */
    public function errorHandler($errno, $errstr, $errfile, $errline, array $errcontext = [])
    {
        $codes = array(
            256   => 'E_USER_ERROR',
            512   => 'E_USER_WARNING',
            1024  => 'E_USER_NOTICE',
            2048  => 'E_STRICT',
            4096  => 'E_RECOVERABLE_ERROR',
            8192  => 'E_DEPRECATED',
            16384 => 'E_USER_DEPRECATED',
            8     => 'E_NOTICE',
            2     => 'E_WARNING'
        );

        $message = 'Error of level ';
        if (array_key_exists($errno, $codes)) {
            $message .= $codes[$errno];
        } else {
            $message .= sprintf('Unknown error level, code of %d passed', $errno);
        }

        $message .= sprintf(
            '. Error message was "%s" in file %s at line %d.',
            $errstr,
            $errfile,
            $errline
        );

        // Log message
        $this->container['log']->error($message, $errcontext);
        $this->exceptionHandler(new InternalServerError('An unexpected error occurred.'));
    }

    /**
     * Handle thrown and uncaught exceptions thrown in the middleware
     * queue. The exception handler is registered when this Mistake
     * middleware is created. Any exceptions thrown before that won't
     * be caught by this handler.
     *
     * @param $exception
     */
    public function exceptionHandler($exception)
    {
        // Try and get the latest request, or a new request
        $request =
            (isset($this->container['latestRequest']) ?
                $this->container['latestRequest'] : $this->container['request']);

        // Try and get the latest response, or a new response
        $response =
            (isset($this->container['latestResponse']) ?
                $this->container['latestResponse'] : $this->container['response']);

        // Check if exception is an instance of the Phapi Exception. If not, create
        // an InternalServerError Exception to get better error message to send to
        // the client. This will also catch PHP 7 ErrorExceptions
        if (!($exception instanceof Exception)) {
            $exception = new InternalServerError(
                $exception->getMessage(),
                $exception->getCode(),
                $exception->getPrevious()
            );
        }

        // Add to log
        $this->logException($exception);

        // Prepare response with updated body (error message)
        // Reset body
        $response = $response->withBody(new Stream('php://memory', 'w+'));
        // Set status code
        $response = $response->withStatus($exception->getStatusCode());
        // Set error message
        $body = $this->prepareErrorBody($exception);

        // Set body to response
        $response = $response->withUnserializedBody($body);

        // Restart pipeline
        $this->container['pipeline']->prepareErrorQueue();
        $this->container['pipeline']($request, $response);
    }

    /**
     * Create a log entry about the error exception
     *
     * @param Exception $exception
     */
    private function logException(Exception $exception)
    {
        // Check if the error message should be logged or not
        if (in_array($exception->getStatusCode(), $this->doNotLog)) {
            return;
        }

        // Prepare log message
        $message = sprintf(
            'Uncaught exception of type %s thrown in file %s at line %s%s.',
            get_class($exception),
            $exception->getFile(),
            $exception->getLine(),
            $exception->getMessage() ? sprintf(' with message "%s"', $exception->getMessage()) : ''
        );
        // Log error
        $this->container['log']->error($message, array(
            'exception' => $exception,
            'Exception message'  => $message,
            'Exception line'  => $exception->getLine(),
            'Exception trace' => $exception->getTraceAsString(),
        ));
    }

    /**
     * Takes an Error Exception and gets the available error information
     * and creates a body of it and returns the body.
     *
     * @param Exception $exception
     * @return array
     */
    private function prepareErrorBody(Exception $exception)
    {
        // Prepare body
        $body = [ 'errors' => [] ];

        // Set HTTP status code
        if (!empty($statusCode = $exception->getStatusCode())) {
            $body['errors']['statusCode'] = $statusCode;
        }

        // Check if a description exists
        if (!empty($description = $exception->getDescription())) {
            $body['errors']['description'] = $description;
        }

        // Check if a message has been defined
        if (!empty($message = $exception->getMessage())) {
            $body['errors']['message'] = $message;
        }

        // Check if an error code has been defined
        if (!empty($code = $exception->getCode())) {
            $body['errors']['code'] = $code;
        }

        // Check if a link has been specified
        if (!empty($link = $exception->getLink())) {
            $body['errors']['link'] = $link;
        }

        return $body;
    }

    /**
     * Set dependency injection container
     *
     * @param Container $container
     */
    public function setContainer(Container $container)
    {
        $this->container = $container;
    }

    /**
     * Handle the middleware pipeline call.
     *
     * Does not do much, just calls next middleware and returns
     * the response.
     *
     * @param RequestInterface $request
     * @param ResponseInterface $response
     * @param callable $next
     * @return ResponseInterface
     */
    public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next = null)
    {
        $response = $next($request, $response, $next);

        return $response;
    }
}


<?php

namespace Versatile\Search;

use Versatile\Search\Contracts\Search;
use Versatile\Search\Contracts\Criteria as CriteriaContract;
use Versatile\Search\Contracts\Queryable;
use Versatile\Search\Contracts\Sortable;
use Versatile\Search\Contracts\Filter as FilterContract;
use Versatile\Query\Builder;

class BuilderSearch implements Search
{

    use ProvidesKeyInterface;
    use ForwardsToCriteria;

    protected $builder;

    protected $queryListener;

    protected $wasBuilded = false;

    public function __construct(Builder $builder, CriteriaContract $criteria)
    {
        $this->builder = $builder;
        $this->criteria = $criteria;
        $this->queryListener = function($query){};
    }

    /**
     * Get the complete result without pagination
     *
     * @param $keys (optional)
     * @return \Traversable
     **/
    public function get($keys=[])
    {
        $this->buildIfNotBuilded();
        $keys = $keys == [] ? $this->keys() : $keys;

        if (!$keys) {
            return $this->builder->get();
        }

        return $this->builder->withColumns($keys)->get($keys);
    }

    /**
     * Get the paginated result
     *
     * @param array $keys (optional)
     * @param $perPage (optional)
     * @return \Traversable
     **/
    public function paginate($keys=[], $perPage = null)
    {
        $this->buildIfNotBuilded();
        $keys = $keys == [] ? $this->keys() : $keys;

        if (!$keys) {
            return $this->builder->paginate($perPage);
        }

        return $this->builder->withColumns($keys)->paginate($perPage);

    }

    public function onBuilding(callable $listener)
    {
        $this->queryListener = $listener;
        return $this;
    }

    protected function buildIfNotBuilded()
    {
        if ($this->wasBuilded) {
            return;
        }

        call_user_func($this->queryListener, $this->builder);

        $this->appendWheresToBuilder();
        $this->appendSortingToBuilder();
    }

    protected function appendWheresToBuilder()
    {
        foreach ($this->criteria->filter() as $expression) {
            $this->builder->where(
                $expression->key(),
                $expression->operator(),
                $expression->value(),
                $expression->bool()
            );
        }
    }

    protected function appendSortingToBuilder()
    {
        foreach ($this->criteria->sorting() as $key=>$direction) {
            if (trim($key) != '') {
                $this->builder->orderBy($key, $direction);
            }
        }
    }
}


<?php

namespace carlosV2\DumbsmartRepositoriesBundle\Configurer;

use carlosV2\DumbsmartRepositories\Exception\MetadataNotFoundException;
use carlosV2\DumbsmartRepositories\Exception\RepositoryNotFoundException;
use carlosV2\DumbsmartRepositories\MetadataManager;
use carlosV2\DumbsmartRepositories\RepositoryManager;
use carlosV2\DumbsmartRepositoriesBundle\Metadata\DoctrineMetadataFactory;
use carlosV2\DumbsmartRepositoriesBundle\ObjectIdentifier\AliasedObjectIdentifier;
use carlosV2\DumbsmartRepositoriesBundle\ObjectIdentifier\ObjectIdentifierFactory;
use carlosV2\DumbsmartRepositoriesBundle\Repository\RepositoryFactory;
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
use Doctrine\Common\Persistence\Mapping\ClassMetadataFactory;

class DoctrineConfigurer
{
    /**
     * @var MetadataManager
     */
    private $mm;

    /**
     * @var RepositoryManager
     */
    private $rm;

    /**
     * @var ObjectIdentifierFactory
     */
    private $oif;

    /**
     * @var DoctrineMetadataFactory
     */
    private $dmf;

    /**
     * @var RepositoryFactory
     */
    private $rf;

    /**
     * @param MetadataManager         $mm
     * @param RepositoryManager       $rm
     * @param ObjectIdentifierFactory $oif
     * @param DoctrineMetadataFactory $dmf
     * @param RepositoryFactory       $rf
     */
    public function __construct(
        MetadataManager $mm,
        RepositoryManager $rm,
        ObjectIdentifierFactory $oif,
        DoctrineMetadataFactory $dmf,
        RepositoryFactory $rf
    ) {
        $this->mm = $mm;
        $this->rm = $rm;
        $this->oif = $oif;
        $this->dmf = $dmf;
        $this->rf = $rf;
    }

    /**
     * @param ClassMetadataFactory $factory
     */
    public function configure(ClassMetadataFactory $factory)
    {
        foreach ($factory->getAllMetadata() as $metadata) {
            $className = $metadata->getName();
            $parentClassName = $this->getParentClassName($metadata);
            $identifier = new AliasedObjectIdentifier(
                $className,
                $this->oif->createDoctrineObjectIdentifier($metadata)
            );

            try {
                $this->mm->getMetadataForClassName($className);
            } catch (MetadataNotFoundException $e) {
                $this->mm->addMetadata($className, $this->dmf->createMetadata($metadata, $identifier));
            }

            if ($className === $parentClassName) {
                try {
                    $repository = $this->rm->getRepositoryForClassName($className);
                } catch (RepositoryNotFoundException $e) {
                    $repository = $this->rf->createRepository($metadata->getName(), $identifier);
                }
            } else {
                try {
                    $repository = $this->rm->getRepositoryForClassName($parentClassName);
                } catch (RepositoryNotFoundException $e) {
                    $repository = $this->rf->createRepository(
                        $factory->getMetadataFor($parentClassName)->getName(),
                        $identifier
                    );
                }
                $this->rm->addRepository($parentClassName, $repository);
            }

            $this->rm->addRepository($className, $repository);
        }
    }

    /**
     * @param ClassMetadata $metadata
     *
     * @return string
     */
    private function getParentClassName(ClassMetadata $metadata)
    {
        // So far only single inheritance is supported
        if (count($metadata->parentClasses) > 0) {
            return $metadata->parentClasses[0];
        }

        return $metadata->getName();
    }
}


<?php

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

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

namespace EasyWeChat\Core;

use EasyWeChat\Core\Exceptions\HttpException;
use EasyWeChat\Support\Collection;
use EasyWeChat\Support\Log;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Uri;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

/**
 * Class AbstractAPI.
 */
abstract class AbstractAPI
{
    /**
     * Http instance.
     *
     * @var \EasyWeChat\Core\Http
     */
    protected $http;

    /**
     * The request token.
     *
     * @var \EasyWeChat\Core\AccessToken
     */
    protected $accessToken;

    const GET = 'get';
    const POST = 'post';
    const JSON = 'json';

    /**
     * @var int
     */
    protected static $maxRetries = 2;

    /**
     * Constructor.
     *
     * @param \EasyWeChat\Core\AccessToken $accessToken
     */
    public function __construct(AccessToken $accessToken)
    {
        $this->setAccessToken($accessToken);
    }

    /**
     * Return the http instance.
     *
     * @return \EasyWeChat\Core\Http
     */
    public function getHttp()
    {
        if (is_null($this->http)) {
            $this->http = new Http();
        }

        if (count($this->http->getMiddlewares()) === 0) {
            $this->registerHttpMiddlewares();
        }

        return $this->http;
    }

    /**
     * Set the http instance.
     *
     * @param \EasyWeChat\Core\Http $http
     *
     * @return $this
     */
    public function setHttp(Http $http)
    {
        $this->http = $http;

        return $this;
    }

    /**
     * Return the current accessToken.
     *
     * @return \EasyWeChat\Core\AccessToken
     */
    public function getAccessToken()
    {
        return $this->accessToken;
    }

    /**
     * Set the request token.
     *
     * @param \EasyWeChat\Core\AccessToken $accessToken
     *
     * @return $this
     */
    public function setAccessToken(AccessToken $accessToken)
    {
        $this->accessToken = $accessToken;

        return $this;
    }

    /**
     * @param int $retries
     */
    public static function maxRetries($retries)
    {
        self::$maxRetries = abs($retries);
    }

    /**
     * Parse JSON from response and check error.
     *
     * @param string $method
     * @param array  $args
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function parseJSON($method, array $args)
    {
        $http = $this->getHttp();

        $contents = $http->parseJSON(call_user_func_array([$http, $method], $args));

        //$this->checkAndThrow($contents);

        return new Collection($contents);
    }

    /**
     * Register Guzzle middlewares.
     */
    protected function registerHttpMiddlewares()
    {
        // log
        $this->http->addMiddleware($this->logMiddleware());
        // retry
        $this->http->addMiddleware($this->retryMiddleware());
        // access token
        $this->http->addMiddleware($this->accessTokenMiddleware());
    }

    /**
     * Attache access token to request query.
     *
     * @return \Closure
     */
    protected function accessTokenMiddleware()
    {
        return function (callable $handler) {
            return function (RequestInterface $request, array $options) use ($handler) {
                if (!$this->accessToken) {
                    return $handler($request, $options);
                }

                $field = $this->accessToken->getQueryName();
                $token = $this->accessToken->getToken();

                $request = $request->withUri(Uri::withQueryValue($request->getUri(), $field, $token));

                return $handler($request, $options);
            };
        };
    }

    /**
     * Log the request.
     *
     * @return \Closure
     */
    protected function logMiddleware()
    {
        return Middleware::tap(function (RequestInterface $request, $options) {
            Log::debug("Request: {$request->getMethod()} {$request->getUri()} ".json_encode($options));
            Log::debug('Request headers:'.json_encode($request->getHeaders()));
        });
    }

    /**
     * Return retry middleware.
     *
     * @return \Closure
     */
    protected function retryMiddleware()
    {
        return Middleware::retry(function (
                                          $retries,
                                          RequestInterface $request,
                                          ResponseInterface $response = null
                                       ) {
            // Limit the number of retries to 2
            if ($retries <= self::$maxRetries && $response && $body = $response->getBody()) {
                // Retry on server errors
                if (stripos($body, 'errcode') && (stripos($body, '40001') || stripos($body, '42001'))) {
                    $field = $this->accessToken->getQueryName();
                    $token = $this->accessToken->getToken(true);

                    $request = $request->withUri($newUri = Uri::withQueryValue($request->getUri(), $field, $token));

                    Log::debug("Retry with Request Token: {$token}");
                    Log::debug("Retry with Request Uri: {$newUri}");

                    return true;
                }
            }

            return false;
        });
    }

    /**
     * Check the array data errors, and Throw exception when the contents contains error.
     *
     * @param array $contents
     *
     * @throws \EasyWeChat\Core\Exceptions\HttpException
     */
    protected function checkAndThrow(array $contents)
    {
        if (isset($contents['errcode']) && 0 !== $contents['errcode']) {
            if (empty($contents['errmsg'])) {
                $contents['errmsg'] = 'Unknown';
            }

            throw new HttpException($contents['errmsg'], $contents['errcode']);
        }
    }
}


<?php
/**
 *  OpenLSS - Lighter Smarter Simpler
 *
 *	This file is part of OpenLSS.
 *
 *	OpenLSS is free software: you can redistribute it and/or modify
 *	it under the terms of the GNU Lesser General Public License as
 *	published by the Free Software Foundation, either version 3 of
 *	the License, or (at your option) any later version.
 *
 *	OpenLSS 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 Lesser General Public License for more details.
 *
 *	You should have received a copy of the
 *	GNU Lesser General Public License along with OpenLSS.
 *	If not, see <http://www.gnu.org/licenses/>.
 */
namespace LSS;

use \Exception;
use \PHPTAL;
use \tidy;

class Tpl {

	//output handling
	const OUTPUT_DIRECT = true;
	const OUTPUT_RETURN = false;

	//instance for singleton
	static $inst = false;

	//tpl environment
	public $path = 'theme';
	public $uri = '';
	public $body = null;
	public $init = false;
	public $tpl_file_ext = '.xhtml';

	//globals
	protected $constants = array();
	protected $debug = array();
	protected $css = null;
	protected $js = null;
	protected $stub = array();

	//singleton access
	public static function _get(){
		if(self::$inst === false){
			$class = __CLASS__;
			self::$inst = new $class();
		}
		return self::$inst;
	}

	//--------------------------------------------------------
	//Environment Modifiers
	//--------------------------------------------------------
	public function setPath($value){
		$this->path = $value;
		return $this;
	}

	public function setUri($value){
		if(strrpos($value,'/') !== (strlen($value)-1)) $value .= '/';
		$this->uri = $value;
		$this->initTheme();
		return $this;
	}

	//--------------------------------------------------------
	//Javascript and CSS Handlers
	//--------------------------------------------------------
	public function addCss($file,$media='screen'){
		return $this->css .= sprintf(
			 "\t<link type=\"text/css\" rel=\"stylesheet\" href=\"%s\" media=\"%s\" />\n"
			,$file
			,$media
		);
	}

	public function resetCss(){
		$this->css = null;
		return true;
	}

	public function addJs($file){
		return $this->js .= sprintf("\t<script type=\"text/javascript\" src=\"%s\"></script>\n",$file);
	}

	public function resetJs(){
		$this->js = null;
		return true;
	}

	//--------------------------------------------------------
	//Constant Handling
	//--------------------------------------------------------
	public function set($name,$value=null,$overwrite=true){
		if(is_array($name)){
			$overwrite = $value;
			foreach($name as $key => $val) $this->set($key,$val,$overwrite);
			return true;
		}
		if(isset($this->constants[$name]) && $overwrite === false) return false;
		$this->constants[$name] = $value;
		return true;
	}

	public function get($name){
		if(is_null($name)) return $this->constants;
		if(!isset($this->constants[$name])) return null;
		return $this->constants[$name];
	}

	//--------------------------------------------------------
	//Direct body functions
	//--------------------------------------------------------
	public function add($html){
		return $this->body .= $html;
	}

	public function reset(){
		$this->body = '';
		return $this;
	}

	public function setStub($name,$value=true){
		$this->stub[$name] = ($value)?true:false;
		return $this;
	}

	//--------------------------------------------------------
	//Debug handling
	//--------------------------------------------------------
	public function addDebug($value){
		$bt = debug_backtrace();
		//false or null become nullstring ''
		$info = sprintf('%s() at line %d in %s',$bt[1]['function'],$bt[1]['line'],$bt[1]['file']);
		$this->debug[] = array($bt[1]['function'],$bt[1]['line'],$bt[1]['file'],(($value === false) || (is_null($value))) ? '' : $value);
		unset($bt);
		return $this;
	}

	public function debug(){
		$dbg = array();
		if(count($this->debug)){
			foreach($this->debug as $d){
				$title = sprintf('%s() @ line %d: %s',$d[0],$d[1],$d[2]);
				$dbg[] = array('title'=>$title,'entry'=>$d[3],'handle'=>'dbg_'.md5($title.$d[3]));
			}
		}
		return $dbg;
	}

	//--------------------------------------------------------
	//Script Stats
	//--------------------------------------------------------
	public function stats(){
		$stats = 'Execution: '.number_format((microtime(true) - START),5);
		if(is_callable(array('Db','getQueryCount')))
			$stats .= ' | Queries: '.Db::_get()->getQueryCount();
		$stats .= ' | Memory: '.number_format((memory_get_usage()/1024/1024),2).'MB';
		return $stats;
	}

	//--------------------------------------------------------
	//Output Function
	//	This is the main output handler that calls into PHPTAL
	//	it will render the specified template file and add
	//	the passed tags to the environment
	//	it also sets up the global environment for page parsing
	//	NOTE: there should only be one call to this per
	//		page unless in extreme circumstances
	//	ARGUMENTS
	//		file	the template file to be parsed
	//		tags	array of variables to be added to env
	//		echo	when true the tpl system will output
	//					directly to the browser and exit
	//--------------------------------------------------------
	public function output($file,$tags=array(),$echo=true){
		//if there is anything in the buffer, move it to debug
		if(($content = ob_get_contents()) !== '')
			$this->addDebug('<pre>'.$content.'</pre>');
		//init template handler
		$stub_overrides = $this->stub; //backup before initTheme or requested stubs get stomped
		$this->initTheme();
		//start up template engine
		$tpl = new PHPTAL($this->getTplFile($file));
		//init the tpl (load overrides)
		$this->initTpl($tpl,$file);
		//merge stub defaults with the overrides from earlier
		$tpl->stub = $this->stub;
		//setup env for template engine
		$this->setupEnv($tpl);
		//add tags to context
		if(is_array($tags)){
			foreach($tags as $name => $val){
				//dont add invalid vars
				if(strpos($name,'_') === 0) continue;
				if(strpos($name,' ') !== false) continue;
				$tpl->$name = $val;
			}
		}
		//execute template call
		try {
			$out = $tpl->execute();
		} catch(Exception $e){
			//before we throw this upstream we want to restore
			//	the buffer and get more verbose output
			ob_clean();
			echo $content;
			throw $e;
		}
		//if we dont have the tidy extension lets just output now
		if(!extension_loaded('tidy')){
			//print output to browser / terminal
			if($echo){
				$this->reset();
				ob_end_clean();
				echo $out;
				return true;
			} else {
				$this->add($out);
				return $out;
			}
		//we do have tidy so lets do some cleanup
		} else {
			//cleanup the output
			$tidy = new tidy();
			$tidy->parseString($out,Config::get('theme','tidy'),'utf8');
			$tidy->cleanRepair();
			if($echo){
				ob_end_clean();
				echo $tidy;
				return true;
			} else {
				$this->add($tidy);
				return $tidy;
			}
		}
	}

	//--------------------------------------------------------
	//Output Helpers
	//--------------------------------------------------------
	protected function getTplFile($file,$init=false,$try_default=true){
		//figure out which file we want to find
		if($init)
			$file_ext = '.php';
		else
			$file_ext = $this->tpl_file_ext;
		//check for the override first
		$tpl_file = $this->path.'/'.$file.$file_ext;
		if(file_exists($tpl_file))
			return $tpl_file;
		if(!$try_default)
			throw new Exception('Template file doesnt exist: '.$tpl_file);
		//check the default path
		$tpl_file = dirname($this->path).'/default/'.$file.$file_ext;
		if(file_exists($tpl_file))
			return $tpl_file;
		throw new Exception('Template file doesnt exist: '.$tpl_file);
		return false;
	}

	protected function initTheme(){
		try {
			if($this->init)
				return true;
			include($this->getTplFile('init',true));
			$this->init = true;
			return true;
		} catch(Exception $e){
			return false;
		}
	}

	protected function initTpl($tpl,$file){
		try {
			include($this->getTplFile($file,true));
			return true;
		} catch(Exception $e){
			return false;
		}
	}

	protected function setupEnv($tpl){
		//setup globals
		if(!empty($this->css)) $this->set('css',$this->css);
		if(!empty($this->js)) $this->set('js',$this->js);
		//stats
		$stats = $this->stats();
		if(!empty($stats)) $this->set('stats',$stats);
		unset($stats);
		//add global urls if the lib is loaded
		if(is_callable(array('\LSS\Url','_all')))
			$tpl->url = Url::_all();
		//debug
		$debug = $this->debug();
		if(!empty($debug)){
			$this->set('debug',$debug);
			ob_start();
			var_dump($debug);
			file_put_contents('/tmp/debug',ob_get_clean());
		}
		unset($debug);
		//export globals to templating engine
		$tpl->global = $this->constants;
		return true;
	}

	//--------------------------------------------------------
	//Magic Methods
	//--------------------------------------------------------
	public function __toString(){
		return $this->body;
	}

}


<?php

namespace Bridge\Action;

use Transfer\Adapter\SingleBufferAdapter;
use Transfer\Adapter\Transaction\Request;
use Transfer\Procedure\ProcedureBuilder;
use Transfer\Processor\SequentialProcessor;

/**
 * Procedural action.
 */
class ProceduralAction extends AbstractAction
{
    /**
     * @var ProcedureBuilder
     */
    protected $builder;

    /**
     * @param string           $name    Action name
     * @param ProcedureBuilder $builder Procedure builder
     */
    public function __construct($name, ProcedureBuilder $builder = null)
    {
        parent::__construct($name);

        $this->builder = $builder;

        if ($this->builder === null) {
            $this->builder = new ProcedureBuilder();
        }
    }

    /**
     * {@inheritdoc}
     */
    public function execute(array $arguments = array())
    {
        $buffer = new SingleBufferAdapter();

        $this->builder->addTarget($buffer);

        $processor = new SequentialProcessor();
        $processor->addProcedure($this->builder->getProcedure());

        $processor->process();

        return $buffer->receive(new Request());
    }
}


<?php namespace Versatile\View;

use Versatile\View\Contracts\CollectionFactory;
use OutOfBoundsException;
use Ems\Core\Patterns\HookableTrait;

class CollectionFactoryChain implements CollectionFactory
{
    use HookableTrait;

    protected $factories = [];

    protected $booted = false;

    public function add(CollectionFactory $factory)
    {
        $this->factories[] = $factory;
        return $this;
    }

    /**
     * {@inheritdoc}
     *
     * @param mixed $searchable
     * @param array $params
     * @param string $view
     * @return \Collection\Collection
     **/
    public function create($searchable, array $params=[], $view='html')
    {
        return $this->findFactoryFor($searchable, $params, $view)
                    ->create($searchable, $params, $view);
    }

    /**
     * {@inheritdoc}
     *
     * @param mixed $searchable
     * @param array $params
     * @param string $view
     * @return \Collection\Collection
     **/
    public function paginate($searchable, array $params=[], $view='html')
    {
        return $this->findFactoryFor($searchable, $params, $view)
                    ->paginate($searchable, $params, $view);
    }

    /**
     * {@inheritdoc}
     *
     * @param mixed $searchable
     * @param array $params
     * @param string $view
     * @return bool
     **/
    public function canCreate($searchable, array $params=[], $view='html')
    {

        foreach ($this->factories as $factory) {
            if ($factory->canCreate($searchable, $params, $view)) {
                return true;
            }
        }

        return false;

    }

    protected function findFactoryFor($searchable, array $params, $view)
    {

        $this->boot();

        foreach ($this->factories as $factory) {
            if ($factory->canCreate($searchable, $params, $view)) {
                return $factory;
            }
        }

        throw new OutOfBoundsException("No factory supports this searchable");

    }

    /**
     * @param callable $factoryCreator
     * @deprecated Use $app->afterResolving()
     **/
    public function extend(callable $factoryCreator)
    {
        $this->onAfter('boot', $factoryCreator);
    }

    protected function boot()
    {
        if ($this->booted) {
            return;
        }
        $this->callBeforeListeners('boot', [$this]);
        $this->callAfterListeners('boot', [$this]);
        $this->booted = true;
    }

}


<?php

namespace OpenOrchestra\ModelBundle\EventListener;

use Doctrine\ODM\MongoDB\Event\LifecycleEventArgs;
use OpenOrchestra\ModelInterface\Model\ContentAttributeInterface;
use OpenOrchestra\ModelInterface\Model\ContentInterface;
use OpenOrchestra\ModelInterface\Model\FieldTypeInterface;
use OpenOrchestra\ModelInterface\Repository\ContentRepositoryInterface;
use OpenOrchestra\ModelInterface\Repository\ContentTypeRepositoryInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;

/**
 * Class UpdateNonTranslatableContentFieldsListener
 */
class UpdateNonTranslatableContentFieldsListener implements ContainerAwareInterface
{
    use ContainerAwareTrait;

    protected $contentManaged = array();
    protected $contentAttributeClass;
    protected $immutableData;

    /**
     * @param string $contentAttributeClass
     * @param array  $immutableData
     */
    public function __construct($contentAttributeClass, array $immutableData = array())
    {
        $this->contentAttributeClass = $contentAttributeClass;
        $this->immutableData = $immutableData;
    }

    /**
     * @param LifecycleEventArgs $event
     */
    public function preUpdate(LifecycleEventArgs $event)
    {
        if (!($object = $event->getDocument()) instanceof ContentInterface || in_array($object->getContentId(), $this->contentManaged)) {
            return;
        }

        $this->contentManaged[] = $object->getContentId();

        $contents = $this->getContentRepository()->findByContentId($object->getContentId());
        $contentType = $this->getContentTypeRepository()->findOneByContentTypeIdInLastVersion($object->getContentType());

        /** @var ContentInterface $content */
        foreach ($contents as $content) {
            if ($content != $object) {
                foreach ($this->immutableData as $immutableData) {
                    $getter = $this->generateGetter($immutableData, $object);
                    $setter = 'set' . ucfirst($immutableData);
                    $content->$setter($object->$getter());
                }
                /** @var FieldTypeInterface $field */
                foreach ($contentType->getFields() as $field) {
                    if (!$field->isTranslatable()) {
                        $contentAttribute = $this->getContentAttribute($content, $field->getFieldId());
                        $contentAttribute->setValue($object->getAttributeByName($field->getFieldId())->getValue());
                    }
                }

            }
            $event->getDocumentManager()->flush($content);
        }
    }

    /**
     * @return ContentRepositoryInterface
     */
    protected function getContentRepository()
    {
        return $this->container->get('open_orchestra_model.repository.content');
    }

    /**
     * @param string           $immutableData
     * @param ContentInterface $object
     * @return string
     */
    protected function generateGetter($immutableData, ContentInterface $object)
    {
        foreach (array('get', 'is', 'has') as $prefix) {
            $getter = $prefix . ucfirst($immutableData);
            if (method_exists($object, $getter)) {
                return $getter;
            }
        }

        return $immutableData;
    }

    /**
     * @return ContentTypeRepositoryInterface
     */
    protected function getContentTypeRepository()
    {
        return $this->container->get('open_orchestra_model.repository.content_type');
    }

    /**
     * @param ContentInterface $content
     * @param string           $fieldId
     *
     * @return ContentAttributeInterface
     */
    protected function getContentAttribute(ContentInterface $content, $fieldId)
    {
        $contentAttribute = $content->getAttributeByName($fieldId);

        if (!$contentAttribute instanceof ContentAttributeInterface) {
            $contentAttributeClass = $this->contentAttributeClass;
            /** @var ContentAttributeInterface $contentAttribute */
            $contentAttribute = new $contentAttributeClass();
            $contentAttribute->setName($fieldId);
            $content->addAttribute($contentAttribute);
        }

        return $contentAttribute;
    }
}


<?php
namespace Chill\CustomFieldsBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

class ChoicesListType extends AbstractType
{

    private $defaultLocales;

    public function __construct($defaultLocales)
    {
        $this->defaultLocales = $defaultLocales;
    }

    /* (non-PHPdoc)
     * @see \Symfony\Component\Form\AbstractType::buildForm()
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $locales = $this->defaultLocales;

        $builder->add('name', 'translatable_string')
            ->add('active', 'checkbox', array(
                'required' => false
            ))
            ->add('slug', 'hidden', array(

            ))
            ->addEventListener(FormEvents::SUBMIT, function(FormEvent $event) use ($locales){
                $form = $event->getForm();
                $data = $event->getData();

                $formData = $form->getData();

                if (NULL === $formData['slug']) {
                    $slug = $form['name'][$locales[0]]->getData();
                    $slug = strtolower($slug);
                    $slug = preg_replace('/[^a-zA-Z0-9 -]/','', $slug); // only take alphanumerical characters, but keep the spaces and dashes too...
                    $slug = str_replace(' ','-', $slug); // replace spaces by dashes

                    $data['slug'] = $slug;
                    $event->setData($data);
                } else {
                    $data['slug'] = $formData['slug'];
                    $event->setData($data);
                }
            })
        ;
    }

    /*
     *
     * @see \Symfony\Component\Form\FormTypeInterface::getName()
     */
    public function getName()
    {
        return 'cf_choices_list';
    }

}