<?php
/*
 * This file is part of the Lucid Container package.
 *
 * (c) Mike Thorn <mthorn@devlucid.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace Lucid\Router;

/**
 *
 * The actual Router class. has setter methods for configuration, and ->parseRoute()
 *
 * @package Lucid.Router
 *
 */
class Router implements RouterInterface
{
    /**
     *
     * A string used to explode routes into parts
     *
     * @var string
     *
     */
    protected $delimiter = '/';

    /**
     *
     * An array of the default names of additional parameters found in a url
     *
     * @var array
     *
     */
    protected $parameterNames = ['id','name'];

    /**
     *
     * The prefix used for view classes to fully qualify them
     *
     * @var string
     *
     */
    protected $viewClassPrefix = 'App\\View\\';

    /**
     *
     * The suffix used for view classes to fully qualify them
     *
     * @var string
     *
     */
    protected $viewClassSuffix = '';

    /**
     *
     * The prefix used for controller classes to fully qualify them
     *
     * @var string
     *
     */
    protected $controllerClassPrefix = 'App\\Controller\\';

    /**
     *
     * The suffix used for controller classes to fully qualify them
     *
     * @var string
     *
     */
    protected $controllerClassSuffix = '';

    /**
     *
     * An array of allowed objects
     *
     * @var array
     *
     */
    protected $objects = [];

    /**
     *
     * An array of arrays of allowed methods for views. The key for the first array is the final
     * name of a specific view class, or '*'. The value of the inner array is the name of the
     * allowed method.
     *
     * @var array
     *
     */
    protected $viewMethods = [];

    /**
     *
     * An array of arrays of allowed methods for controllers. The key for the first array is the final
     * name of a specific controller class, or '*'. The value of the inner array is the name of the
     * allowed method.
     *
     * @var array
     *
     */
    protected $controllerMethods = [];

    /**
     *
     * Constructor.
     *
     */
    public function __construct()
    {
    }

    /**
     *
     * Sets the delimiter to use when exploding routes
     *
     * @return null
     *
     */
    public function setDelimiter(string $delimiter)
    {
        $this->delimiter = $delimiter;
    }

    /**
     *
     * Sets the default names for parameters found in the url when parsing
     *
     * @return null
     *
     */
    public function setParameterNames(...$names)
    {
        $this->parameterNames = $names;
    }

    /**
     *
     * Sets protected properties $viewClassPrefix and $viewClassSuffix
     *
     * @return null
     *
     */
    public function setViewClassPrefixSuffix(string $prefix = '', string $suffix = '')
    {
        $this->viewClassPrefix = $prefix;
        $this->viewClassSuffix = $suffix;
    }

    /**
     *
     * Sets protected properties $controllerClassPrefix and $controllerClassSuffix
     *
     * @return null
     *
     */
    public function setControllerClassPrefixSuffix(string $prefix = '', string $suffix = '')
    {
        $this->controllerClassPrefix = $prefix;
        $this->controllerClassSuffix = $suffix;
    }

    /**
     * Adds new objects to protected array $objects
     *
     * @return null
     *
     */
    public function allowObjects(...$allowedObjects)
    {
        foreach ($allowedObjects as $object) {
            $this->objects[$object] = true;
        }
    }

    /**
     * Adds allowed view methods for an object
     *
     * @return null
     *
     */
    public function allowViewMethods(string $object, ...$allowedMethods)
    {
        if (isset($this->viewMethods[$object]) === false) {
            $this->viewMethods[$object] = [];
        }

        foreach ($allowedMethods as $allowedMethod) {
            $this->viewMethods[$object][$allowedMethod] = true;
        }
    }

    /**
     * Adds allowed controller methods for an object
     *
     * @return null
     *
     */
    public function allowControllerMethods(string $object, ...$allowedMethods)
    {
        if (isset($this->controllerMethods[$object]) === false) {
            $this->controllerMethods[$object] = [];
        }

        foreach ($allowedMethods as $allowedMethod) {
            $this->controllerMethods[$object][$allowedMethod] = true;
        }
    }

    /**
     * Parses a string, determines what class and method the route should map to, and returns an
     * instance of Lucid\Router\Route
     *
     * @return Lucid\Router\Route
     *
     */
    public function parseRoute(string $route) : Route
    {
        # removing a leading / if necessary
        if (strpos($route, $this->delimiter) === 0){
            $route = substr($route, 1);
        }

        # split the route using the configured delimiter, throw an exception if there aren't
        # at least two parts to the route string
        $routeParts = explode($this->delimiter, $route);
        if (count($routeParts) < 2) {
            throw new Exception\IncorrectFormat($route, $this->delimiter);
        }

        $object = array_shift($routeParts);
        $method = array_shift($routeParts);
        $parameters = [];

        # loop over remaining parts of the route and build the parameters array
        $index = 0;
        while(count($routeParts) > 0){
            $name = $this->parameterNames[$index] ?? 'parameter'.$index;
            $parameters[$name] = array_shift($routeParts);
            $index++;
        }

        # Determine whether this refers to a view or a controller method. Start by disallowing both,
        # allow if we find matching rules
        $allowView       = false;
        $allowController = false;
        $viewClass       = $this->viewClassPrefix . $object . $this->viewClassSuffix;
        $controllerClass = $this->controllerClassPrefix . $object . $this->controllerClassSuffix;

        if (isset($this->objects[$object]) === false && isset($this->objects['*']) === false) {
            throw new Exception\ForbiddenObject($viewClass, $controllerClass);
        }

        # first, check if both classes exist. If neither exists, throw exception
        if (class_exists($viewClass) === false && class_exists($controllerClass) === false) {
            throw new Exception\ClassNotFound($viewClass, $controllerClass);
        }

        # if the view class exists, ensure that the method is allowed to be called
        if (class_exists($viewClass) === true) {
            if (isset($this->viewMethods[$object]) === true) {
                if (isset($this->viewMethods[$object][$method]) === true || isset($this->viewMethods[$object]['*']) === true) {
                    $allowView = true;
                }
            } elseif (isset($this->viewMethods['*']) === true) {
                if (isset($this->viewMethods['*'][$method]) === true || isset($this->viewMethods['*']['*']) === true) {
                    $allowView = true;
                }
            }
        }

        # if the controller class exists, ensure that the method is allowed to be called
        if (class_exists($controllerClass) === true) {
            if (isset($this->controllerMethods[$object]) === true) {
                if (isset($this->controllerMethods[$object][$method]) === true || isset($this->controllerMethods[$object]['*']) === true) {
                    $allowController = true;
                }
            } elseif (isset($this->controllerMethods['*']) === true) {
                if (isset($this->controllerMethods['*'][$method]) === true || isset($this->controllerMethods['*']['*']) === true) {
                    $allowController = true;
                }
            }
        }

        if ($allowController === false && $allowView === false) {
            throw new Exception\ForbiddenMethod($viewClass, $controllerClass, $method);
        }

        if (class_exists($controllerClass) === true && method_exists($controllerClass, $method) === false) {
            $allowController = false;
        }
        if (class_exists($viewClass) === true && method_exists($viewClass, $method) === false) {
            $allowView = false;
        }
        if ($allowController === false && $allowView === false) {
            throw new Exception\MethodNotFound($viewClass, $controllerClass, $method);
        }

        if ($allowController === true && $allowView === true) {
            throw new Exception\AmbiguousRequest($viewClass, $controllerClass, $method);
        }

        if ($allowView) {
            $routeObject = new Route($viewClass, $method, $parameters);
        } elseif ($allowController) {
            $routeObject = new Route($controllerClass, $method, $parameters);
        }

        return $routeObject;
    }
}


<?php

namespace Ekyna\Bundle\CoreBundle\Form\Type;

use Ekyna\Bundle\CoreBundle\Form\DataTransformer\HashToKeyValueArrayTransformer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\OptionsResolver\Options;

/**
 * Class KeyValueCollectionType
 * @package Ekyna\Bundle\CoreBundle\Form\Type
 * @author Bart van den Burg <bart@burgov.nl>
 * @see https://github.com/Burgov/KeyValueFormBundle/blob/master/Form/Type/KeyValueType.php
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
class KeyValueCollectionType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addModelTransformer(new HashToKeyValueArrayTransformer($options['use_container_object']));

        $builder->addEventListener(
            FormEvents::PRE_SET_DATA,
            function (FormEvent $e) {
                $input = $e->getData();
                if (null === $input) {
                    return;
                }
                $output = [];
                foreach ($input as $key => $value) {
                    $output[] = [
                        'key' => $key,
                        'value' => $value
                    ];
                }
                $e->setData($output);
            }, 1
        );
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver
            ->setDefaults([
                'type'                 => 'ekyna_key_value',
                'value_type'           => 'text',
                'value_options'        => [],
                'allowed_keys'         => null,
                'use_container_object' => false,
                'options'              => function (Options $options) {
                    return [
                        'value_type'    => $options['value_type'],
                        'value_options' => $options['value_options'],
                        'allowed_keys'  => $options['allowed_keys']
                    ];
                },
            ])
            ->setRequired(['value_type'])
            ->setAllowedTypes('allowed_keys', ['null', 'array'])
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return 'ekyna_collection';
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'ekyna_key_value_collection';
    }
}


<?php

namespace ifcanduela\db;

abstract class Query
{
    /** @var string[] */
    protected $table;

    /** @var string[] */
    protected $from;

    /** @var array */
    protected $conditions;

    /** @var bool */
    protected $changed = true;

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

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

    /**
     * Create a SELECT query.
     *
     * @param string $field,... List of fields to select
     * @return SelectQuery
     */
    public static function select(string ...$field)
    {
        return new SelectQuery(...$field);
    }

    /**
     * Create a SELECT COUNT(*) query.
     *
     * @return CountQuery
     */
    public static function count()
    {
        return new CountQuery();
    }

    /**
     * Create an INSERT query.
     *
     * @param string $table Name of the table to insert into
     * @return InsertQuery
     */
    public static function insert(string $table = null)
    {
        return new InsertQuery($table);
    }

    /**
     * Create an UPDATE query.
     *
     * @param  string $table Name of the table to update
     * @return UpdateQuery
     */
    public static function update(string $table = null)
    {
        return new UpdateQuery($table);
    }

    /**
     * Create a DELETE query.
     *
     * @param  string $table Name of the table to delete from
     * @return DeleteQuery
     */
    public static function delete(string $table = null)
    {
        return new DeleteQuery($table);
    }

    /**
     * Set the main table on which the query operates.
     *
     * This is the table that follows UPDATE TABLE, INSERT INTO and
     * DELETE FROM.
     *
     * @param  string $table
     * @return self
     */
    public function table(string $table)
    {
        $this->changed = true;
        $this->table = $table;

        return $this;
    }

    /**
     * Set the list of tables on which a SELECT query operates.
     *
     * @param  string $table,...
     * @return self
     */
    public function from(string ...$table)
    {
        $this->changed = true;
        $this->from = $table;

        return $this;
    }

    /**
     * Set the conditions for SELECT, UPDATE and DELETE queries.
     *
     * @param  array  $conditions
     * @return self
     */
    public function where(array $conditions)
    {
        $this->changed = true;
        $this->conditions = $conditions;

        return $this;
    }

    /**
     * Add conditions for SELECT, UPDATE and DELETE queries with an AND operator.
     *
     * @param  array  $conditions
     * @return self
     */
    public function andWhere(array $conditions)
    {
        $this->changed = true;

        if ($this->conditions) {
            $this->conditions = [
                'AND',
                $this->conditions,
                $conditions,
            ];
        } else {
            $this->conditions = $conditions;
        }

        return $this;
    }

    /**
     * Add conditions for SELECT, UPDATE and DELETE queries with an ON operator.
     *
     * @param  array  $conditions
     * @return self
     */
    public function orWhere(array $conditions)
    {
        $this->changed = true;

        if ($this->conditions) {
            $this->conditions = [
                'OR',
                $this->conditions,
                $conditions,
            ];
        } else {
            $this->conditions = $conditions;
        }

        return $this;
    }

    /**
     * Get the SQL query for a prepared statement.
     *
     * @return string
     */
    public function getSql()
    {
        if ($this->changed) {
            $this->build();
        }

        return $this->sql;
    }

    /**
     * Get the parameters for a prepared statement query.
     *
     * @return array
     */
    public function getParams()
    {
        if ($this->changed) {
            $this->build();
        }

        return $this->placeholders;
    }

    /**
     * Build the query,
     */
    abstract protected function build();
}


<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Filter
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Inflector.php 24593 2012-01-05 20:35:02Z matthew $
 */

/**
 * @see Zend_Filter
 * @see Zend_Filter_Interface
 */

/**
 * @see Zend_Loader_PluginLoader
 */

/**
 * Filter chain for string inflection
 *
 * @category   Zend
 * @package    Zend_Filter
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Filter_Inflector implements Zend_Filter_Interface
{
    /**
     * @var Zend_Loader_PluginLoader_Interface
     */
    protected $_pluginLoader = null;

    /**
     * @var string
     */
    protected $_target = null;

    /**
     * @var bool
     */
    protected $_throwTargetExceptionsOn = true;

    /**
     * @var string
     */
    protected $_targetReplacementIdentifier = ':';

    /**
     * @var array
     */
    protected $_rules = array();

    /**
     * Constructor
     *
     * @param string|array $options Options to set
     */
    public function __construct($options = null)
    {
        if ($options instanceof Zend_Config) {
            $options = $options->toArray();
        } else if (!is_array($options)) {
            $options = func_get_args();
            $temp    = array();

            if (!empty($options)) {
                $temp['target'] = array_shift($options);
            }

            if (!empty($options)) {
                $temp['rules'] = array_shift($options);
            }

            if (!empty($options)) {
                $temp['throwTargetExceptionsOn'] = array_shift($options);
            }

            if (!empty($options)) {
                $temp['targetReplacementIdentifier'] = array_shift($options);
            }

            $options = $temp;
        }

        $this->setOptions($options);
    }

    /**
     * Retreive PluginLoader
     *
     * @return Zend_Loader_PluginLoader_Interface
     */
    public function getPluginLoader()
    {
        if (!$this->_pluginLoader instanceof Zend_Loader_PluginLoader_Interface) {
            $this->_pluginLoader = new Zend_Loader_PluginLoader(array('Zend_Filter_' => 'Zend/Filter/'), __CLASS__);
        }

        return $this->_pluginLoader;
    }

    /**
     * Set PluginLoader
     *
     * @param Zend_Loader_PluginLoader_Interface $pluginLoader
     * @return Zend_Filter_Inflector
     */
    public function setPluginLoader(Zend_Loader_PluginLoader_Interface $pluginLoader)
    {
        $this->_pluginLoader = $pluginLoader;
        return $this;
    }

    /**
     * Use Zend_Config object to set object state
     *
     * @deprecated Use setOptions() instead
     * @param  Zend_Config $config
     * @return Zend_Filter_Inflector
     */
    public function setConfig(Zend_Config $config)
    {
        return $this->setOptions($config);
    }

    /**
     * Set options
     *
     * @param  array $options
     * @return Zend_Filter_Inflector
     */
    public function setOptions($options) {
        if ($options instanceof Zend_Config) {
            $options = $options->toArray();
        }

        // Set Präfix Path
        if (array_key_exists('filterPrefixPath', $options)) {
            if (!is_scalar($options['filterPrefixPath'])) {
                foreach ($options['filterPrefixPath'] as $prefix => $path) {
                    $this->addFilterPrefixPath($prefix, $path);
                }
            }
        }

        if (array_key_exists('throwTargetExceptionsOn', $options)) {
            $this->setThrowTargetExceptionsOn($options['throwTargetExceptionsOn']);
        }

        if (array_key_exists('targetReplacementIdentifier', $options)) {
            $this->setTargetReplacementIdentifier($options['targetReplacementIdentifier']);
        }

        if (array_key_exists('target', $options)) {
            $this->setTarget($options['target']);
        }

        if (array_key_exists('rules', $options)) {
            $this->addRules($options['rules']);
        }

        return $this;
    }

    /**
     * Convienence method to add prefix and path to PluginLoader
     *
     * @param string $prefix
     * @param string $path
     * @return Zend_Filter_Inflector
     */
    public function addFilterPrefixPath($prefix, $path)
    {
        $this->getPluginLoader()->addPrefixPath($prefix, $path);
        return $this;
    }

    /**
     * Set Whether or not the inflector should throw an exception when a replacement
     * identifier is still found within an inflected target.
     *
     * @param bool $throwTargetExceptions
     * @return Zend_Filter_Inflector
     */
    public function setThrowTargetExceptionsOn($throwTargetExceptionsOn)
    {
        $this->_throwTargetExceptionsOn = ($throwTargetExceptionsOn == true) ? true : false;
        return $this;
    }

    /**
     * Will exceptions be thrown?
     *
     * @return bool
     */
    public function isThrowTargetExceptionsOn()
    {
        return $this->_throwTargetExceptionsOn;
    }

    /**
     * Set the Target Replacement Identifier, by default ':'
     *
     * @param string $targetReplacementIdentifier
     * @return Zend_Filter_Inflector
     */
    public function setTargetReplacementIdentifier($targetReplacementIdentifier)
    {
        if ($targetReplacementIdentifier) {
            $this->_targetReplacementIdentifier = (string) $targetReplacementIdentifier;
        }

        return $this;
    }

    /**
     * Get Target Replacement Identifier
     *
     * @return string
     */
    public function getTargetReplacementIdentifier()
    {
        return $this->_targetReplacementIdentifier;
    }

    /**
     * Set a Target
     * ex: 'scripts/:controller/:action.:suffix'
     *
     * @param string
     * @return Zend_Filter_Inflector
     */
    public function setTarget($target)
    {
        $this->_target = (string) $target;
        return $this;
    }

    /**
     * Retrieve target
     *
     * @return string
     */
    public function getTarget()
    {
        return $this->_target;
    }

    /**
     * Set Target Reference
     *
     * @param reference $target
     * @return Zend_Filter_Inflector
     */
    public function setTargetReference(&$target)
    {
        $this->_target =& $target;
        return $this;
    }

    /**
     * SetRules() is the same as calling addRules() with the exception that it
     * clears the rules before adding them.
     *
     * @param array $rules
     * @return Zend_Filter_Inflector
     */
    public function setRules(Array $rules)
    {
        $this->clearRules();
        $this->addRules($rules);
        return $this;
    }

    /**
     * AddRules(): multi-call to setting filter rules.
     *
     * If prefixed with a ":" (colon), a filter rule will be added.  If not
     * prefixed, a static replacement will be added.
     *
     * ex:
     * array(
     *     ':controller' => array('CamelCaseToUnderscore','StringToLower'),
     *     ':action'     => array('CamelCaseToUnderscore','StringToLower'),
     *     'suffix'      => 'phtml'
     *     );
     *
     * @param array
     * @return Zend_Filter_Inflector
     */
    public function addRules(Array $rules)
    {
        $keys = array_keys($rules);
        foreach ($keys as $spec) {
            if ($spec[0] == ':') {
                $this->addFilterRule($spec, $rules[$spec]);
            } else {
                $this->setStaticRule($spec, $rules[$spec]);
            }
        }

        return $this;
    }

    /**
     * Get rules
     *
     * By default, returns all rules. If a $spec is provided, will return those
     * rules if found, false otherwise.
     *
     * @param  string $spec
     * @return array|false
     */
    public function getRules($spec = null)
    {
        if (null !== $spec) {
            $spec = $this->_normalizeSpec($spec);
            if (isset($this->_rules[$spec])) {
                return $this->_rules[$spec];
            }
            return false;
        }

        return $this->_rules;
    }

    /**
     * getRule() returns a rule set by setFilterRule(), a numeric index must be provided
     *
     * @param string $spec
     * @param int $index
     * @return Zend_Filter_Interface|false
     */
    public function getRule($spec, $index)
    {
        $spec = $this->_normalizeSpec($spec);
        if (isset($this->_rules[$spec]) && is_array($this->_rules[$spec])) {
            if (isset($this->_rules[$spec][$index])) {
                return $this->_rules[$spec][$index];
            }
        }
        return false;
    }

    /**
     * ClearRules() clears the rules currently in the inflector
     *
     * @return Zend_Filter_Inflector
     */
    public function clearRules()
    {
        $this->_rules = array();
        return $this;
    }

    /**
     * Set a filtering rule for a spec.  $ruleSet can be a string, Filter object
     * or an array of strings or filter objects.
     *
     * @param string $spec
     * @param array|string|Zend_Filter_Interface $ruleSet
     * @return Zend_Filter_Inflector
     */
    public function setFilterRule($spec, $ruleSet)
    {
        $spec = $this->_normalizeSpec($spec);
        $this->_rules[$spec] = array();
        return $this->addFilterRule($spec, $ruleSet);
    }

    /**
     * Add a filter rule for a spec
     *
     * @param mixed $spec
     * @param mixed $ruleSet
     * @return void
     */
    public function addFilterRule($spec, $ruleSet)
    {
        $spec = $this->_normalizeSpec($spec);
        if (!isset($this->_rules[$spec])) {
            $this->_rules[$spec] = array();
        }

        if (!is_array($ruleSet)) {
            $ruleSet = array($ruleSet);
        }

        if (is_string($this->_rules[$spec])) {
            $temp = $this->_rules[$spec];
            $this->_rules[$spec] = array();
            $this->_rules[$spec][] = $temp;
        }

        foreach ($ruleSet as $rule) {
            $this->_rules[$spec][] = $this->_getRule($rule);
        }

        return $this;
    }

    /**
     * Set a static rule for a spec.  This is a single string value
     *
     * @param string $name
     * @param string $value
     * @return Zend_Filter_Inflector
     */
    public function setStaticRule($name, $value)
    {
        $name = $this->_normalizeSpec($name);
        $this->_rules[$name] = (string) $value;
        return $this;
    }

    /**
     * Set Static Rule Reference.
     *
     * This allows a consuming class to pass a property or variable
     * in to be referenced when its time to build the output string from the
     * target.
     *
     * @param string $name
     * @param mixed $reference
     * @return Zend_Filter_Inflector
     */
    public function setStaticRuleReference($name, &$reference)
    {
        $name = $this->_normalizeSpec($name);
        $this->_rules[$name] =& $reference;
        return $this;
    }

    /**
     * Inflect
     *
     * @param  string|array $source
     * @return string
     */
    public function filter($source)
    {
        // clean source
        foreach ( (array) $source as $sourceName => $sourceValue) {
            $source[ltrim($sourceName, ':')] = $sourceValue;
        }

        $pregQuotedTargetReplacementIdentifier = preg_quote($this->_targetReplacementIdentifier, '#');
        $processedParts = array();

        foreach ($this->_rules as $ruleName => $ruleValue) {
            if (isset($source[$ruleName])) {
                if (is_string($ruleValue)) {
                    // overriding the set rule
                    $processedParts['#'.$pregQuotedTargetReplacementIdentifier.$ruleName.'#'] = str_replace('\\', '\\\\', $source[$ruleName]);
                } elseif (is_array($ruleValue)) {
                    $processedPart = $source[$ruleName];
                    foreach ($ruleValue as $ruleFilter) {
                        $processedPart = $ruleFilter->filter($processedPart);
                    }
                    $processedParts['#'.$pregQuotedTargetReplacementIdentifier.$ruleName.'#'] = str_replace('\\', '\\\\', $processedPart);
                }
            } elseif (is_string($ruleValue)) {
                $processedParts['#'.$pregQuotedTargetReplacementIdentifier.$ruleName.'#'] = str_replace('\\', '\\\\', $ruleValue);
            }
        }

        // all of the values of processedParts would have been str_replace('\\', '\\\\', ..)'d to disable preg_replace backreferences
        $inflectedTarget = preg_replace(array_keys($processedParts), array_values($processedParts), $this->_target);

        if ($this->_throwTargetExceptionsOn && (preg_match('#(?='.$pregQuotedTargetReplacementIdentifier.'[A-Za-z]{1})#', $inflectedTarget) == true)) {

            throw new Zend_Filter_Exception('A replacement identifier ' . $this->_targetReplacementIdentifier . ' was found inside the inflected target, perhaps a rule was not satisfied with a target source?  Unsatisfied inflected target: ' . $inflectedTarget);
        }

        return $inflectedTarget;
    }

    /**
     * Normalize spec string
     *
     * @param  string $spec
     * @return string
     */
    protected function _normalizeSpec($spec)
    {
        return ltrim((string) $spec, ':&');
    }

    /**
     * Resolve named filters and convert them to filter objects.
     *
     * @param  string $rule
     * @return Zend_Filter_Interface
     */
    protected function _getRule($rule)
    {
        if ($rule instanceof Zend_Filter_Interface) {
            return $rule;
        }

        $rule = (string) $rule;

        $className  = $this->getPluginLoader()->load($rule);
        $ruleObject = new $className();
        if (!$ruleObject instanceof Zend_Filter_Interface) {

            throw new Zend_Filter_Exception('No class named ' . $rule . ' implementing Zend_Filter_Interface could be found');
        }

        return $ruleObject;
    }
}


<?php

namespace Reaction\Web;

use Reaction;
use Reaction\Exceptions\InvalidConfigException;
use Reaction\Helpers\ArrayHelper;
use Reaction\Helpers\Html;
use Reaction\Helpers\Json;

/**
 * View represents a view object in the MVC pattern.
 *
 * View provides a set of methods (e.g. [[render()]]) for rendering purpose.
 *
 * View is configured as an application component in [[\yii\base\Application]] by default.
 * You can access that instance via `Yii::$app->view`.
 *
 * You can modify its configuration by adding an array to your application config under `components`
 * as it is shown in the following example:
 *
 * ```php
 * 'view' => [
 *     'theme' => 'app\themes\MyTheme',
 *     'renderers' => [
 *         // you may add Smarty or Twig renderer here
 *     ]
 *     // ...
 * ]
 * ```
 *
 * For more details and usage information on View, see the [guide article on views](guide:structure-views).
 *
 * @property \Reaction\Web\AssetManager $assetManager The asset manager. Defaults to the "assetManager" application
 * component.
 *
 * Borrowed from yii2
 */
class View extends \Reaction\Base\View implements Reaction\Base\RequestAppComponentInterface
{
    use Reaction\Helpers\Request\RequestAppHelpersExtractedTrait;

    /**
     * @event Event an event that is triggered by [[beginBody()]].
     */
    const EVENT_BEGIN_BODY = 'beginBody';
    /**
     * @event Event an event that is triggered by [[endBody()]].
     */
    const EVENT_END_BODY = 'endBody';
    /**
     * The location of registered JavaScript code block or files.
     * This means the location is in the head section.
     */
    const POS_HEAD = 1;
    /**
     * The location of registered JavaScript code block or files.
     * This means the location is at the beginning of the body section.
     */
    const POS_BEGIN = 2;
    /**
     * The location of registered JavaScript code block or files.
     * This means the location is at the end of the body section.
     */
    const POS_END = 3;
    /**
     * The location of registered JavaScript code block.
     * This means the JavaScript code block will be enclosed within `jQuery(document).ready()`.
     */
    const POS_READY = 4;
    /**
     * The location of registered JavaScript code block.
     * This means the JavaScript code block will be enclosed within `jQuery(window).load()`.
     */
    const POS_LOAD = 5;
    /**
     * This is internally used as the placeholder for receiving the content registered for the head section.
     */
    const PH_HEAD = '<![CDATA[REACTION-BLOCK-HEAD]]>';
    /**
     * This is internally used as the placeholder for receiving the content registered for the beginning of the body section.
     */
    const PH_BODY_BEGIN = '<![CDATA[REACTION-BLOCK-BODY-BEGIN]]>';
    /**
     * This is internally used as the placeholder for receiving the content registered for the end of the body section.
     */
    const PH_BODY_END = '<![CDATA[REACTION-BLOCK-BODY-END]]>';

    /**
     * @var Reaction\RequestApplicationInterface  Current request application
     */
    public $app;
    /**
     * @var AssetBundle[] list of the registered asset bundles. The keys are the bundle names, and the values
     * are the registered [[AssetBundle]] objects.
     * @see registerAssetBundle()
     */
    public $assetBundles = [];
    /**
     * @var string the page title
     */
    public $title;
    /**
     * @var array the registered meta tags.
     * @see registerMetaTag()
     */
    public $metaTags = [];
    /**
     * @var array the registered link tags.
     * @see registerLinkTag()
     */
    public $linkTags = [];
    /**
     * @var array the registered CSS code blocks.
     * @see registerCss()
     */
    public $css = [];
    /**
     * @var array the registered CSS files.
     * @see registerCssFile()
     */
    public $cssFiles = [];
    /**
     * @var array the registered JS code blocks
     * @see registerJs()
     */
    public $js = [];
    /**
     * @var array the registered JS files.
     * @see registerJsFile()
     */
    public $jsFiles = [];

    private $_assetManager;

    /**
     * Marks the position of an HTML head section.
     */
    public function head()
    {
        echo self::PH_HEAD;
    }

    /**
     * Marks the beginning of an HTML body section.
     */
    public function beginBody()
    {
        echo self::PH_BODY_BEGIN;
        $this->emit(self::EVENT_BEGIN_BODY, [$this]);
    }

    /**
     * Marks the ending of an HTML body section.
     */
    public function endBody()
    {
        $this->emit(self::EVENT_END_BODY, [$this]);
        echo self::PH_BODY_END;

        foreach (array_keys($this->assetBundles) as $bundle) {
            $this->registerAssetFiles($bundle);
        }
    }

    /**
     * Marks the ending of an HTML page.
     * @param bool $ajaxMode whether the view is rendering in AJAX mode.
     * If true, the JS scripts registered at [[POS_READY]] and [[POS_LOAD]] positions
     * will be rendered at the end of the view like normal scripts.
     */
    public function endPage($ajaxMode = false)
    {
        $this->emit(self::EVENT_END_PAGE, [$this]);

        $content = ob_get_clean();

        echo strtr($content, [
            self::PH_HEAD => $this->renderHeadHtml(),
            self::PH_BODY_BEGIN => $this->renderBodyBeginHtml(),
            self::PH_BODY_END => $this->renderBodyEndHtml($ajaxMode),
        ]);

        $this->clear();
    }

    /**
     * Renders a view in response to an AJAX request.
     *
     * This method is similar to [[render()]] except that it will surround the view being rendered
     * with the calls of [[beginPage()]], [[head()]], [[beginBody()]], [[endBody()]] and [[endPage()]].
     * By doing so, the method is able to inject into the rendering result with JS/CSS scripts and files
     * that are registered with the view.
     *
     * @param string $view the view name. Please refer to [[render()]] on how to specify this parameter.
     * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
     * @param object $context the context that the view should use for rendering the view. If null,
     * existing [[context]] will be used.
     * @return string the rendering result
     * @see render()
     */
    public function renderAjax($view, $params = [], $context = null)
    {
        $viewFile = $this->findViewFile($view, $context);

        ob_start();
        ob_implicit_flush(false);

        $this->beginPage();
        $this->head();
        $this->beginBody();
        echo $this->renderFile($viewFile, $params, $context);
        $this->endBody();
        $this->endPage(true);

        return ob_get_clean();
    }

    /**
     * Registers the asset manager being used by this view object.
     * @return \Reaction\Web\AssetManager the asset manager. Defaults to the "assetManager" application component.
     */
    public function getAssetManager()
    {
        return $this->_assetManager ? $this->_assetManager : $this->app->assetManager;
    }

    /**
     * Sets the asset manager.
     * @param \Reaction\Web\AssetManager $value the asset manager
     */
    public function setAssetManager($value)
    {
        $this->_assetManager = $value;
    }

    /**
     * Clears up the registered meta tags, link tags, css/js scripts and files.
     */
    public function clear()
    {
        $this->metaTags = [];
        $this->linkTags = [];
        $this->css = [];
        $this->cssFiles = [];
        $this->js = [];
        $this->jsFiles = [];
        $this->assetBundles = [];
    }

    /**
     * Registers all files provided by an asset bundle including depending bundles files.
     * Removes a bundle from [[assetBundles]] once files are registered.
     * @param string $name name of the bundle to register
     */
    protected function registerAssetFiles($name)
    {
        if (!isset($this->assetBundles[$name])) {
            return;
        }
        $bundle = $this->assetBundles[$name];
        if ($bundle) {
            foreach ($bundle->depends as $dep) {
                $this->registerAssetFiles($dep);
            }
            $bundle->registerAssetFiles($this);
        }
        unset($this->assetBundles[$name]);
    }

    /**
     * Registers the named asset bundle.
     * All dependent asset bundles will be registered.
     * @param string $name the class name of the asset bundle (without the leading backslash)
     * @param int|null $position if set, this forces a minimum position for javascript files.
     * This will adjust depending assets javascript file position or fail if requirement can not be met.
     * If this is null, asset bundles position settings will not be changed.
     * See [[registerJsFile]] for more details on javascript position.
     * @return AssetBundle the registered asset bundle instance
     * @throws InvalidConfigException if the asset bundle does not exist or a circular dependency is detected
     */
    public function registerAssetBundle($name, $position = null)
    {
        if (!isset($this->assetBundles[$name])) {
            $am = $this->getAssetManager();
            $bundle = $am->getBundle($name);
            $this->assetBundles[$name] = false;
            // register dependencies
            $pos = isset($bundle->jsOptions['position']) ? $bundle->jsOptions['position'] : null;
            foreach ($bundle->depends as $dep) {
                $this->registerAssetBundle($dep, $pos);
            }
            $this->assetBundles[$name] = $bundle;
        } elseif ($this->assetBundles[$name] === false) {
            throw new InvalidConfigException("A circular dependency is detected for bundle '$name'.");
        } else {
            $bundle = $this->assetBundles[$name];
        }

        if ($position !== null) {
            $pos = isset($bundle->jsOptions['position']) ? $bundle->jsOptions['position'] : null;
            if ($pos === null) {
                $bundle->jsOptions['position'] = $pos = $position;
            } elseif ($pos > $position) {
                throw new InvalidConfigException("An asset bundle that depends on '$name' has a higher javascript file position configured than '$name'.");
            }
            // update position for all dependencies
            foreach ($bundle->depends as $dep) {
                $this->registerAssetBundle($dep, $pos);
            }
        }

        return $bundle;
    }

    /**
     * Registers a meta tag.
     *
     * For example, a description meta tag can be added like the following:
     *
     * ```php
     * $view->registerMetaTag([
     *     'name' => 'description',
     *     'content' => 'This website is about funny raccoons.'
     * ]);
     * ```
     *
     * will result in the meta tag `<meta name="description" content="This website is about funny raccoons.">`.
     *
     * @param array $options the HTML attributes for the meta tag.
     * @param string $key the key that identifies the meta tag. If two meta tags are registered
     * with the same key, the latter will overwrite the former. If this is null, the new meta tag
     * will be appended to the existing ones.
     */
    public function registerMetaTag($options, $key = null)
    {
        if ($key === null) {
            $this->metaTags[] = Html::tag('meta', '', $options);
        } else {
            $this->metaTags[$key] = Html::tag('meta', '', $options);
        }
    }

    /**
     * Registers CSRF meta tags.
     * They are rendered dynamically to retrieve a new CSRF token for each request.
     *
     * ```php
     * $view->registerCsrfMetaTags();
     * ```
     *
     * The above code will result in `<meta name="csrf-param" content="[yii\web\Request::$csrfParam]">`
     * and `<meta name="csrf-token" content="tTNpWKpdy-bx8ZmIq9R72...K1y8IP3XGkzZA==">` added to the page.
     *
     * Note: Hidden CSRF input of ActiveForm will be automatically refreshed by calling `window.yii.refreshCsrfToken()`
     * from `yii.js`.
     */
    public function registerCsrfMetaTags()
    {
        $this->metaTags['csrf_meta_tags'] = $this->renderDynamic('return Reaction\Helpers\Html::csrfMetaTags();');
    }

    /**
     * Registers a link tag.
     *
     * For example, a link tag for a custom [favicon](http://www.w3.org/2005/10/howto-favicon)
     * can be added like the following:
     *
     * ```php
     * $view->registerLinkTag(['rel' => 'icon', 'type' => 'image/png', 'href' => '/myicon.png']);
     * ```
     *
     * which will result in the following HTML: `<link rel="icon" type="image/png" href="/myicon.png">`.
     *
     * **Note:** To register link tags for CSS stylesheets, use [[registerCssFile()]] instead, which
     * has more options for this kind of link tag.
     *
     * @param array $options the HTML attributes for the link tag.
     * @param string $key the key that identifies the link tag. If two link tags are registered
     * with the same key, the latter will overwrite the former. If this is null, the new link tag
     * will be appended to the existing ones.
     */
    public function registerLinkTag($options, $key = null)
    {
        if ($key === null) {
            $this->linkTags[] = Html::tag('link', '', $options);
        } else {
            $this->linkTags[$key] = Html::tag('link', '', $options);
        }
    }

    /**
     * Registers a CSS code block.
     * @param string $css the content of the CSS code block to be registered
     * @param array $options the HTML attributes for the `<style>`-tag.
     * @param string $key the key that identifies the CSS code block. If null, it will use
     * $css as the key. If two CSS code blocks are registered with the same key, the latter
     * will overwrite the former.
     */
    public function registerCss($css, $options = [], $key = null)
    {
        $key = $key ?: md5($css);
        $this->css[$key] = Html::style($css, $options);
    }

    /**
     * Registers a CSS file.
     *
     * This method should be used for simple registration of CSS files. If you want to use features of
     * [[AssetManager]] like appending timestamps to the URL and file publishing options, use [[AssetBundle]]
     * and [[registerAssetBundle()]] instead.
     *
     * @param string $url the CSS file to be registered.
     * @param array $options the HTML attributes for the link tag. Please refer to [[Html::cssFile()]] for
     * the supported options. The following options are specially handled and are not treated as HTML attributes:
     *
     * - `depends`: array, specifies the names of the asset bundles that this CSS file depends on.
     *
     * @param string $key the key that identifies the CSS script file. If null, it will use
     * $url as the key. If two CSS files are registered with the same key, the latter
     * will overwrite the former.
     */
    public function registerCssFile($url, $options = [], $key = null)
    {
        $url = \Reaction::$app->getAlias($url);
        $key = $key ?: $url;

        $depends = ArrayHelper::remove($options, 'depends', []);

        if (empty($depends)) {
            $this->cssFiles[$key] = Html::cssFile($url, $options);
        } else {
            $this->getAssetManager()->bundles[$key] = \Reaction::create([
                'class' => AssetBundle::class,
                'baseUrl' => '',
                'css' => [strncmp($url, '//', 2) === 0 ? $url : ltrim($url, '/')],
                'cssOptions' => $options,
                'depends' => (array)$depends,
            ]);
            $this->registerAssetBundle($key);
        }
    }

    /**
     * Registers a JS code block.
     * @param string $js the JS code block to be registered
     * @param int $position the position at which the JS script tag should be inserted
     * in a page. The possible values are:
     *
     * - [[POS_HEAD]]: in the head section
     * - [[POS_BEGIN]]: at the beginning of the body section
     * - [[POS_END]]: at the end of the body section
     * - [[POS_LOAD]]: enclosed within jQuery(window).load().
     *   Note that by using this position, the method will automatically register the jQuery js file.
     * - [[POS_READY]]: enclosed within jQuery(document).ready(). This is the default value.
     *   Note that by using this position, the method will automatically register the jQuery js file.
     *
     * @param string $key the key that identifies the JS code block. If null, it will use
     * $js as the key. If two JS code blocks are registered with the same key, the latter
     * will overwrite the former.
     */
    public function registerJs($js, $position = self::POS_READY, $key = null)
    {
        $key = $key ?: md5($js);
        $this->js[$position][$key] = $js;
        if ($position === self::POS_READY || $position === self::POS_LOAD) {
            Reaction\Assets\JqueryAsset::register($this);
        }
    }

    /**
     * Registers a JS file.
     *
     * This method should be used for simple registration of JS files. If you want to use features of
     * [[AssetManager]] like appending timestamps to the URL and file publishing options, use [[AssetBundle]]
     * and [[registerAssetBundle()]] instead.
     *
     * @param string $url the JS file to be registered.
     * @param array $options the HTML attributes for the script tag. The following options are specially handled
     * and are not treated as HTML attributes:
     *
     * - `depends`: array, specifies the names of the asset bundles that this JS file depends on.
     * - `position`: specifies where the JS script tag should be inserted in a page. The possible values are:
     *     * [[POS_HEAD]]: in the head section
     *     * [[POS_BEGIN]]: at the beginning of the body section
     *     * [[POS_END]]: at the end of the body section. This is the default value.
     *
     * Please refer to [[Html::jsFile()]] for other supported options.
     *
     * @param string $key the key that identifies the JS script file. If null, it will use
     * $url as the key. If two JS files are registered with the same key at the same position, the latter
     * will overwrite the former. Note that position option takes precedence, thus files registered with the same key,
     * but different position option will not override each other.
     */
    public function registerJsFile($url, $options = [], $key = null)
    {
        $url = \Reaction::$app->getAlias($url);
        $key = $key ?: $url;
        $helpers = $this->app->helpers;

        $depends = ArrayHelper::remove($options, 'depends', []);

        if (empty($depends)) {
            $position = ArrayHelper::remove($options, 'position', self::POS_END);
            $this->jsFiles[$position][$key] = $helpers->html->jsFile($url, $options);
        } else {
            $this->getAssetManager()->bundles[$key] = Reaction::create([
                'class' => AssetBundle::class,
                'baseUrl' => '',
                'js' => [strncmp($url, '//', 2) === 0 ? $url : ltrim($url, '/')],
                'jsOptions' => $options,
                'depends' => (array)$depends,
            ]);
            $this->registerAssetBundle($key);
        }
    }

    /**
     * Registers a JS code block defining a variable. The name of variable will be
     * used as key, preventing duplicated variable names.
     *
     * @param string $name Name of the variable
     * @param array|string $value Value of the variable
     * @param int $position the position in a page at which the JavaScript variable should be inserted.
     * The possible values are:
     *
     * - [[POS_HEAD]]: in the head section. This is the default value.
     * - [[POS_BEGIN]]: at the beginning of the body section.
     * - [[POS_END]]: at the end of the body section.
     * - [[POS_LOAD]]: enclosed within jQuery(window).load().
     *   Note that by using this position, the method will automatically register the jQuery js file.
     * - [[POS_READY]]: enclosed within jQuery(document).ready().
     *   Note that by using this position, the method will automatically register the jQuery js file.
     */
    public function registerJsVar($name, $value, $position = self::POS_HEAD)
    {
        $js = sprintf('var %s = %s;', $name, Json::htmlEncode($value));
        $this->registerJs($js, $position, $name);
    }

    /**
     * Renders the content to be inserted in the head section.
     * The content is rendered using the registered meta tags, link tags, CSS/JS code blocks and files.
     * @return string the rendered content
     */
    protected function renderHeadHtml()
    {
        $lines = [];
        if (!empty($this->metaTags)) {
            $lines[] = implode("\n", $this->metaTags);
        }

        if (!empty($this->linkTags)) {
            $lines[] = implode("\n", $this->linkTags);
        }
        if (!empty($this->cssFiles)) {
            $lines[] = implode("\n", $this->cssFiles);
        }
        if (!empty($this->css)) {
            $lines[] = implode("\n", $this->css);
        }
        if (!empty($this->jsFiles[self::POS_HEAD])) {
            $lines[] = implode("\n", $this->jsFiles[self::POS_HEAD]);
        }
        if (!empty($this->js[self::POS_HEAD])) {
            $lines[] = Html::script(implode("\n", $this->js[self::POS_HEAD]));
        }

        return empty($lines) ? '' : implode("\n", $lines);
    }

    /**
     * Renders the content to be inserted at the beginning of the body section.
     * The content is rendered using the registered JS code blocks and files.
     * @return string the rendered content
     */
    protected function renderBodyBeginHtml()
    {
        $lines = [];
        if (!empty($this->jsFiles[self::POS_BEGIN])) {
            $lines[] = implode("\n", $this->jsFiles[self::POS_BEGIN]);
        }
        if (!empty($this->js[self::POS_BEGIN])) {
            $lines[] = Html::script(implode("\n", $this->js[self::POS_BEGIN]));
        }

        return empty($lines) ? '' : implode("\n", $lines);
    }

    /**
     * Renders the content to be inserted at the end of the body section.
     * The content is rendered using the registered JS code blocks and files.
     * @param bool $ajaxMode whether the view is rendering in AJAX mode.
     * If true, the JS scripts registered at [[POS_READY]] and [[POS_LOAD]] positions
     * will be rendered at the end of the view like normal scripts.
     * @return string the rendered content
     */
    protected function renderBodyEndHtml($ajaxMode)
    {
        $lines = [];

        if (!empty($this->jsFiles[self::POS_END])) {
            $lines[] = implode("\n", $this->jsFiles[self::POS_END]);
        }

        if ($ajaxMode) {
            $scripts = [];
            if (!empty($this->js[self::POS_END])) {
                $scripts[] = implode("\n", $this->js[self::POS_END]);
            }
            if (!empty($this->js[self::POS_READY])) {
                $scripts[] = implode("\n", $this->js[self::POS_READY]);
            }
            if (!empty($this->js[self::POS_LOAD])) {
                $scripts[] = implode("\n", $this->js[self::POS_LOAD]);
            }
            if (!empty($scripts)) {
                $lines[] = Html::script(implode("\n", $scripts));
            }
        } else {
            if (!empty($this->js[self::POS_END])) {
                $lines[] = Html::script(implode("\n", $this->js[self::POS_END]));
            }
            if (!empty($this->js[self::POS_READY])) {
                $js = "jQuery(function ($) {\n" . implode("\n", $this->js[self::POS_READY]) . "\n});";
                $lines[] = Html::script($js);
            }
            if (!empty($this->js[self::POS_LOAD])) {
                $js = "jQuery(window).on('load', function () {\n" . implode("\n", $this->js[self::POS_LOAD]) . "\n});";
                $lines[] = Html::script($js);
            }
        }

        return empty($lines) ? '' : implode("\n", $lines);
    }
}


<?php namespace Ordercloud\Entities\Organisations;

use JsonSerializable;
use Ordercloud\Entities\Transactions\Currency;

class Organisation extends OrganisationShort implements JsonSerializable
{
    /**
     * @var array|OrganisationType[]
     * @reflectType Ordercloud\Entities\Organisations\OrganisationType
     */
    private $types;
    /**
     * @var array|OrganisationIndustry[]
     * @reflectType Ordercloud\Entities\Organisations\OrganisationIndustry
     */
    private $industries;
    /**
     * @var OrganisationProfile
     */
    private $profile;
    /**
     * @var array|OrganisationOperatingHours[]
     * @reflectType Ordercloud\Entities\Organisations\OrganisationOperatingHours
     */
    private $operatingHours;
    /**
     * @var int
     */
    private $ordersHash;
    /**
     * @var OrganisationStatus
     */
    private $status;
    /**
     * @var int
     */
    private $lastOnline;
    /**
     * @var boolean
     */
    private $delivering;
    /**
     * @var boolean
     */
    private $open;
    /**
     * @var boolean
     */
    private $registeredDirectly;
    /**
     * @var Currency
     */
    private $currency;

    /**
     * @param int                          $id
     * @param string                       $name
     * @param string                       $code
     * @param OrganisationType[]           $types
     * @param OrganisationIndustry[]       $industries
     * @param OrganisationProfile          $profile
     * @param OrganisationOperatingHours[] $operatingHours
     * @param int                          $ordersHash
     * @param OrganisationStatus|null      $status
     * @param int                          $lastOnline
     * @param boolean                      $delivering
     * @param boolean                      $open
     * @param boolean                      $registeredDirectly
     * @param Currency                     $currency
     */
    public function __construct($id, $name, $code, array $types, array $industries, OrganisationProfile $profile, array $operatingHours, $ordersHash, OrganisationStatus $status = null, $lastOnline, $delivering, $open, $registeredDirectly, Currency $currency)
    {
        parent::__construct($id, $name, $code);
        $this->types = $types;
        $this->industries = $industries;
        $this->profile = $profile;
        $this->operatingHours = $operatingHours;
        $this->ordersHash = $ordersHash;
        $this->status = $status;
        $this->lastOnline = $lastOnline;
        $this->delivering = $delivering;
        $this->open = $open;
        $this->registeredDirectly = $registeredDirectly;
        $this->currency = $currency;
    }

    /**
     * @return array|OrganisationType[]
     */
    public function getTypes()
    {
        return $this->types;
    }

    /**
     * @return array|OrganisationIndustry[]
     */
    public function getIndustries()
    {
        return $this->industries;
    }

    /**
     * @return OrganisationProfile
     */
    public function getProfile()
    {
        return $this->profile;
    }

    /**
     * @return array|OrganisationOperatingHours[]
     */
    public function getOperatingHours()
    {
        return $this->operatingHours;
    }

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

    /**
     * @return OrganisationStatus
     */
    public function getStatus()
    {
        return $this->status;
    }

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

    /**
     * @return boolean
     */
    public function isDelivering()
    {
        return $this->delivering;
    }

    /**
     * @return boolean
     */
    public function isOpen()
    {
        return $this->open;
    }

    /**
     * @return boolean
     */
    public function isRegisteredDirectly()
    {
        return $this->registeredDirectly;
    }

    /**
     * @return Currency
     */
    public function getCurrency()
    {
        return $this->currency;
    }

    /**
     * Specify data which should be serialized to JSON
     */
    public function jsonSerialize()
    {
        $json = parent::jsonSerialize();

        $json['types'] = $this->getTypes();
        $json['industries'] = $this->getIndustries();
        $json['profile'] = $this->getProfile();
        $json['operatingHours'] = $this->getOperatingHours();
        $json['ordersHash'] = $this->getOrdersHash();
        $json['status'] = $this->getStatus();
        $json['lastOnline'] = $this->getLastOnline();
        $json['delivering'] = $this->isDelivering();
        $json['open'] = $this->isOpen();
        $json['registeredDirectly'] = $this->isRegisteredDirectly();
        $json['currency'] = $this->getCurrency();

        return $json;
    }
}


<?php
/**
 * AdroStatic.
 *
 * @copyright Copyright (c) 2017 Alejandro Morelos
 *
 * @link      https://github.com/adrorocker/adrostatic
 */

namespace AdroStatic\Content;

use AdroStatic\Util;
use SplFileInfo;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Yaml;

class Parser
{
    const PATTERN = '^\s*(?:<!--|---|\+++){1}[\n\r\s]*(.*?)[\n\r\s]*(?:-->|---|\+++){1}[\s\n\r]*(.*)$';

    /**
     * @var SplFileInfo
     */
    protected $file;

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

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

    /**
     * Constructor.
     *
     * @param SplFileInfo $file
     */
    public function __construct(SplFileInfo $file)
    {
        $this->file = $file;
    }

    /**
     * Parse the contents of the file.
     *
     * @throws \RuntimeException
     *
     * @return $this
     */
    public function parse()
    {
        preg_match(
            '/'.self::PATTERN.'/s',
            Util::filesystem()->read($this->file->getPathName()),
            $matches
        );

        if (!$matches) {
            $this->body = Util::filesystem()->read($this->file->getPathName());

            return $this;
        }

        try {
            $this->attributes = Yaml::parse($matches[1]);
        } catch (ParseException $e) {
        }

        $this->body = trim($matches[2]);

        return $this;
    }

    /**
     * Get attributes.
     *
     * @return array
     */
    public function getAttributes()
    {
        return $this->attributes;
    }

    /**
     * Get body.
     *
     * @return string
     */
    public function getBody()
    {
        return $this->body;
    }

    /**
     * Get file path.
     *
     * @return string
     */
    public function getPath()
    {
        return $this->file->getPathName();
    }
}