<?php namespace Ordercloud\Entities\Orders;

use Carbon\Carbon;
use JsonSerializable;

class ScheduleOption implements JsonSerializable
{
    /**
     * @var string
     */
    private $min;
    /**
     * @var string
     */
    private $max;
    /**
     * @var string
     */
    private $date;

    /**
     * @param string $min  Minimum time of day that order can be scheduled
     * @param string $max  Maximum time of day that order can be scheduled
     * @param string $date The date when the min and max times are applicable
     */
    public function __construct($min, $max, $date)
    {
        $this->min = $min;
        $this->max = $max;
        $this->date = $date;
    }

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

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

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

    /**
     * @param int $interval In minutes
     *
     * @return array|Carbon
     */
    public function getTimeOptions($interval)
    {
        $min = Carbon::parse($this->getMin());
        $max = Carbon::parse($this->getMax());
        $options = [];

        // Round up to the closest interval
        while ($min->minute % $interval != 0) {
            $min->addMinute();
        }

        // Add options foreach interval
        while ($min->lte($max)) {
            $options[] = $min->copy();
            $min->addMinutes($interval);
        }

        return $options;
    }

    /**
     * Specify data which should be serialized to JSON
     */
    public function jsonSerialize()
    {
        return [
            'min' => $this->getMin(),
            'max' => $this->getMax(),
            'date' => $this->getDate(),
        ];
    }
}


<?php
namespace ROH\Util;

use Exception;

class Composition
{
    protected $attributes = [];

    protected $core;

    protected $stack;

    protected $context;

    /**
     * Add callback to composition
     *
     * @param callable $callback
     * @return Composition
     */
    public function compose(callable $callback)
    {

        $this->attributes[] = $callback;

        return $this;
    }

    /**
     * Check whether composition is compiled
     *
     * @return boolean
     */
    public function isCompiled()
    {
        return null !== $this->stack;
    }

    /**
     * Compile composition
     *
     * @return Composition
     */
    public function compile()
    {
        if (!$this->isCompiled()) {
            $this->stack = [$this];
            $len = count($this->attributes);
            for ($i = $len - 1; $i >= 0; $i--) {
                $next = $this->stack[0];
                $handler = $this->attributes[$i];
                array_unshift($this->stack, function () use ($next, $handler) {
                    call_user_func($handler, $this->context, $next);
                    return $this->context;
                });
            }
        }

        return $this;
    }

    /**
     * Set core callable
     *
     * @param callable $core
     * @return Composition
     */
    public function setCore(callable $core)
    {
        $this->core = $core;
        return $this;
    }

    /**
     * Apply/run composition
     *
     * @param mixed $context
     * @return mixed
     */
    public function apply($context = null)
    {
        if (null === $this->core) {
            throw new Exception('Core is undefined');
        }

        $this->context = $context;
        return $this->compile()->stack[0]($context);
    }

    public function __invoke()
    {
        $core = $this->core;
        return $core($this->context);
    }

    public function __debugInfo()
    {
        return [
            'chain' => $this->attributes,
        ];
    }
}


<?php

namespace Reaction\Widgets\Bootstrap;

use Reaction\Assets\BootstrapAsset;
use Reaction\Helpers\Html;
use Reaction;
use Reaction\Exceptions\InvalidConfigException;
use Reaction\Helpers\ArrayHelper;

/**
 * Class Nav
 * @package Reaction\Widgets\Bootstrap
 */
class Nav extends Widget
{
    /**
     * @var array list of items in the nav widget. Each array element represents a single
     * menu item which can be either a string or an array with the following structure:
     *
     * - label: string, required, the nav item label.
     * - url: optional, the item's URL. Defaults to "#".
     * - visible: boolean, optional, whether this menu item is visible. Defaults to true.
     * - linkOptions: array, optional, the HTML attributes of the item's link.
     * - options: array, optional, the HTML attributes of the item container (LI).
     * - active: boolean, optional, whether the item should be on active state or not.
     * - dropDownOptions: array, optional, the HTML options that will passed to the [[Dropdown]] widget.
     * - items: array|string, optional, the configuration array for creating a [[Dropdown]] widget,
     *   or a string representing the dropdown menu. Note that Bootstrap does not support sub-dropdown menus.
     * - encode: boolean, optional, whether the label will be HTML-encoded. If set, supersedes the $encodeLabels option for only this item.
     *
     * If a menu item is a string, it will be rendered directly without HTML encoding.
     */
    public $items = [];
    /**
     * @var boolean whether the nav items labels should be HTML-encoded.
     */
    public $encodeLabels = true;
    /**
     * @var boolean whether to automatically activate items according to whether their route setting
     * matches the currently requested route.
     * @see isItemActive
     */
    public $activateItems = true;
    /**
     * @var boolean whether to activate parent menu items when one of the corresponding child menu items is active.
     */
    public $activateParents = false;
    /**
     * @var string the route used to determine if a menu item is active or not.
     * If not set, it will use the route of the current request.
     * @see params
     * @see isItemActive
     */
    public $route;
    /**
     * @var array the parameters used to determine if a menu item is active or not.
     * If not set, it will use `$_GET`.
     * @see route
     * @see isItemActive
     */
    public $params;
    /**
     * @var string this property allows you to customize the HTML which is used to generate the drop down caret symbol,
     * which is displayed next to the button text to indicate the drop down functionality.
     * Defaults to `null` which means `<span class="caret"></span>` will be used. To disable the caret, set this property to be an empty string.
     */
    public $dropDownCaret;
    /**
     * @var string name of a class to use for rendering dropdowns within this widget. Defaults to [[Dropdown]].
     */
    public $dropdownClass = 'Reaction\Widgets\Bootstrap\Dropdown';

    /**
     * Initializes the widget.
     */
    public function init()
    {
        parent::init();
        if ($this->route === null && $this->app->getRoute()->controller !== null) {
            $this->route = $this->app->getRoute()->getRoutePath(true);
        }
        if ($this->params === null) {
            $this->params = $this->app->reqHelper->getQueryParams();
        }
        Html::addCssClass($this->options, ['widget' => 'nav']);
    }

    /**
     * Renders the widget.
     * @return string
     * @throws InvalidConfigException
     * @throws \Exception
     */
    public function run()
    {
        BootstrapAsset::register($this->getView());
        return $this->renderItems();
    }

    /**
     * Renders widget items.
     * @return string
     * @throws InvalidConfigException
     * @throws \Exception
     */
    public function renderItems()
    {
        $items = [];
        foreach ($this->items as $i => $item) {
            if (isset($item['visible']) && !$item['visible']) {
                continue;
            }
            $items[] = $this->renderItem($item);
        }

        return $this->htmlHlp->tag('ul', implode("\n", $items), $this->options);
    }

    /**
     * Renders a widget's item.
     * @param string|array $item the item to render.
     * @return string the rendering result.
     * @throws InvalidConfigException
     * @throws \Exception
     */
    public function renderItem($item)
    {
        if (is_string($item)) {
            return $item;
        }
        if (!isset($item['label'])) {
            throw new InvalidConfigException("The 'label' option is required.");
        }
        $encodeLabel = isset($item['encode']) ? $item['encode'] : $this->encodeLabels;
        $label = $encodeLabel ? $this->htmlHlp->encode($item['label']) : $item['label'];
        $options = ArrayHelper::getValue($item, 'options', []);
        $items = ArrayHelper::getValue($item, 'items');
        $url = ArrayHelper::getValue($item, 'url', '#');
        $linkOptions = ArrayHelper::getValue($item, 'linkOptions', []);

        if (isset($item['active'])) {
            $active = ArrayHelper::remove($item, 'active', false);
        } else {
            $active = $this->isItemActive($item);
        }

        if (empty($items)) {
            $items = '';
        } else {
            $linkOptions['data-toggle'] = 'dropdown';
            Html::addCssClass($options, ['widget' => 'dropdown']);
            Html::addCssClass($linkOptions, ['widget' => 'dropdown-toggle']);
            if (isset($this->dropDownCaret) && $this->dropDownCaret !== '') {
                $label .= ' ' . $this->dropDownCaret;
            }
            if (is_array($items)) {
                $items = $this->isChildActive($items, $active);
                $items = $this->renderDropdown($items, $item);
            }
        }

        if ($active) {
            Html::addCssClass($linkOptions, 'active');
        }
        Html::addCssClass($options, 'nav-item');
        Html::addCssClass($linkOptions, 'nav-link');

        return $this->htmlHlp->tag('li', $this->htmlHlp->a($label, $url, $linkOptions) . $items, $options);
    }

    /**
     * Renders the given items as a dropdown.
     * This method is called to create sub-menus.
     * @param array $items the given items. Please refer to [[Dropdown::items]] for the array structure.
     * @param array $parentItem the parent item information. Please refer to [[items]] for the structure of this array.
     * @return string the rendering result.
     * @throws \Exception
     */
    protected function renderDropdown($items, $parentItem)
    {
        /** @var Widget $dropdownClass */
        $dropdownClass = $this->dropdownClass;
        return $dropdownClass::widget([
            'app' => $this->app,
            'options' => ArrayHelper::getValue($parentItem, 'dropDownOptions', []),
            'items' => $items,
            'encodeLabels' => $this->encodeLabels,
            'clientOptions' => false,
            'view' => $this->getView(),
        ]);
    }

    /**
     * Check to see if a child item is active optionally activating the parent.
     * @param array $items @see items
     * @param bool $active should the parent be active too
     * @return array @see items
     */
    protected function isChildActive($items, &$active)
    {
        foreach ($items as $i => $child) {
            if (is_array($child) && !ArrayHelper::getValue($child, 'visible', true)) {
                continue;
            }
            if (ArrayHelper::remove($items[$i], 'active', false) || $this->isItemActive($child)) {
                Html::addCssClass($items[$i]['options'], 'active');
                if ($this->activateParents) {
                    $active = true;
                }
            }
            $childItems = ArrayHelper::getValue($child, 'items');
            if (is_array($childItems)) {
                $activeParent = false;
                $items[$i]['items'] = $this->isChildActive($childItems, $activeParent);
                if ($activeParent) {
                    Html::addCssClass($items[$i]['options'], 'active');
                    $active = true;
                }
            }
        }
        return $items;
    }

    /**
     * Checks whether a menu item is active.
     * This is done by checking if [[route]] and [[params]] match that specified in the `url` option of the menu item.
     * When the `url` option of a menu item is specified in terms of an array, its first element is treated
     * as the route for the item and the rest of the elements are the associated parameters.
     * Only when its route and parameters match [[route]] and [[params]], respectively, will a menu item
     * be considered active.
     * @param array $item the menu item to be checked
     * @return bool whether the menu item is active
     */
    protected function isItemActive($item)
    {
        if (!$this->activateItems) {
            return false;
        }
        if (isset($item['url']) && is_array($item['url']) && isset($item['url'][0])) {
            $route = $item['url'][0];
            if ($route[0] !== '/' && $this->app->getRoute()->controller) {
                $route = $this->app->getRoute()->controller->getUniqueId() . '/' . $route;
            }
            if (ltrim($route, '/') !== $this->route) {
                return false;
            }
            unset($item['url']['#']);
            if (count($item['url']) > 1) {
                $params = $item['url'];
                unset($params[0]);
                foreach ($params as $name => $value) {
                    if ($value !== null && (!isset($this->params[$name]) || $this->params[$name] != $value)) {
                        return false;
                    }
                }
            }

            return true;
        }

        return false;
    }
}


<?php

namespace Philip\Plugin;

use Philip\AbstractPlugin as BasePlugin;
use Philip\IRC\Response;
use Philip\IRC\Event;

/**
 * Uses the DarkSky API to get up-to-the-minute forecasts.
 *
 * @author Bill Israel <bill.israel@gmail.com>
 */
class DarkSkyPlugin extends BasePlugin
{

    /** @var \DarkSky $darksky An instance of the DarkSky API wrapper */
    private $darksky;

    /**
     * Uses the DarkSky API to retrieve weather data
     */
    public function init()
    {
        $config = $this->getConfig();

        if (!isset($config['api_key'])) {
            throw new \Exception('Unable to locate darksky_api_key in bot configuration.');
        }

        $this->darksky = new \DarkSky($config['api_key']);
        $plugin = $this;    // PHP 5.3, you suck.

        // Look at all this weather!
        $this->bot->onChannel('/^!ds (\w+)(.*)/', function(Event $event) use ($plugin) {
            $matches = $event->getMatches();
            switch($cmd = $matches[0]) {
                case 'now':
                case 'current':
                    $plugin->getCurrentWeather(trim($matches[1]), $event);
                    break;

                case 'forecast':
                case 'at':
                    $plugin->getPrecipitation(trim($matches[1]), $event);
                    break;

                default:
                    $plugin->addErrorMsg($event, "Unknown command: $cmd");
                    break;
            }
        });
    }

    /**
     * Gets the current weather and a simple prediction for the next hour.
     *
     * @param string $where The location to lookup
     * @param \Philip\IRC\Event $event The event to handle
     *
     * @return void
     */
    public function getCurrentWeather($where, $event)
    {
        if (!$found = $this->getLatLongForLocation($where)) {
            $this->addLatLongError($event);
            return;
        }

        try {
            list($lat, $long) = $found;
            $forecast = $this->darksky->getBriefForecast($lat, $long);

            $event->addResponse(
                Response::msg(
                    $event->getRequest()->getSource(),
                    sprintf('[Weather for %s] Currently: %s, %s degrees. For the next hour: %s',
                        $where,
                        $forecast['currentSummary'],
                        $forecast['currentTemp'],
                        $forecast['hourSummary']
                    )
                )
            );
        } catch (\Exception $ex) {
            $this->addErrorMsg($event, "Oops, I'm unable to get the weather for that location...");
            return;
        }
    }

    /**
     * Gets the precipitation at a specific place and time.
     *
     * @param string $match The remainder of the match (holds location info)
     * @param \Philip\IRC\Event $event The event to handle.
     *
     * @return void
     */
    public function getPrecipitation($match, $event)
    {
        $location = explode('@', $match);
        $where = trim($location[0]);
        $when  = trim($location[1]);

        if (!$found = $this->getLatLongForLocation($where)) {
            $this->addLatLongError($event);
            return;
        }

        try {
            $time = new \DateTime($when);
            list($lat, $long) = $found;
            $precipitation = $this->darksky->getPrecipitation(array(
                'lat'  => $lat,
                'long' => $long,
                'time' => $time->getTimestamp()
            ));

            $chanceOfRain = $precipitation['precipitation'][0]['probability'] * 100;
            $intensity = $precipitation['precipitation'][0]['intensity'];

            $event->addResponse(
                Response::msg(
                    $event->getRequest()->getSource(),
                    sprintf('[Weather for %s @ %s] %s (%d%% chance of rain)',
                        $where,
                        $time->format('g:ia'),
                        $this->getEnglishIntensity($intensity),
                        $chanceOfRain
                    )
                )
            );
        } catch (\Exception $ex) {
            $this->addErrorMsg($event, "Oops. I'm unable to get the precipitation for that location at that time...");
            return;
        }
    }

    /**
     * This method uses the Google Maps Geocoding API to retrieve the
     * lat and long for the given location.
     *
     *      More info here: https://developers.google.com/maps/documentation/geocoding/
     *
     * @param string $location The location to look up the lat/long for
     *
     * @return array An array of 2 elements: the lat and the long
     */
    public function getLatLongForLocation($location)
    {
        $encoded = urlencode($location);
        $response = json_decode(
            file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=$encoded"),
            true
        );

        if ($response['status'] === 'OK') {
            $lat = $response['results'][0]['geometry']['location']['lat'];
            $long = $response['results'][0]['geometry']['location']['lng'];

            return array($lat, $long);
        }

        return false;
    }

    /**
     * Add a lat/long error response to the event
     *
     * @param \Philip\IRC\Event $event The event to add a response to
     *
     * @return void
     */
    public function addLatLongError($event)
    {
        $this->addErrorMsg($event, "Oops. I'm unable to find a lat/long for that location...");
    }

    /**
     * Add an error message to the response.
     *
     * @param \Philip\IRC\Event $event The event to add a response to
     * @param string $msg The error message to send
     *
     * @return void
     */
    public function addErrorMsg($event, $msg)
    {
        $event->addResponse(Response::msg($event->getRequest()->getSource(), $msg));
    }

    /**
     * Converts an intensity value to a string.
     *
     * @param float $intensity The intensity value to convert to a string
     *
     * @return string
     */
    private function getEnglishIntensity($intensity)
    {
        $desc = 'no';

        if ($intensity >= 2 && $intensity < 15) {
            $desc = 'sporadic';
        } else if ($intensity >= 15 && $intensity < 30) {
            $desc = 'light';
        } else if ($intensity >= 30 && $intensity < 45) {
            $desc = 'moderate';
        } else if ($intensity > 45) {
            $desc = 'heavy';
        }

        return $desc . ' rain';
    }

    /**
     * Help messages!
     */
    public function displayHelp(Event $event)
    {
        return array(
            "!ds now|current <location> - retrieves the current conditions for the given location",
            "!ds forecast|at <location> @ <time> - retrieves the forecast for the location at the given time"
        );
    }

    /**
     * @see \Philip\AbstractPlugin#getName()
     */
    public function getName()
    {
        return 'DarkSkyPlugin';
    }
}


<?php

namespace Reaction\Base\Logger;

use React\Stream\WritableStreamInterface;
use Reaction\Helpers\Console;
use Reaction\Helpers\StringHelper;

/**
 * Class Debugger
 * @package Reaction\Base\Logger
 */
class Debugger
{
    /**
     * Print backtrace to console
     * @param bool $withArgs Show arguments names and content
     * @param int  $traceShift Shift trace for number positions
     * @param bool $useEcho Use direct call to `echo` function instead of Stream::write()
     */
    public static function backTrace($withArgs = false, $traceShift = 0, $useEcho = false)
    {
        $trace = debug_backtrace();
        if ($traceShift > 0) {
            $trace = array_slice($trace, $traceShift);
        }
        $called = array_shift($trace);
        $trace = static::reduceBacktrace($trace);
        $functions = [];
        $padLn = 12;
        $traceNum = 0;
        foreach ($trace as $row) {
            $function = $row['function'];
            $functionStr = isset($row['class'])
                ? $row['class'] . $row['type'] . $function
                : $function;
            $functionStr = Console::ansiFormat($functionStr, [Console::FG_GREEN, Console::BOLD]);
            if ($withArgs) {
                /** @var \Throwable[] $exceptionArgs */
                $exceptionArgs = [];
                list($argsSimple, $argsFull, $argsStrLength) = static::getArgumentsFromTrace($row, true);
                $argsFullExt = $argsStrLength > 100;
                $argsFullMaxLn = 0;
                $functionStr .= '(' . implode(', ', $argsSimple) . ')';
                if ($argsFullExt) {
                    foreach ($argsFull as $argName => $argValue) {
                        $argLn = mb_strlen($argName);
                        $argsFullMaxLn = $argsFullMaxLn < $argLn ? $argLn : $argsFullMaxLn;
                    }
                }
                $argsFullOld = $argsFull;
                $argsFull = [];
                foreach ($argsFullOld as $argName => $argValue) {
                    $argName = str_pad($argName, $argsFullMaxLn, ' ', STR_PAD_RIGHT);
                    $argsFull[] = Console::ansiFormat($argName, [Console::FG_GREEN]) . ' ' . $argValue;
                }
                $argsFullSeparator = $argsFullExt ? "\n" . str_repeat(' ', $padLn) : ", ";
                $functionStr .= !empty($argsFull) ? "\n" . str_repeat(' ', $padLn) . implode($argsFullSeparator, $argsFull) : '';
                if (!empty($exceptionArgs)) {
                    foreach ($exceptionArgs as $exceptionArg) {
                        $functionStr .= "\n" . str_pad('', $padLn, ' ', STR_PAD_LEFT)
                            . Console::ansiFormat($exceptionArg->getMessage(), [Console::FG_RED]);
                    }
                }
            } else {
                $functionStr .= '()';
            }
            $positionStr = '';
            if (isset($row['file']) && $row['file'] !== "") {
                $positionStr .= "\n" . str_pad('', $padLn, ' ', STR_PAD_RIGHT)
                    . Console::ansiFormat($row['file'], [Console::FG_PURPLE]);
            } else {
                $positionStr .= "\n" . str_pad('', $padLn, ' ', STR_PAD_RIGHT)
                    . Console::ansiFormat('{no path}', [Console::FG_PURPLE]);
            }
            if (isset($row['line']) && $row['line'] !== "") {
                $positionStr .= ' ' . Console::ansiFormat('#' . $row['line'], [Console::FG_CYAN]);
            }
            $functionStr .= $positionStr;
            $functionStr = str_pad('[' . $traceNum . '] ', $padLn - 1, '-', STR_PAD_RIGHT) . ' ' . $functionStr;
            $functionStr = str_pad($functionStr, $padLn, ' ', STR_PAD_RIGHT);
            $functions[] = $functionStr;
            $traceNum++;
        }
        $str = "\n" . implode("\n", $functions) . "\n";
        $str .= Console::ansiFormat("Called from " . $called['file'] . ' #' . $called['line'], [Console::FG_YELLOW]) . "\n";
        if ($useEcho) {
            echo $str . "\n";
        } else {
            /** @var WritableStreamInterface $stream */
            $stream = \Reaction::create('stdoutWriteStream');
            $stream->write($str . "\n");
        }
    }

    /**
     * Reduce backtrace
     * @param array $trace
     * @param bool  $withLineNum
     * @return array
     */
    public static function reduceBacktrace($trace = [], $withLineNum = false)
    {
        $traceNew = [];
        if ($withLineNum) {
            $trace = array_filter($trace, function($row) {
                return isset($row['file']) && isset($row['line']);
            });
        }
        foreach ($trace as $row) {
            if (isset($row['class']) && isset($exclude[$row['class']])) {
                if (empty($exclude[$row['class']])) {
                    continue;
                } elseif (!empty($row['function']) && in_array($row['function'], $exclude[$row['class']])) {
                    continue;
                }
            }
            $traceNew[] = $row;
        }
        return $traceNew;
    }

    /**
     * Get trace row arguments
     * @param array $row
     * @param bool $explain
     * @return array
     */
    protected static function getArgumentsFromTrace($row, $explain = false)
    {
        $isClosure = strpos(strtolower($row['function']), '{closure}') !== false;
        $argsSimple = [];
        $argsFull = [];
        $argsStrLength = 0;
        if (!empty($row['args'])) {
            if (!$isClosure) {
                try {
                    $funcRef = isset($row['class']) && $row['class'] !== ""
                        ? new \ReflectionMethod($row['class'], $row['function'])
                        : new \ReflectionFunction($row['function']);
                    $funcParams = $funcRef->getParameters();
                } catch (\ReflectionException $exception) {
                    $funcParams = [];
                }
            } else {
                $funcParams = [];
            }
            foreach ($row['args'] as $argNum => $arg) {
                $argType = $argSimple = gettype($arg);
                $argName = '$...';
                if ($argType === 'object') {
                    $argSimple = get_class($arg);
                }
                if (isset($funcParams[$argNum])) {
                    $argName = '$' . $funcParams[$argNum]->name;
                    $argSimple .= Console::ansiFormat(' ' . $argName, [Console::FG_GREEN]);
                }
                $argSimple = Console::ansiFormat($argSimple, [Console::FG_CYAN]);
                $argsSimple[] = $argSimple;

                if (!$explain) {
                    continue;
                }

                $argIsException = false;
                if ($argType === 'object' && $arg instanceof \Throwable) {
                    $exceptionArgs[] = $argNum;
                    $argIsException = true;
                    $argValue = "'" . $arg->getMessage() . "'" . ' thrown in (' . $arg->getFile() . ' #' . $arg->getLine() . ')';
                } elseif ($argType === 'integer') {
                    $argValue = $arg;
                } elseif ($argType === 'string') {
                    $argValue = strlen($arg) < 80 ? $arg : StringHelper::truncate($arg, 80);
                    $argValue = "'" . $argValue . "'";
                } elseif ($argType === 'boolean') {
                    $argValue = !empty($arg) ? 'TRUE' : 'FALSE';
                } elseif ($argType === 'array') {
                    $argValue = 'array(' . count($arg) . ')';
                } elseif ($arg === null) {
                    $argValue = 'NULL';
                } else {
                    $argValue = $argType === 'object' ? get_class($arg) : $argType;
                }
                $argName = isset($argName) ? $argName : '$';
                $argsStrLength += mb_strlen($argName) + mb_strlen($argValue);
                $argFull = !$argIsException
                    ? Console::ansiFormat($argValue, [Console::FG_CYAN])
                    : Console::ansiFormat($argValue, [Console::FG_RED]);
                $argsFull[$argName] = $argFull;
            }
        }
        return [$argsSimple, $argsFull, $argsStrLength];
    }
}


<?php

/*
 * This file is part of the Valkyrja framework.
 *
 * (c) Melech Mizrachi
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Valkyrja\Annotations;

use ReflectionClass;
use ReflectionFunction;
use ReflectionFunctionAbstract;
use ReflectionMethod;
use ReflectionParameter;
use ReflectionProperty;
use Valkyrja\Application;
use Valkyrja\Container\CoreComponent;
use Valkyrja\Support\Providers\Provides;

/**
 * Class Annotations.
 *
 * @author Melech Mizrachi
 */
class NativeAnnotations implements Annotations
{
    use Provides;

    /**
     * The parser.
     *
     * @var \Valkyrja\Annotations\AnnotationsParser
     */
    protected $parser;

    /**
     * Cached reflection classes.
     *
     * @var array
     */
    protected static $reflections = [];

    /**
     * Cached annotations.
     *
     * @var array
     */
    protected static $annotations = [];

    /**
     * Cache index constants.
     */
    protected const CLASS_CACHE             = 'class';
    protected const CLASS_MEMBERS_CACHE     = 'class.members';
    protected const CLASS_AND_MEMBERS_CACHE = 'class.and.members';
    protected const PROPERTY_CACHE          = 'property';
    protected const PROPERTIES_CACHE        = 'properties';
    protected const METHOD_CACHE            = 'method';
    protected const METHODS_CACHE           = 'methods';
    protected const FUNCTION_CACHE          = 'function';

    /**
     * Annotations constructor.
     *
     * @param AnnotationsParser $parser The parser
     */
    public function __construct(AnnotationsParser $parser)
    {
        $this->parser = $parser;
    }

    /**
     * Get the parser.
     *
     * @return \Valkyrja\Annotations\AnnotationsParser
     */
    public function getParser(): AnnotationsParser
    {
        return $this->parser;
    }

    /**
     * Set the parser.
     *
     * @param AnnotationsParser $parser The parser
     *
     * @return void
     */
    public function setParser(AnnotationsParser $parser): void
    {
        $this->parser = $parser;
    }

    /**
     * Get a class's annotations.
     *
     * @param string $class The class
     *
     * @throws \ReflectionException
     *
     * @return \Valkyrja\Annotations\Annotation[]
     */
    public function classAnnotations(string $class): array
    {
        $index = static::CLASS_CACHE . $class;

        return self::$annotations[$index]
            ?? self::$annotations[$index] = $this->setAnnotationValues(
                [
                    'class' => $class,
                ],
                ...$this->parser->getAnnotations(
                $this->getClassReflection($class)->getDocComment()
            )
            );
    }

    /**
     * Get a class's annotations by type.
     *
     * @param string $type  The type
     * @param string $class The class
     *
     * @throws \ReflectionException
     *
     * @return array
     */
    public function classAnnotationsType(string $type, string $class): array
    {
        return $this->filterAnnotationsByType(
            $type,
            ...$this->classAnnotations($class)
        );
    }

    /**
     * Get a class's members' annotations.
     *
     * @param string $class The class
     *
     * @throws \ReflectionException
     *
     * @return \Valkyrja\Annotations\Annotation[]
     */
    public function classMembersAnnotations(string $class): array
    {
        $index = static::CLASS_MEMBERS_CACHE . $class;

        if (isset(self::$annotations[$index])) {
            return self::$annotations[$index];
        }

        return self::$annotations[$index] = array_merge(
            $this->propertiesAnnotations($class),
            $this->methodsAnnotations($class)
        );
    }

    /**
     * Get a class's members' annotations by type.
     *
     * @param string $type  The type
     * @param string $class The class
     *
     * @throws \ReflectionException
     *
     * @return \Valkyrja\Annotations\Annotation[]
     */
    public function classMembersAnnotationsType(string $type, string $class): array
    {
        return $this->filterAnnotationsByType(
            $type,
            ...$this->classMembersAnnotations(
            $class
        )
        );
    }

    /**
     * Get a class's and class's members' annotations.
     *
     * @param string $class The class
     *
     * @throws \ReflectionException
     *
     * @return \Valkyrja\Annotations\Annotation[]
     */
    public function classAndMembersAnnotations(string $class): array
    {
        $index = static::CLASS_AND_MEMBERS_CACHE . $class;

        if (isset(self::$annotations[$index])) {
            return self::$annotations[$index];
        }

        return self::$annotations[$index] = array_merge(
            $this->classAnnotations($class),
            $this->classMembersAnnotations($class)
        );
    }

    /**
     * Get a class's and class's members' annotations by type.
     *
     * @param string $type  The type
     * @param string $class The class
     *
     * @throws \ReflectionException
     *
     * @return \Valkyrja\Annotations\Annotation[]
     */
    public function classAndMembersAnnotationsType(
        string $type,
        string $class
    ): array {
        return $this->filterAnnotationsByType(
            $type,
            ...$this->classAndMembersAnnotations(
            $class
        )
        );
    }

    /**
     * Get a property's annotations.
     *
     * @param string $class    The class
     * @param string $property The property
     *
     * @throws \ReflectionException
     *
     * @return \Valkyrja\Annotations\Annotation[]
     */
    public function propertyAnnotations(string $class, string $property): array
    {
        $index = static::PROPERTY_CACHE . $class . $property;

        return self::$annotations[$index]
            ?? self::$annotations[$index] = $this->setAnnotationValues(
                [
                    'class'    => $class,
                    'property' => $property,
                ],
                ...$this->parser->getAnnotations(
                $this->getPropertyReflection($class, $property)->getDocComment()
            )
            );
    }

    /**
     * Get a property's annotations by type.
     *
     * @param string $type     The type
     * @param string $class    The class
     * @param string $property The property
     *
     * @throws \ReflectionException
     *
     * @return \Valkyrja\Annotations\Annotation[]
     */
    public function propertyAnnotationsType(string $type, string $class, string $property): array
    {
        return $this->filterAnnotationsByType(
            $type,
            ...$this->propertyAnnotations(
            $class,
            $property
        )
        );
    }

    /**
     * Get a class's properties' annotations.
     *
     * @param string $class The class
     *
     * @throws \ReflectionException
     *
     * @return \Valkyrja\Annotations\Annotation[]
     */
    public function propertiesAnnotations(string $class): array
    {
        $index = static::PROPERTIES_CACHE . $class;

        if (isset(self::$annotations[$index])) {
            return self::$annotations[$index];
        }

        $annotations = [];
        // Get the class's reflection
        $reflection = $this->getClassReflection($class);

        // Iterate through the properties
        foreach ($reflection->getProperties() as $property) {
            $index = static::METHOD_CACHE . $class . $property->getName();
            // Set the property's reflection class in the cache
            self::$reflections[$index] = $property;

            // Iterate through all the property's annotations
            foreach ($this->propertyAnnotations(
                $class,
                $property->getName()
            ) as $propertyAnnotation) {
                // Set the annotation in the list
                $annotations[] = $propertyAnnotation;
            }
        }

        self::$annotations[$index] = $annotations;

        return $annotations;
    }

    /**
     * Get a class's properties' annotations by type.
     *
     * @param string $type  The type
     * @param string $class The class
     *
     * @throws \ReflectionException
     *
     * @return \Valkyrja\Annotations\Annotation[]
     */
    public function propertiesAnnotationsType(string $type, string $class): array
    {
        return $this->filterAnnotationsByType(
            $type,
            ...$this->propertiesAnnotations(
            $class
        )
        );
    }

    /**
     * Get a method's annotations.
     *
     * @param string $class  The class
     * @param string $method The method
     *
     * @throws \ReflectionException
     *
     * @return \Valkyrja\Annotations\Annotation[]
     */
    public function methodAnnotations(string $class, string $method): array
    {
        $index      = static::METHOD_CACHE . $class . $method;
        $reflection = $this->getMethodReflection($class, $method);

        return self::$annotations[$index]
            ?? self::$annotations[$index] = $this->setAnnotationValues(
                [
                    'class'  => $class,
                    'method' => $method,
                ],
                ...$this->getReflectionFunctionAnnotations(
                $reflection
            )
            );
    }

    /**
     * Get a method's annotations by type.
     *
     * @param string $type   The type
     * @param string $class  The class
     * @param string $method The method
     *
     * @throws \ReflectionException
     *
     * @return \Valkyrja\Annotations\Annotation[]
     */
    public function methodAnnotationsType(string $type, string $class, string $method): array
    {
        return $this->filterAnnotationsByType(
            $type,
            ...$this->methodAnnotations(
            $class,
            $method
        )
        );
    }

    /**
     * Get a class's methods' annotations.
     *
     * @param string $class The class
     *
     * @throws \ReflectionException
     *
     * @return \Valkyrja\Annotations\Annotation[]
     */
    public function methodsAnnotations(string $class): array
    {
        $index = static::METHODS_CACHE . $class;

        if (isset(self::$annotations[$index])) {
            return self::$annotations[$index];
        }

        $annotations = [];
        // Get the class's reflection
        $reflection = $this->getClassReflection($class);

        // Iterate through the methods
        foreach ($reflection->getMethods() as $method) {
            $index = static::METHOD_CACHE . $class . $method->getName();
            // Set the method's reflection class in the cache
            self::$reflections[$index] = $method;

            // Iterate through all the method's annotations
            foreach ($this->methodAnnotations(
                $class,
                $method->getName()
            ) as $methodAnnotation) {
                // Set the annotation in the list
                $annotations[] = $methodAnnotation;
            }
        }

        self::$annotations[$index] = $annotations;

        return $annotations;
    }

    /**
     * Get a class's methods' annotations by type.
     *
     * @param string $type  The type
     * @param string $class The class
     *
     * @throws \ReflectionException
     *
     * @return \Valkyrja\Annotations\Annotation[]
     */
    public function methodsAnnotationsType(string $type, string $class): array
    {
        return $this->filterAnnotationsByType(
            $type,
            ...$this->methodsAnnotations($class)
        );
    }

    /**
     * Get a function's annotations.
     *
     * @param string $function The function
     *
     * @throws \ReflectionException
     *
     * @return \Valkyrja\Annotations\Annotation[]
     */
    public function functionAnnotations(string $function): array
    {
        $index = static::FUNCTION_CACHE . $function;

        return self::$annotations[$index]
            ?? self::$annotations[$index] = $this->setAnnotationValues(
                [
                    'function' => $function,
                ],
                ...$this->getReflectionFunctionAnnotations(
                $this->getFunctionReflection($function)
            )
            );
    }

    /**
     * Get a function's annotations.
     *
     * @param string $type     The type
     * @param string $function The function
     *
     * @throws \ReflectionException
     *
     * @return \Valkyrja\Annotations\Annotation[]
     */
    public function functionAnnotationsType(string $type, string $function): array
    {
        return $this->filterAnnotationsByType(
            $type,
            ...$this->functionAnnotations(
            $function
        )
        );
    }

    /**
     * Filter annotations by type.
     *
     * @param string       $type           The type to match
     * @param Annotation[] ...$annotations The annotations
     *
     * @return array
     */
    public function filterAnnotationsByType(string $type, Annotation ...$annotations): array
    {
        // Set a list of annotations to return
        $annotationsList = [];

        // Iterate through the annotation
        foreach ($annotations as $annotation) {
            // If the annotation's type matches the type requested
            if ($annotation->getAnnotationType() === $type) {
                // Set the annotation in the list
                $annotationsList[] = $annotation;
            }
        }

        return $annotationsList;
    }

    /**
     * Get a reflection class's annotations.
     *
     * @param \ReflectionFunctionAbstract $reflection The reflection class
     *
     * @return \Valkyrja\Annotations\Annotation[]
     */
    public function getReflectionFunctionAnnotations(ReflectionFunctionAbstract $reflection): array
    {
        return $this->parser->getAnnotations($reflection->getDocComment());
    }

    /**
     * Set the base annotation model values.
     *
     * @param array        $properties  The properties
     * @param Annotation[] $annotations The annotations
     *
     * @return \Valkyrja\Annotations\Annotation[]
     */
    protected function setAnnotationValues(array $properties, Annotation ...$annotations): array
    {
        foreach ($annotations as $annotation) {
            $annotation->setClass($properties['class'] ?? null);
            $annotation->setProperty($properties['property'] ?? null);
            $annotation->setMethod($properties['method'] ?? null);
            $annotation->setFunction($properties['function'] ?? null);
        }

        return $annotations;
    }

    /**
     * Get a class's reflection.
     *
     * @param string $class The class
     *
     * @throws \ReflectionException
     *
     * @return \ReflectionClass
     */
    public function getClassReflection(string $class): ReflectionClass
    {
        $index = static::CLASS_CACHE . $class;

        return self::$reflections[$index]
            ?? self::$reflections[$index] = new ReflectionClass($class);
    }

    /**
     * Get a property's reflection.
     *
     * @param string $class    The class
     * @param string $property The property
     *
     * @throws \ReflectionException
     *
     * @return \ReflectionProperty
     */
    public function getPropertyReflection(string $class, string $property): ReflectionProperty
    {
        $index = static::PROPERTY_CACHE . $class . $property;

        return self::$reflections[$index]
            ?? self::$reflections[$index] =
                new ReflectionProperty($class, $property);
    }

    /**
     * Get a method's reflection.
     *
     * @param string $class  The class
     * @param string $method The method
     *
     * @throws \ReflectionException
     *
     * @return \ReflectionMethod
     */
    public function getMethodReflection(string $class, string $method): ReflectionMethod
    {
        $index = static::METHOD_CACHE . $class . $method;

        return self::$reflections[$index]
            ?? self::$reflections[$index] =
                new ReflectionMethod($class, $method);
    }

    /**
     * get a function's reflection.
     *
     * @param string $function The function
     *
     * @throws \ReflectionException
     *
     * @return \ReflectionFunction
     */
    public function getFunctionReflection(string $function): ReflectionFunction
    {
        $index = static::FUNCTION_CACHE . $function;

        return self::$reflections[$index]
            ?? self::$reflections[$index] = new ReflectionFunction($function);
    }

    /**
     * Get dependencies from parameters.
     *
     * @param \ReflectionParameter[] $parameters The parameters
     *
     * @return string[]
     */
    protected function getDependencies(ReflectionParameter ...$parameters): array
    {
        // Setup to find any injectable objects through the service container
        $dependencies = [];

        // Iterate through the method's parameters
        foreach ($parameters as $parameter) {
            // We only care for classes
            if ($parameter->getClass()) {
                // Set the injectable in the array
                $dependencies[] = $parameter->getClass()->getName();
            }
        }

        return $dependencies;
    }

    /**
     * The items provided by this provider.
     *
     * @return array
     */
    public static function provides(): array
    {
        return [
            Annotations::class,
        ];
    }

    /**
     * Publish the provider.
     *
     * @param Application $app The application
     *
     * @return void
     */
    public static function publish(Application $app): void
    {
        $app->container()->singleton(
            Annotations::class,
            new static(
                $app->container()->getSingleton(
                    CoreComponent::ANNOTATIONS_PARSER
                )
            )
        );
    }
}


<?php
/**
 * This file is part of the Maths package.
 *
 * Copyright (c) 2014-2016 Pierre Cassat <me@e-piwi.fr> and contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * The source code of this package is available online at
 * <http://github.com/atelierspierrot/maths>.
 */

namespace Maths\Geometry;

use \Maths\Maths;
use \Maths\Geometry\Line;
use \Maths\PointInterface;

/**
 * Segment class : two points A -> B
 *
 * @author  piwi <me@e-piwi.fr>
 */
class Segment
    extends Line
{

    /**
     * Write a segment as `[(Ax,Ay),(Bx,By)]`
     *
     * @return  string
     */
    public function __toString()
    {
        return Maths::segmentToString(
            ($this->is3D() ?
                array($this->getPointA()->x, $this->getPointA()->y, $this->getPointA()->z) : array($this->getPointA()->x, $this->getPointA()->y)
            ),
            ($this->is3D() ?
                array($this->getPointB()->x, $this->getPointB()->y, $this->getPointB()->z) : array($this->getPointB()->x, $this->getPointB()->y)
            )
        );
    }

    /**
     * Write an algebraic function of the segment
     *
     * @return  string
     */
    public function __equationToString()
    {
        return "y = f(x){ ({$this->getSlope()} * x) + {$this->getYIntercept()} }";
    }

// Characteristics

    /**
     * Get the length of the segment
     *
     * @return  float
     */
    public function getLength()
    {
        return sqrt(
            pow(($this->getPointB()->getAbscissa() - $this->getPointA()->getAbscissa()), 2)
            +
            pow(($this->getPointB()->getOrdinate() - $this->getPointA()->getOrdinate()), 2)
        );
    }

    /**
     * Get the middle of the segment as a `\Maths\Geometry\Point` object
     *
     * @return  \Maths\Geometry\Point
     */
    public function getCenter()
    {
        $abscissas = array(
            $this->getPointA()->getAbscissa(), $this->getPointB()->getAbscissa()
        );
        $ordinates = array(
            $this->getPointA()->getOrdinate(), $this->getPointB()->getOrdinate()
        );
        return new Point(
            ((max($abscissas) - min($abscissas)) / 2),
            ((max($ordinates) - min($ordinates)) / 2)
        );
    }
}


<?php

namespace Reaction\Widgets;

use Reaction;
use Reaction\Assets\ActiveFormAsset;
use Reaction\Exceptions\InvalidCallException;
use Reaction\Base\Model;
use Reaction\Base\Widget;
use Reaction\Helpers\ArrayHelper;
use Reaction\Helpers\Html;

/**
 * ActiveForm is a widget that builds an interactive HTML form for one or multiple data models.
 *
 * For more details and usage information on ActiveForm, see the [guide article on forms](guide:input-forms).
 */
class ActiveForm extends Widget
{
    /**
     * Add validation state class to container tag
     */
    const VALIDATION_STATE_ON_CONTAINER = 'container';
    /**
     * Add validation state class to input tag
     */
    const VALIDATION_STATE_ON_INPUT = 'input';

    /**
     * @var array|string the form action URL. This parameter will be processed by [[\yii\helpers\Url::to()]].
     * @see method for specifying the HTTP method for this form.
     */
    public $action = '';
    /**
     * @var string the form submission method. This should be either `post` or `get`. Defaults to `post`.
     *
     * When you set this to `get` you may see the url parameters repeated on each request.
     * This is because the default value of [[action]] is set to be the current request url and each submit
     * will add new parameters instead of replacing existing ones.
     * You may set [[action]] explicitly to avoid this:
     *
     * ```php
     * $form = ActiveForm::begin([
     *     'method' => 'get',
     *     'action' => ['controller/action'],
     * ]);
     * ```
     */
    public $method = 'post';
    /**
     * @var array the HTML attributes (name-value pairs) for the form tag.
     * @see \Reaction\Helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
     */
    public $options = [];
    /**
     * @var string the default field class name when calling [[field()]] to create a new field.
     * @see fieldConfig
     */
    public $fieldClass = 'Reaction\Widgets\ActiveField';
    /**
     * @var array|\Closure the default configuration used by [[field()]] when creating a new field object.
     * This can be either a configuration array or an anonymous function returning a configuration array.
     * If the latter, the signature should be as follows:
     *
     * ```php
     * function ($model, $attribute)
     * ```
     *
     * The value of this property will be merged recursively with the `$options` parameter passed to [[field()]].
     *
     * @see fieldClass
     */
    public $fieldConfig = [];
    /**
     * @var bool whether to perform encoding on the error summary.
     */
    public $encodeErrorSummary = true;
    /**
     * @var string the default CSS class for the error summary container.
     * @see errorSummary()
     */
    public $errorSummaryCssClass = 'error-summary';
    /**
     * @var string the CSS class that is added to a field container when the associated attribute is required.
     */
    public $requiredCssClass = 'required';
    /**
     * @var string the CSS class that is added to a field container when the associated attribute has validation error.
     */
    public $errorCssClass = 'has-error';
    /**
     * @var string the CSS class that is added to a field container when the associated attribute is successfully validated.
     */
    public $successCssClass = 'has-success';
    /**
     * @var string the CSS class that is added to a field container when the associated attribute is being validated.
     */
    public $validatingCssClass = 'validating';
    /**
     * @var string where to render validation state class
     * Could be either "container" or "input".
     * Default is "container".
     */
    public $validationStateOn = self::VALIDATION_STATE_ON_CONTAINER;
    /**
     * @var bool whether to enable client-side data validation.
     * If [[ActiveField::enableClientValidation]] is set, its value will take precedence for that input field.
     */
    public $enableClientValidation = true;
    /**
     * @var bool whether to enable AJAX-based data validation.
     * If [[ActiveField::enableAjaxValidation]] is set, its value will take precedence for that input field.
     */
    public $enableAjaxValidation = false;
    /**
     * @var bool whether to hook up `yii.activeForm` JavaScript plugin.
     * This property must be set `true` if you want to support client validation and/or AJAX validation, or if you
     * want to take advantage of the `yii.activeForm` plugin. When this is `false`, the form will not generate
     * any JavaScript.
     * @see registerClientScript
     */
    public $enableClientScript = true;
    /**
     * @var array|string the URL for performing AJAX-based validation. This property will be processed by
     * [[Url::to()]]. Please refer to [[Url::to()]] for more details on how to configure this property.
     * If this property is not set, it will take the value of the form's action attribute.
     */
    public $validationUrl;
    /**
     * @var bool whether to perform validation when the form is submitted.
     */
    public $validateOnSubmit = true;
    /**
     * @var bool whether to perform validation when the value of an input field is changed.
     * If [[ActiveField::validateOnChange]] is set, its value will take precedence for that input field.
     */
    public $validateOnChange = true;
    /**
     * @var bool whether to perform validation when an input field loses focus.
     * If [[ActiveField::$validateOnBlur]] is set, its value will take precedence for that input field.
     */
    public $validateOnBlur = true;
    /**
     * @var bool whether to perform validation while the user is typing in an input field.
     * If [[ActiveField::validateOnType]] is set, its value will take precedence for that input field.
     * @see validationDelay
     */
    public $validateOnType = false;
    /**
     * @var int number of milliseconds that the validation should be delayed when the user types in the field
     * and [[validateOnType]] is set `true`.
     * If [[ActiveField::validationDelay]] is set, its value will take precedence for that input field.
     */
    public $validationDelay = 500;
    /**
     * @var string the name of the GET parameter indicating the validation request is an AJAX request.
     */
    public $ajaxParam = 'ajax';
    /**
     * @var string the type of data that you're expecting back from the server.
     */
    public $ajaxDataType = 'json';
    /**
     * @var bool whether to scroll to the first error after validation.
     */
    public $scrollToError = true;
    /**
     * @var int offset in pixels that should be added when scrolling to the first error.
     */
    public $scrollToErrorOffset = 0;
    /**
     * @var array the client validation options for individual attributes. Each element of the array
     * represents the validation options for a particular attribute.
     * @internal
     */
    public $attributes = [];

    /**
     * @var ActiveField[] the ActiveField objects that are currently active
     */
    private $_fields = [];

    /**
     * Initializes the widget.
     * This renders the form open tag.
     */
    public function init()
    {
        parent::init();
        if (!isset($this->options['id'])) {
            $this->options['id'] = $this->getId();
        }
        ob_start();
        ob_implicit_flush(false);
    }

    /**
     * Runs the widget.
     * This registers the necessary JavaScript code and renders the form open and close tags.
     * @throws InvalidCallException if `beginField()` and `endField()` calls are not matching.
     */
    public function run()
    {
        if (!empty($this->_fields)) {
            throw new InvalidCallException('Each beginField() should have a matching endField() call.');
        }

        $content = ob_get_clean();
        echo $this->htmlHlp->beginForm($this->action, $this->method, $this->options);
        echo $content;

        if ($this->enableClientScript) {
            $this->registerClientScript();
        }

        echo $this->htmlHlp->endForm();
    }

    /**
     * This registers the necessary JavaScript code.
     */
    public function registerClientScript()
    {
        $id = $this->options['id'];
        $options = $this->jsonHlp->htmlEncode($this->getClientOptions());
        $attributes = $this->jsonHlp->htmlEncode($this->attributes);
        $view = $this->getView();
        ActiveFormAsset::register($view);
        $view->registerJs("jQuery('#$id').yiiActiveForm($attributes, $options);");
    }

    /**
     * Returns the options for the form JS widget.
     * @return array the options.
     */
    protected function getClientOptions()
    {
        $options = [
            'encodeErrorSummary' => $this->encodeErrorSummary,
            'errorSummary' => '.' . implode('.', preg_split('/\s+/', $this->errorSummaryCssClass, -1, PREG_SPLIT_NO_EMPTY)),
            'validateOnSubmit' => $this->validateOnSubmit,
            'errorCssClass' => $this->errorCssClass,
            'successCssClass' => $this->successCssClass,
            'validatingCssClass' => $this->validatingCssClass,
            'ajaxParam' => $this->ajaxParam,
            'ajaxDataType' => $this->ajaxDataType,
            'scrollToError' => $this->scrollToError,
            'scrollToErrorOffset' => $this->scrollToErrorOffset,
            'validationStateOn' => $this->validationStateOn,
        ];
        if ($this->validationUrl !== null) {
            $options['validationUrl'] = $this->urlHlp->to($this->validationUrl);
        }

        // only get the options that are different from the default ones (set in yii.activeForm.js)
        return array_diff_assoc($options, [
            'encodeErrorSummary' => true,
            'errorSummary' => '.error-summary',
            'validateOnSubmit' => true,
            'errorCssClass' => 'has-error',
            'successCssClass' => 'has-success',
            'validatingCssClass' => 'validating',
            'ajaxParam' => 'ajax',
            'ajaxDataType' => 'json',
            'scrollToError' => true,
            'scrollToErrorOffset' => 0,
            'validationStateOn' => self::VALIDATION_STATE_ON_CONTAINER,
        ]);
    }

    /**
     * Generates a summary of the validation errors.
     * If there is no validation error, an empty error summary markup will still be generated, but it will be hidden.
     * @param Model|Model[] $models the model(s) associated with this form.
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
     *
     * - `header`: string, the header HTML for the error summary. If not set, a default prompt string will be used.
     * - `footer`: string, the footer HTML for the error summary.
     *
     * The rest of the options will be rendered as the attributes of the container tag. The values will
     * be HTML-encoded using [[\yii\helpers\Html::encode()]]. If a value is `null`, the corresponding attribute will not be rendered.
     * @return string the generated error summary.
     * @see errorSummaryCssClass
     */
    public function errorSummary($models, $options = [])
    {
        $this->htmlHlp->addCssClass($options, $this->errorSummaryCssClass);
        $options['encode'] = $this->encodeErrorSummary;
        return $this->htmlHlp->errorSummary($models, $options);
    }

    /**
     * Generates a form field.
     * A form field is associated with a model and an attribute. It contains a label, an input and an error message
     * and use them to interact with end users to collect their inputs for the attribute.
     * @param Model $model the data model.
     * @param string $attribute the attribute name or expression. See [[Html::getAttributeName()]] for the format
     * about attribute expression.
     * @param array $options the additional configurations for the field object. These are properties of [[ActiveField]]
     * or a subclass, depending on the value of [[fieldClass]].
     * @return ActiveField the created ActiveField object.
     * @see fieldConfig
     */
    public function field($model, $attribute, $options = [])
    {
        $config = $this->fieldConfig;
        if ($config instanceof \Closure) {
            $config = call_user_func($config, $model, $attribute);
        }
        if (!isset($config['class'])) {
            $config['class'] = $this->fieldClass;
        }

        return Reaction::create(ArrayHelper::merge($config, $options, [
            'model' => $model,
            'attribute' => $attribute,
            'form' => $this,
        ]));
    }

    /**
     * Begins a form field.
     * This method will create a new form field and returns its opening tag.
     * You should call [[endField()]] afterwards.
     * @param Model $model the data model.
     * @param string $attribute the attribute name or expression. See [[Html::getAttributeName()]] for the format
     * about attribute expression.
     * @param array $options the additional configurations for the field object.
     * @return string the opening tag.
     * @see endField()
     * @see field()
     */
    public function beginField($model, $attribute, $options = [])
    {
        $field = $this->field($model, $attribute, $options);
        $this->_fields[] = $field;
        return $field->begin();
    }

    /**
     * Ends a form field.
     * This method will return the closing tag of an active form field started by [[beginField()]].
     * @return string the closing tag of the form field.
     * @throws InvalidCallException if this method is called without a prior [[beginField()]] call.
     */
    public function endField()
    {
        $field = array_pop($this->_fields);
        if ($field instanceof ActiveField) {
            return $field->end();
        }

        throw new InvalidCallException('Mismatching endField() call.');
    }

    /**
     * Validates one or several models and returns an error message array indexed by the attribute IDs.
     * This is a helper method that simplifies the way of writing AJAX validation code.
     *
     * For example, you may use the following code in a controller action to respond
     * to an AJAX validation request:
     *
     * ```php
     * $model = new Post;
     * $model->load(Yii::$app->request->post());
     * if (Yii::$app->request->isAjax) {
     *     Yii::$app->response->format = Response::FORMAT_JSON;
     *     return ActiveForm::validate($model);
     * }
     * // ... respond to non-AJAX request ...
     * ```
     *
     * To validate multiple models, simply pass each model as a parameter to this method, like
     * the following:
     *
     * ```php
     * ActiveForm::validate($model1, $model2, ...);
     * ```
     *
     * @param Model $model the model to be validated.
     * @param mixed $attributes list of attributes that should be validated.
     * If this parameter is empty, it means any attribute listed in the applicable
     * validation rules should be validated.
     *
     * When this method is used to validate multiple models, this parameter will be interpreted
     * as a model.
     *
     * @return array the error message array indexed by the attribute IDs.
     */
    public static function validate($model, $attributes = null)
    {
        $result = [];
        if ($attributes instanceof Model) {
            // validating multiple models
            $models = func_get_args();
            $attributes = null;
        } else {
            $models = [$model];
        }
        /* @var $model Model */
        foreach ($models as $model) {
            $model->validate($attributes);
            foreach ($model->getErrors() as $attribute => $errors) {
                $result[Html::getInputId($model, $attribute)] = $errors;
            }
        }

        return $result;
    }

    /**
     * Validates an array of model instances and returns an error message array indexed by the attribute IDs.
     * This is a helper method that simplifies the way of writing AJAX validation code for tabular input.
     *
     * For example, you may use the following code in a controller action to respond
     * to an AJAX validation request:
     *
     * ```php
     * // ... load $models ...
     * if (Yii::$app->request->isAjax) {
     *     Yii::$app->response->format = Response::FORMAT_JSON;
     *     return ActiveForm::validateMultiple($models);
     * }
     * // ... respond to non-AJAX request ...
     * ```
     *
     * @param array $models an array of models to be validated.
     * @param mixed $attributes list of attributes that should be validated.
     * If this parameter is empty, it means any attribute listed in the applicable
     * validation rules should be validated.
     * @return array the error message array indexed by the attribute IDs.
     */
    public static function validateMultiple($models, $attributes = null)
    {
        $result = [];
        /* @var $model Model */
        foreach ($models as $i => $model) {
            $model->validate($attributes);
            foreach ($model->getErrors() as $attribute => $errors) {
                $result[Html::getInputId($model, "[$i]" . $attribute)] = $errors;
            }
        }

        return $result;
    }
}


<?php

namespace Bcol\Component\Type\Collection;

use Bcol\Component\Type\Cache;
use Bcol\Component\Type\NonEmptyString;
use Closure;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Criteria;
use Star\Component\Collection\TypedCollection;

/**
 * Class TypedCachedCollection
 *
 * @author Brice Colucci <brice.colucci@gmail.com>
 */
abstract class TypedCachedCollection extends TypedCollection
{
    /**
     * @var string
     */
    private $name;

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

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

    /**
     * @param string $name
     */
    public function __construct($name, Cache $cache, array $elements = null)
    {
        $this->name = new NonEmptyString($name);
        $this->name = $this->name->getValue();

        $this->cache = $cache;

        if (!is_array($elements)) {
            $elements = $this->cache->get($this->name);
        }
        if (!is_array($elements)) {
            $elements = array();
        }

        parent::__construct($this->getAllowedType(), $elements);
    }

    public function persist()
    {
        $this->cache->add($this->name, $this->toArray());
    }

    /**
     * @return Cache
     */
    public function getCache()
    {
        return $this->cache;
    }

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

    /**
     * @return ArrayCollection
     */
    private function getCollection()
    {
        return new ArrayCollection($this->getValues());
    }

    /**
     * @param callable $p
     *
     * @return \Doctrine\Common\Collections\Collection|static
     */
    public function filter(Closure $p)
    {
        $elements = $this->getCollection()->filter($p)->toArray();

        return new static($this->name, $this->cache, $elements);
    }

    /**
     * @param callable $p
     *
     * @return array
     */
    public function partition(Closure $p)
    {
        $partition = $this->getCollection()->partition($p);

        return array(
            new static($this->name, $this->cache, $partition[0]->toArray()),
            new static($this->name, $this->cache, $partition[1]->toArray()),
        );
    }

    /**
     * @param Criteria $criteria
     *
     * @return \Doctrine\Common\Collections\Collection|static
     */
    function matching(Criteria $criteria)
    {
        $elements = $this->getCollection()->matching($criteria)->toArray();

        return new static($this->name, $this->cache, $elements);
    }
}


<?php

namespace Nip\Config;

use ArrayAccess;
use Countable;
use Iterator;

/**
 * Class Repository
 * @package Nip\Config
 */
class Config implements Countable, Iterator, ArrayAccess
{
    /**
     * Whether modifications to configuration data are allowed.
     *
     * @var bool
     */
    protected $allowModifications;

    /**
     * All of the configuration items.
     *
     * @var array
     */
    protected $data = [];

    /**
     * Used when unsetting values during iteration to ensure we do not skip
     * the next element.
     *
     * @var bool
     */
    protected $skipNextIteration;

    /**
     * Create a new configuration repository.
     *
     * @param array $array
     * @param bool $allowModifications
     */
    public function __construct(array $array = [], $allowModifications = false)
    {
        $this->allowModifications = (bool) $allowModifications;

        foreach ($array as $key => $value) {
            $this->setDataItem($key, $value);
        }
    }

    /**
     * @param $name
     * @param $value
     * @return $this
     */
    protected function setDataItem($name, $value)
    {
        if (is_array($value)) {
            $value = new static($value, true);
        }
        if (null === $name) {
            $this->data[] = $value;
        } else {
            $this->data[$name] = $value;
        }

        return $this;
    }

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

    /**
     * Retrieve a value and return $default if there is no element set.
     *
     * @param  string $key
     * @param  string $default
     * @return mixed
     */
    public function get($key, $default = null)
    {
        if (strpos($key, '.') === false) {
            $value = $this->getByKey($key);
        } else {
            $value = $this->getByPath($key);
        }

        return $value === null ? $default : $value;
    }

    /**
     * @param string $key
     * @return mixed|null
     */
    public function getByKey($key)
    {
        if ($this->hasByKey($key)) {
            return $this->data[$key];
        }

        return null;
    }

    /**
     * Determine if the given configuration value exists.
     *
     * @param  string $key
     * @return bool
     */
    public function hasByKey($key)
    {
        return isset($this->data[$key]);
    }

    /**
     * @param string $path
     * @return string
     */
    protected function getByPath($path)
    {
        $segments = explode('.', $path);
        $value = $this;
        foreach ($segments as $segment) {
            if ($value->hasByKey($segment)) {
                $value = $value->getByKey($segment);
            } else {
                return null;
            }
        }

        return $value;
    }

    /**
     * @param $key
     * @return bool
     */
    public function __isset($key)
    {
        return $this->has($key);
    }

    /**
     * Determine if the given configuration value exists.
     *
     * @param  string $key
     * @return bool
     */
    public function has($key)
    {
        if (strpos($key, '.') === false) {
            return $this->hasByKey($key);
        }

        return $this->hasByPath($key);
    }

    /**
     * @param string $path
     * @return bool
     */
    public function hasByPath($path)
    {
        $segments = explode('.', $path);
        $value = $this;
        foreach ($segments as $segment) {
            if ($value->hasByKey($segment)) {
                $value = $value->getByKey($segment);
            } else {
                return false;
            }
        }

        return ($value !== null);
    }

    /**
     * Determine if the given configuration option exists.
     *
     * @param  string $key
     * @return bool
     */
    public function offsetExists($key)
    {
        return $this->has($key);
    }

    /**
     * Get a configuration option.
     *
     * @param  string $key
     * @return mixed
     */
    public function offsetGet($key)
    {
        return $this->get($key);
    }

    /**
     * Set a configuration option.
     *
     * @param  string $key
     * @param  mixed $value
     * @return void
     */
    public function offsetSet($key, $value)
    {
        $this->set($key, $value);
    }

    /**
     * @param $name
     * @param $value
     * @return $this
     * @throws Exception\RuntimeException
     */
    public function set($name, $value)
    {
        if ($this->isReadOnly()) {
            throw new Exception\RuntimeException('Config is read only');
        }

        return $this->setDataItem($name, $value);
    }

    /**
     * Returns whether this Config object is read only or not.
     *
     * @return bool
     */
    public function isReadOnly()
    {
        return !$this->allowModifications;
    }

    /**
     * Unset a configuration option.
     *
     * @param  string $key
     * @return void
     */
    public function offsetUnset($key)
    {
        $this->set($key, null);
    }

    /**
     * @param string $path
     * @return $this
     */
    public function mergeFile($path)
    {
        $data = Factory::fromFile($path, false);
        $config = new self($data, $this->allowModifications);
        return $this->merge($config);
    }

    /**
     * Merge another Config with this one.
     *
     * For duplicate keys, the following will be performed:
     * - Nested Configs will be recursively merged.
     * - Items in $merge with INTEGER keys will be appended.
     * - Items in $merge with STRING keys will overwrite current values.
     *
     * @param  self $merge
     * @return $this
     */
    public function merge(self $merge)
    {
        /** @var self $value */
        foreach ($merge as $key => $value) {
            if (array_key_exists($key, $this->data)) {
                if (is_int($key)) {
                    $this->data[] = $value;
                } elseif ($value instanceof self && $this->data[$key] instanceof self) {
                    $this->data[$key]->merge($value);
                } else {
                    if ($value instanceof self) {
                        $this->data[$key] = new static($value->toArray(), $this->allowModifications);
                    } else {
                        $this->data[$key] = $value;
                    }
                }
            } else {
                if ($value instanceof self) {
                    $this->data[$key] = new static($value->toArray(), $this->allowModifications);
                } else {
                    $this->data[$key] = $value;
                }
            }
        }

        return $this;
    }

    /**
     * Return an associative array of the stored data.
     *
     * @return array
     */
    public function toArray()
    {
        $array = [];
        $data = $this->data;
        /** @var self $value */
        foreach ($data as $key => $value) {
            if ($value instanceof self) {
                $array[$key] = $value->toArray();
            } else {
                $array[$key] = $value;
            }
        }

        return $array;
    }

    /**
     * count(): defined by Countable interface.
     *
     * @see    Countable::count()
     * @return int
     */
    public function count()
    {
        return count($this->data);
    }

    /**
     * current(): defined by Iterator interface.
     *
     * @see    Iterator::current()
     * @return mixed
     */
    public function current()
    {
        $this->skipNextIteration = false;

        return current($this->data);
    }

    /**
     * next(): defined by Iterator interface.
     *
     * @see    Iterator::next()
     * @return void
     */
    public function next()
    {
        if ($this->skipNextIteration) {
            $this->skipNextIteration = false;

            return;
        }
        next($this->data);
    }

    /**
     * rewind(): defined by Iterator interface.
     *
     * @see    Iterator::rewind()
     * @return void
     */
    public function rewind()
    {
        $this->skipNextIteration = false;
        reset($this->data);
    }

    /**
     * valid(): defined by Iterator interface.
     *
     * @see    Iterator::valid()
     * @return bool
     */
    public function valid()
    {
        return ($this->key() !== null);
    }

    /**
     * key(): defined by Iterator interface.
     *
     * @see    Iterator::key()
     * @return mixed
     */
    public function key()
    {
        return key($this->data);
    }
}


<?php

/*
 * This file is part of the SmarTwig (Twig Extension).
 *
 * (c) Omar Yepez <omar.yepez@yepsua.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Yepsua\SmarTwig\Twig\Extension;

use \YsJQuery as JQuery;
use \YsPNotify as Notify;
use \YsJLayout as Layout;
use \YsComponent as Component;

class UIAddonsExtension extends UIWidgetExtension {

  /**
   * Returns the token parser instance to add to the existing list.
   *
   * @return array An array of Twig_TokenParser instances
   */
  public function getTokenParsers() {
    return array(
        new \Yepsua\SmarTwig\Twig\TokenParser\BlockUITokenParser(),
        new \Yepsua\SmarTwig\Twig\TokenParser\BoxTokenParser(),
        new \Yepsua\SmarTwig\Twig\TokenParser\ColorpickerTokenParser(),
        new \Yepsua\SmarTwig\Twig\TokenParser\NotifyTokenParser(),
        new \Yepsua\SmarTwig\Twig\TokenParser\HotkeyTokenParser(),
        new \Yepsua\SmarTwig\Twig\TokenParser\IdleMonitorTokenParser(),
        new \Yepsua\SmarTwig\Twig\TokenParser\KeypadTokenParser(),
        new \Yepsua\SmarTwig\Twig\TokenParser\CalculatorTokenParser(),
        new \Yepsua\SmarTwig\Twig\TokenParser\LayoutTokenParser(),
        new \Yepsua\SmarTwig\Twig\TokenParser\MaskTokenParser(),
        new \Yepsua\SmarTwig\Twig\TokenParser\FormWizardTokenParser(),
        new \Yepsua\SmarTwig\Twig\TokenParser\AjaxFormTokenParser(),
        new \Yepsua\SmarTwig\Twig\TokenParser\ValidationTokenParser(),
        new \Yepsua\SmarTwig\Twig\TokenParser\BookletTokenParser(),
        new \Yepsua\SmarTwig\Twig\TokenParser\CycleTokenParser(),
        new \Yepsua\SmarTwig\Twig\TokenParser\RingTokenParser(),
        new \Yepsua\SmarTwig\Twig\TokenParser\UploadTokenParser(),
    );
  }

  /**
  * Returns a list of functions to add to the existing list.
  *
  * @return array An array of functions
  */
  public function getFunctions(){
    return array(
        'notify' => new \Twig_Function_Method($this, 'notify',array('is_safe' => array('html'))),
        'notify_error' => new \Twig_Function_Method($this, 'notifyError',array('is_safe' => array('html'))),
        'toggle_north' => new \Twig_Function_Method($this, 'toggleNorth',array('is_safe' => array('html'))),
        'toggle_south' => new \Twig_Function_Method($this, 'toggleSouth',array('is_safe' => array('html'))),
        'toggle_west' => new \Twig_Function_Method($this, 'toggleWest',array('is_safe' => array('html'))),
        'toggle_east' => new \Twig_Function_Method($this, 'toggleEast',array('is_safe' => array('html'))),
        'toggle_center' => new \Twig_Function_Method($this, 'toggleCenter',array('is_safe' => array('html'))),
        'animate_layout' => new \Twig_Function_Method($this, 'animateLayout',array('is_safe' => array('html'))),
        'component_render' => new \Twig_Function_Method($this, 'componentRender',array('is_safe' => array('html'))),
    );
  }

  public function notify($arg0 = "",$arg1 = null,$arg2 = null,$arg3 = null){
    $options = array();
    $options['pnotify_text'] = "";
    if(is_array($arg0)){
      $options = $arg0;
    }else{
      $options['pnotify_text'] = $arg0;
      if($arg1 !== null) $options['pnotify_title'] = $arg1;
      if($arg2 !== null) $options['pnotify_stack'] = $arg2;
      if($arg3 !== null) $options['pnotify_type'] = $arg3;
    }
    JQuery::usePlugin('pnotify');
    return str_replace(array("'",'"'),array("\'",'\''),Notify::build($options));
  }

  public function notifyError($arg0 = "",$arg1 = null,$arg2 = null){
    return $this->notify($arg0,$arg1,$arg2,Notify::ERROR_TYPE);
  }

  public function toggleNorth($layout,$region){
    JQuery::usePlugin('jLayout');
    return str_replace(array('"'),array('\''),Layout::toggleNorthLayout($layout,$region));
  }

  public function toggleSouth($layout,$region){
    JQuery::usePlugin('jLayout');
    return str_replace(array('"'),array('\''),Layout::toggleSouthLayout($layout,$region));
  }

  public function toggleWest($layout,$region){
    JQuery::usePlugin('jLayout');
    return str_replace(array('"'),array('\''),Layout::toggleWestLayout($layout,$region));
  }

  public function toggleEast($layout,$region){
    JQuery::usePlugin('jLayout');
    return str_replace(array('"'),array('\''),Layout::toggleEastLayout($layout,$region));
  }

  public function toggleCenter($layout,$region){
    JQuery::usePlugin('jLayout');
    return str_replace(array('"'),array('\''),Layout::toggleCenterLayout($layout,$region));
  }

  public function animateLayout($layout,$region, $effect = 'bounce'){
    JQuery::usePlugin('jLayout');
    return str_replace(array('"'),array('\''),Layout::effect($layout,$region,$effect));
  }

  public function componentRender(Component $component){
    return $component->draw();
  }

  /**
   * Returns the name of the extension.
   *
   * @return string The extension name
   */
  public function getName() {
    return 'ui.addons';
  }
}


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

namespace CarteBlanche\Model;

/**
 */
class DirectoryModel
{

    /**
     * The path of the directories root path
     */
    var $path       = '';

    /**
     * The name of the current directory
     */
    var $dirname    = null;

    /**
     * The content of the current directory
     */
    var $data       = null;

    /**
     * Directories names to ignore
     */
    var $ignore     = array( '.', '..', '.DS_Store' );

    /**
     * Returns TRUE if the directory exists
     */
    public function exists()
    {
        return isset($this->dirname) &&
            file_exists( $this->getPath().$this->dirname );
    }

    /**
     * Returns TRUE if the root path exists
     */
    public function pathExists()
    {
        return file_exists( $this->getPath() ) && is_dir( $this->getPath() );
    }

// ------------------------------------------
// Setters / Getters
// ------------------------------------------

    /**
     * Sets the global path
     *
     * @param string $path The root path
     */
    public function setPath($path = null)
    {
        if (!empty($path)) $this->path = rtrim($path, '/').'/';
    }

    /**
     * Gets the global path
     *
     * @return string The root path
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * Sets the directory name
     *
     * @param string $dirname The directory name
     */
    public function setDirname($dirname = null)
    {
        if (!empty($dirname)) $this->dirname = $dirname;
    }

    /**
     * Gets the directory name
     *
     * @return string The directory name
     */
    public function getDirname()
    {
        return $this->dirname;
    }

    /**
     * Gets the directory name transformed to be displayed as a title
     *
     * @return string The directory name transformed
     */
    public function getDisplayDirname()
    {
        $_dirname = $this->dirname;
        if (empty($_dirname)) $_dirname = basename($this->getPath());
        return ucwords( str_replace( '_', ' ', $_dirname ) );
    }

    /**
     * Sets the object data
     *
     * @param array $data An array of the object contents
     */
    public function setData($data = null)
    {
        $this->data = $data;
    }

    /**
     * Gets the object data
     *
     * @return array The object data
     */
    public function getData()
    {
        return $this->data;
    }

    /**
     * Scan the current directory
     *
     * @param bool $recursive Is the scan recursive ?
     * @return array
     */
    public function scanDir($recursive = false)
    {
        if (!$this->exists()) return false;
        $_dir = opendir($this->getPath().$this->dirname);
        $data = array();
        while ($entry = @readdir($_dir)) {
            if (!in_array($entry, $this->ignore)) {
                if (is_dir($this->getPath().$this->dirname.'/'.$entry)) {
                    if (true === $recursive){
                        $_new_dir = new DirectoryModel;
                        $_new_dir->setPath( $this->getPath().$this->dirname );
                        $_new_dir->setDirname( $entry );
                        $data[] = $_new_dir->scanDir( $recursive );
                    } else {
                        $data[] = $entry;
                    }
                } else {
                    $data[] = $entry;
                }
            }
        }
        closedir($_dir);
        return $data;
    }

// ------------------------------------------
// CRUD Methods
// ------------------------------------------

    /**
     * Must return the counting of all model objects
     */
    public function count()
    {
        $_new_dir = new DirectoryModel;
        $_new_dir->setPath( dirname($this->getPath()) );
        $_new_dir->setDirname( basename($this->getPath()) );
        return count($_new_dir->scanDir());
    }

    /**
     * Must return the list of all model objects
     */
    public function dump()
    {
        $_new_dir = new DirectoryModel;
        $_new_dir->setPath( dirname($this->getPath()) );
        $_new_dir->setDirname( basename($this->getPath()) );
        return $_new_dir->scanDir();
    }

    /**
     * Must return the content of the object
     *
     * @param int $id The primary ID of the object
     */
    public function read( $id=null )
    {
    }

    /**
     * Create a new object
     *
     * @param array $data An array of the object contents
     */
    public function create( $data=null )
    {
    }

    /**
     * Update an existing object
     *
     * @param int $id The primary ID of the object
     * @param array $data An array of the object contents
     */
    public function update( $id=null, $data=null )
    {
    }

    /**
     * Delete an object
     *
     * @param int $id The primary ID of the object
     */
    public function delete( $id=null )
    {
    }

}

// Endfile


<?php

namespace Ekyna\Bundle\CoreBundle\Doctrine\Repository;

use Doctrine\ORM\QueryBuilder;

/**
 * Trait DeletedAtFilterTrait
 * @package Ekyna\Bundle\CoreBundle\Doctrine\Repository
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
trait DeletedAtFilterTrait
{
    /**
     * @var bool
     */
    protected $_filterDeletedAt = true;

    /**
     * Sets if the query builder should be configured or not.
     *
     * @param $boolean
     */
    public function setFilterDeletedAt($boolean)
    {
        $this->_filterDeletedAt = (bool) $boolean;
    }

    /**
     * Configures the query builder.
     *
     * @param QueryBuilder $qb
     */
    public function addFilterDeletedAtClause(QueryBuilder $qb)
    {
        if ($this->_filterDeletedAt) {
            $qb->andWhere($qb->expr()->isNull($qb->getRootAliases()[0].'.deletedAt'));
        }
    }
}


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

namespace Skeetr\Runtime\Overrides;

use Skeetr\Runtime\Override;
use Skeetr\HTTP\Response;
use http;

/**
 * PHP impementation of header* functions
 *
 * Built-in functions:
 * [+] header_register_callback — Call a header function
 * [+] header_remove — Remove previously set headers
 * [+] header — Send a raw HTTP header
 * [+] headers_list — Returns a list of response headers sent (or ready to send)
 * [+] headers_sent — Checks if or where headers have been sent
 *
 * [+] = Implemented [-] = Original
 */
class Header extends Override
{
    private static $list;
    private static $code;
    private static $callback;

    /**
     * Send a raw HTTP header.
     *
     * @link http://www.php.net/manual/en/function.header.php
     *
     * @param  string  $string             The header string.
     * @param  boolean $replace            (optional) The optional replace parameter indicates whether the header should replace a previous similar header, or add a second header of the same type.
     * @param  boolean $http_response_code (optional) Forces the HTTP response code to the specified value.
     * @return boolean
     */
    final public static function header($string, $replace = true, $http_response_code = null)
    {
        if ( !$headers = http\Header::parse($string) ) Returns;
        $header = key($headers);

        if ( $replace || !isset(self::$list[$header]) ) {
            self::$list[$header] = array();
        }

        self::$list[$header][] = $string;

        if ( strtolower($header) == 'location' ) $http_response_code = 302;
        if ( $http_response_code ) self::$code = $http_response_code;
    }

    /**
     * Remove previously set headers.
     *
     * @link http://www.php.net/manual/en/function.header-remove.php
     *
     * @param string $name (optional) The header name to be removed. If empty removes all.
     */
    final public static function header_remove($name = null)
    {
        if ( $name ) unset(self::$list[$name]);
        else self::$list = array();
    }

    /**
     * Returns a list of response headers ready to send
     *
     * @link http://www.php.net/manual/en/function.headers_list.php
     *
     * @return array Returns a numerically indexed array of headers.
     */
    final public static function headers_list()
    {
        $results = array();
        foreach (self::$list as $headers) {
            $results = array_merge($results, $headers);
        }

        return $results;
    }

    /**
     * Call a header function
     *
     * @link http://www.php.net/manual/en/function.header-register-callback.php
     *
     * @param callback $callback Function called just before the headers are sent. It gets no parameters and the return value is ignored.
     */
    final public static function header_register_callback($callback)
    {
        if ( !is_callable($callback) ) return null;
        self::$callback = $callback;
    }

    /**
     * Checks if or where headers have been sent, allways returns false.
     *
     * @link http://www.php.net/manual/en/function.headers-sent.php
     *
     * @param  string  $file
     * @param  string  $line
     * @return boolean
     */
    final public static function headers_sent(&$file = null, &$line = null)
    {
        return false;
    }

    /**
     * {@inheritdoc}
     */
    public static function reset()
    {
        self::$list = array();
        self::$code = null;
        self::$callback;
    }

    /**
     * {@inheritdoc}
     */
    public static function values()
    {
        return get_class_vars(get_called_class());
    }
}