<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license. For more information, see
 * <http://www.doctrine-project.org>.
 */

namespace DoctrineModule\Form\Element;

use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
use InvalidArgumentException;
use ReflectionMethod;
use RuntimeException;
use Traversable;
use Zend\Stdlib\Guard\GuardUtils;

class Proxy implements ObjectManagerAwareInterface
{
    /**
     * @var array|Traversable
     */
    protected $objects;

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

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

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

    /**
     * @var
     */
    protected $property;

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

    /**
     * @var callable $labelGenerator A callable used to create a label based on an item in the collection an Entity
     */
    protected $labelGenerator;

    /**
     * @var bool|null
     */
    protected $isMethod;

    /**
     * @var ObjectManager
     */
    protected $objectManager;

    /**
     * @var bool
     */
    protected $displayEmptyItem = false;

    /**
     * @var string
     */
    protected $emptyItemLabel = '';

    /**
     * @var string|null
     */
    protected $optgroupIdentifier;

    /**
     * @var string|null
     */
    protected $optgroupDefault;

    public function setOptions($options)
    {
        if (isset($options['object_manager'])) {
            $this->setObjectManager($options['object_manager']);
        }

        if (isset($options['target_class'])) {
            $this->setTargetClass($options['target_class']);
        }

        if (isset($options['property'])) {
            $this->setProperty($options['property']);
        }

        if (isset($options['label_generator'])) {
            $this->setLabelGenerator($options['label_generator']);
        }

        if (isset($options['find_method'])) {
            $this->setFindMethod($options['find_method']);
        }

        if (isset($options['is_method'])) {
            $this->setIsMethod($options['is_method']);
        }

        if (isset($options['display_empty_item'])) {
            $this->setDisplayEmptyItem($options['display_empty_item']);
        }

        if (isset($options['empty_item_label'])) {
            $this->setEmptyItemLabel($options['empty_item_label']);
        }

        if (isset($options['option_attributes'])) {
            $this->setOptionAttributes($options['option_attributes']);
        }

        if (isset($options['optgroup_identifier'])) {
            $this->setOptgroupIdentifier($options['optgroup_identifier']);
        }

        if (isset($options['optgroup_default'])) {
            $this->setOptgroupDefault($options['optgroup_default']);
        }
    }

    public function getValueOptions()
    {
        if (empty($this->valueOptions)) {
            $this->loadValueOptions();
        }

        return $this->valueOptions;
    }

    /**
     * @return array|Traversable
     */
    public function getObjects()
    {
        $this->loadObjects();

        return $this->objects;
    }

    /**
     * Set the label for the empty option
     *
     * @param string $emptyItemLabel
     *
     * @return Proxy
     */
    public function setEmptyItemLabel($emptyItemLabel)
    {
        $this->emptyItemLabel = $emptyItemLabel;

        return $this;
    }

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

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

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

    /**
     * Set a flag, whether to include the empty option at the beginning or not
     *
     * @param boolean $displayEmptyItem
     *
     * @return Proxy
     */
    public function setDisplayEmptyItem($displayEmptyItem)
    {
        $this->displayEmptyItem = $displayEmptyItem;

        return $this;
    }

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

    /**
     * Set the object manager
     *
     * @param  ObjectManager $objectManager
     *
     * @return Proxy
     */
    public function setObjectManager(ObjectManager $objectManager)
    {
        $this->objectManager = $objectManager;

        return $this;
    }

    /**
     * Get the object manager
     *
     * @return ObjectManager
     */
    public function getObjectManager()
    {
        return $this->objectManager;
    }

    /**
     * Set the FQCN of the target object
     *
     * @param  string $targetClass
     *
     * @return Proxy
     */
    public function setTargetClass($targetClass)
    {
        $this->targetClass = $targetClass;

        return $this;
    }

    /**
     * Get the target class
     *
     * @return string
     */
    public function getTargetClass()
    {
        return $this->targetClass;
    }

    /**
     * Set the property to use as the label in the options
     *
     * @param  string $property
     *
     * @return Proxy
     */
    public function setProperty($property)
    {
        $this->property = $property;

        return $this;
    }

    /**
     * @return mixed
     */
    public function getProperty()
    {
        return $this->property;
    }

    /**
     * Set the label generator callable that is responsible for generating labels for the items in the collection
     *
     * @param callable $callable A callable used to create a label based off of an Entity
     *
     * @throws InvalidArgumentException
     *
     * @return void
     */
    public function setLabelGenerator($callable)
    {
        if (!is_callable($callable)) {
            throw new InvalidArgumentException(
                'Property "label_generator" needs to be a callable function or a \Closure'
            );
        }

        $this->labelGenerator = $callable;
    }

    /**
     * @return callable|null
     */
    public function getLabelGenerator()
    {
        return $this->labelGenerator;
    }

    /**
     * @return string|null
     */
    public function getOptgroupIdentifier()
    {
        return $this->optgroupIdentifier;
    }

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

    /**
     * @return string|null
     */
    public function getOptgroupDefault()
    {
        return $this->optgroupDefault;
    }

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

    /**
     * Set if the property is a method to use as the label in the options
     *
     * @param  boolean $method
     *
     * @return Proxy
     */
    public function setIsMethod($method)
    {
        $this->isMethod = (bool) $method;

        return $this;
    }

    /**
     * @return mixed
     */
    public function getIsMethod()
    {
        return $this->isMethod;
    }

    /** Set the findMethod property to specify the method to use on repository
     *
     * @param array $findMethod
     *
     * @return Proxy
     */
    public function setFindMethod($findMethod)
    {
        $this->findMethod = $findMethod;

        return $this;
    }

    /**
     * Get findMethod definition
     *
     * @return array
     */
    public function getFindMethod()
    {
        return $this->findMethod;
    }

    /**
     * @param $targetEntity
     *
     * @return string|null
     */
    protected function generateLabel($targetEntity)
    {
        if (null === ($labelGenerator = $this->getLabelGenerator())) {
            return null;
        }

        return call_user_func($labelGenerator, $targetEntity);
    }

    /**
     * @param  $value
     *
     * @return array|mixed|object
     * @throws RuntimeException
     */
    public function getValue($value)
    {
        if (!($om = $this->getObjectManager())) {
            throw new RuntimeException('No object manager was set');
        }

        if (!($targetClass = $this->getTargetClass())) {
            throw new RuntimeException('No target class was set');
        }

        $metadata = $om->getClassMetadata($targetClass);

        if (is_object($value)) {
            if ($value instanceof Collection) {
                $data = array();

                foreach ($value as $object) {
                    $values = $metadata->getIdentifierValues($object);
                    $data[] = array_shift($values);
                }

                $value = $data;
            } else {
                $metadata   = $om->getClassMetadata(get_class($value));
                $identifier = $metadata->getIdentifierFieldNames();

                // TODO: handle composite (multiple) identifiers
                if (count($identifier) > 1) {
                    //$value = $key;
                } else {
                    $value = current($metadata->getIdentifierValues($value));
                }
            }
        }

        return $value;
    }

    /**
     * Load objects
     *
     * @throws RuntimeException
     * @throws Exception\InvalidRepositoryResultException
     * @return void
     */
    protected function loadObjects()
    {
        if (!empty($this->objects)) {
            return;
        }

        $findMethod = (array) $this->getFindMethod();

        if (!$findMethod) {
            $findMethodName = 'findAll';
            $repository     = $this->objectManager->getRepository($this->targetClass);
            $objects        = $repository->findAll();
        } else {
            if (!isset($findMethod['name'])) {
                throw new RuntimeException('No method name was set');
            }
            $findMethodName   = $findMethod['name'];
            $findMethodParams = isset($findMethod['params']) ? array_change_key_case($findMethod['params']) : array();
            $repository       = $this->objectManager->getRepository($this->targetClass);

            if (!method_exists($repository, $findMethodName)) {
                throw new RuntimeException(
                    sprintf(
                        'Method "%s" could not be found in repository "%s"',
                        $findMethodName,
                        get_class($repository)
                    )
                );
            }

            $r    = new ReflectionMethod($repository, $findMethodName);
            $args = array();

            foreach ($r->getParameters() as $param) {
                if (array_key_exists(strtolower($param->getName()), $findMethodParams)) {
                    $args[] = $findMethodParams[strtolower($param->getName())];
                } elseif ($param->isDefaultValueAvailable()) {
                    $args[] = $param->getDefaultValue();
                } elseif (!$param->isOptional()) {
                    throw new RuntimeException(
                        sprintf(
                            'Required parameter "%s" with no default value for method "%s" in repository "%s"'
                            . ' was not provided',
                            $param->getName(),
                            $findMethodName,
                            get_class($repository)
                        )
                    );
                }
            }
            $objects = $r->invokeArgs($repository, $args);
        }

        GuardUtils::guardForArrayOrTraversable(
            $objects,
            sprintf('%s::%s() return value', get_class($repository), $findMethodName),
            'DoctrineModule\Form\Element\Exception\InvalidRepositoryResultException'
        );

        $this->objects = $objects;
    }

    /**
     * Load value options
     *
     * @throws RuntimeException
     * @return void
     */
    protected function loadValueOptions()
    {
        if (!($om = $this->objectManager)) {
            throw new RuntimeException('No object manager was set');
        }

        if (!($targetClass = $this->targetClass)) {
            throw new RuntimeException('No target class was set');
        }

        $metadata         = $om->getClassMetadata($targetClass);
        $identifier       = $metadata->getIdentifierFieldNames();
        $objects          = $this->getObjects();
        $options          = array();
        $optionAttributes = array();

        if ($this->displayEmptyItem) {
            $options[''] = $this->getEmptyItemLabel();
        }

        foreach ($objects as $key => $object) {
            if (null !== ($generatedLabel = $this->generateLabel($object))) {
                $label = $generatedLabel;
            } elseif ($property = $this->property) {
                if ($this->isMethod == false && !$metadata->hasField($property)) {
                    throw new RuntimeException(
                        sprintf(
                            'Property "%s" could not be found in object "%s"',
                            $property,
                            $targetClass
                        )
                    );
                }

                $getter = 'get' . ucfirst($property);

                if (!is_callable(array($object, $getter))) {
                    throw new RuntimeException(
                        sprintf('Method "%s::%s" is not callable', $this->targetClass, $getter)
                    );
                }

                $label = $object->{$getter}();
            } else {
                if (!is_callable(array($object, '__toString'))) {
                    throw new RuntimeException(
                        sprintf(
                            '%s must have a "__toString()" method defined if you have not set a property'
                            . ' or method to use.',
                            $targetClass
                        )
                    );
                }

                $label = (string) $object;
            }

            if (count($identifier) > 1) {
                $value = $key;
            } else {
                $value = current($metadata->getIdentifierValues($object));
            }

            foreach ($this->getOptionAttributes() as $optionKey => $optionValue) {
                if (is_string($optionValue)) {
                    $optionAttributes[$optionKey] = $optionValue;

                    continue;
                }

                if (is_callable($optionValue)) {
                    $callableValue                = call_user_func($optionValue, $object);
                    $optionAttributes[$optionKey] = (string) $callableValue;

                    continue;
                }

                throw new RuntimeException(
                    sprintf(
                        'Parameter "option_attributes" expects an array of key => value where value is of type'
                        . '"string" or "callable". Value of type "%s" found.',
                        gettype($optionValue)
                    )
                );
            }

            // If no optgroup_identifier has been configured, apply default handling and continue
            if (is_null($this->getOptgroupIdentifier())) {
                $options[] = array('label' => $label, 'value' => $value, 'attributes' => $optionAttributes);

                continue;
            }

            // optgroup_identifier found, handle grouping
            $optgroupGetter = 'get' . ucfirst($this->getOptgroupIdentifier());

            if (!is_callable(array($object, $optgroupGetter))) {
                throw new RuntimeException(
                    sprintf('Method "%s::%s" is not callable', $this->targetClass, $optgroupGetter)
                );
            }

            $optgroup = $object->{$optgroupGetter}();

            // optgroup_identifier contains a valid group-name. Handle default grouping.
            if (false === is_null($optgroup) && trim($optgroup) !== '') {
                $options[$optgroup]['label']     = $optgroup;
                $options[$optgroup]['options'][] = array(
                    'label'      => $label,
                    'value'      => $value,
                    'attributes' => $optionAttributes
                );

                continue;
            }

            $optgroupDefault = $this->getOptgroupDefault();

            // No optgroup_default has been provided. Line up without a group
            if (is_null($optgroupDefault)) {
                $options[] = array('label' => $label, 'value' => $value, 'attributes' => $optionAttributes);

                continue;
            }

            // Line up entry with optgroup_default
            $options[$optgroupDefault]['label']     = $optgroupDefault;
            $options[$optgroupDefault]['options'][] = array(
                'label'      => $label,
                'value'      => $value,
                'attributes' => $optionAttributes
            );
        }

        $this->valueOptions = $options;
    }
}


<?php
/**
 * @copyright Copyright (c) 2013-2016 Voodoo Mobile Consulting Group LLC
 * @link      https://voodoo.rocks
 * @license   http://opensource.org/licenses/MIT The MIT License (MIT)
 */
namespace vr\core;

use ArrayAccess;
use Yii;
use yii\base\Arrayable;
use yii\base\Exception;
use yii\base\InvalidParamException;
use yii\db\ActiveRecord;
use yii\db\BaseActiveRecord;
use yii\helpers\ArrayHelper;

/**
 * Class ArrayObject
 * @package vr\core
 */
class ArrayObject implements Arrayable, ArrayAccess
{
    /**
     * @var array|object
     */
    private $data;

    /**
     * @param array $data
     */
    public function __construct($data)
    {
        if (!is_array($data)) {
            throw new InvalidParamException('Value cannot be an object or something else. Only arrays accepted');
        }

        ArrayHelper::remove($data, 'optional');

        $this->data = $data;
    }

    /**
     * @deprecated
     *
     * @param $name
     *
     * @return bool
     */
    public function contains($name)
    {
        return array_key_exists($name, $this->data);
    }

    /**
     * @param $name
     *
     * @return bool
     */
    public function has($name)
    {
        return array_key_exists($name, $this->data);
    }

    /**
     * @return bool
     */
    public function isEmpty()
    {
        return count($this->data) === 0;
    }

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

    /**
     * @param string $name
     *
     * @return mixed|ArrayObject
     */
    public function __get($name)
    {
        $value = ArrayHelper::getValue($this->data, $name, null);

        if (ArrayHelper::isAssociative($value)) {
            return new ArrayObject($value);
        } else if (ArrayHelper::isIndexed($value)) {
            $objects = [];

            foreach ($value as $item) {
                if (is_array($item)) {
                    $objects[] = new ArrayObject($item);
                } else {
                    $objects[] = $item;
                }
            }

            return $objects;
        }

        return $value;
    }

    /**
     * @param       $class
     * @param array $attributes
     *
     * @return object
     * @throws Exception
     * @throws \yii\base\InvalidConfigException
     *
     */
    public function createModel($class, $attributes = [])
    {
        /** @var ActiveRecord $model */
        $model = Yii::createObject($class);

        if (!$model || !is_a($model, BaseActiveRecord::className())) {
            throw new Exception('This class is not supported for creating from ArrayObject. Only subclasses of yii\base\Model are supported');
        }

        if ($attributes && !empty($attributes)) {
            foreach ($attributes as $attribute) {
                $model->setAttribute($attribute, $this->{$attribute});
            }
        } else {
            $model->setAttributes($this->getValues(), true);
        }

        return $model;
    }

    /**
     * Returns the list of fields that should be returned by default by [[toArray()]] when no specific fields are
     * specified. A field is a named element in the returned array by [[toArray()]]. This method should return an array
     * of field names or field definitions. If the former, the field name will be treated as an object property name
     * whose value will be used as the field value. If the latter, the array key should be the field name while the
     * array value should be the corresponding field definition which can be either an object property name or a PHP
     * callable returning the corresponding field value. The signature of the callable should be:
     * ```php
     * function ($field, $model) {
     *     // return field value
     * }
     * ```
     * For example, the following code declares four fields:
     * - `email`: the field name is the same as the property name `email`;
     * - `firstName` and `lastName`: the field names are `firstName` and `lastName`, and their
     *   values are obtained from the `first_name` and `last_name` properties;
     * - `fullName`: the field name is `fullName`. Its value is obtained by concatenating `first_name`
     *   and `last_name`.
     * ```php
     * return [
     *     'email',
     *     'firstName' => 'first_name',
     *     'lastName' => 'last_name',
     *     'fullName' => function ($model) {
     *         return $model->first_name . ' ' . $model->last_name;
     *     },
     * ];
     * ```
     * @return array the list of field names or field definitions.
     * @see toArray()
     */
    public function fields()
    {
        return array_keys($this->data);
    }

    /**
     * Returns the list of additional fields that can be returned by [[toArray()]] in addition to those listed in
     * [[fields()]]. This method is similar to [[fields()]] except that the list of fields declared by this method are
     * not returned by default by [[toArray()]]. Only when a field in the list is explicitly requested, will it be
     * included in the result of [[toArray()]].
     * @return array the list of expandable field names or field definitions. Please refer
     * to [[fields()]] on the format of the return value.
     * @see toArray()
     * @see fields()
     */
    public function extraFields()
    {
    }

    /**
     * Converts the object into an array.
     *
     * @param array   $fields    the fields that the output array should contain. Fields not specified
     *                           in [[fields()]] will be ignored. If this parameter is empty, all fields as specified
     *                           in
     *                           [[fields()]] will be returned.
     * @param array   $expand    the additional fields that the output array should contain.
     *                           Fields not specified in [[extraFields()]] will be ignored. If this parameter is empty,
     *                           no extra fields will be returned.
     * @param boolean $recursive whether to recursively return array representation of embedded objects.
     *
     * @return array the array representation of the object
     */
    public function toArray(array $fields = [], array $expand = [], $recursive = true)
    {
        $array = [];

        foreach ($this->data as $key => $value) {
            if ($recursive && is_array($value)) {
                $array[$key] = (new ArrayObject($value))->toArray([], [], $recursive);
            } else {
                $array[$key] = $value;
            }
        }

        return $array;
    }

    /**
     * (PHP 5 >= 5.0.0)

     * Whether a offset exists
     * @link http://php.net/manual/en/arrayaccess.offsetexists.php
     *
     * @param mixed $offset

     *                      An offset to check for.
     *

     *
     * @return boolean true on success or false on failure.
     *

     *

     * The return value will be casted to boolean if non-boolean was returned.
     */
    public function offsetExists($offset)
    {
        return ArrayHelper::isIndexed($this->data) && count($this->data) > $offset;
    }

    /**
     * (PHP 5 >= 5.0.0)

     * Offset to retrieve
     * @link http://php.net/manual/en/arrayaccess.offsetget.php
     *
     * @param mixed $offset

     *                      The offset to retrieve.
     *

     *
     * @return mixed Can return all value types.
     */
    public function offsetGet($offset)
    {
        return $this->data[$offset];
    }

    /**
     * (PHP 5 >= 5.0.0)

     * Offset to set
     * @link http://php.net/manual/en/arrayaccess.offsetset.php
     *
     * @param mixed $offset

     *                      The offset to assign the value to.
     *

     * @param mixed $value

     *                      The value to set.
     *

     *
     * @return void
     */
    public function offsetSet($offset, $value)
    {
    }

    /**
     * (PHP 5 >= 5.0.0)

     * Offset to unset
     * @link http://php.net/manual/en/arrayaccess.offsetunset.php
     *
     * @param mixed $offset

     *                      The offset to unset.
     *

     *
     * @return void
     */
    public function offsetUnset($offset)
    {
    }
}


<?php

namespace InetStudio\Access\Providers;

use Collective\Html\FormBuilder;
use Illuminate\Support\ServiceProvider;
use InetStudio\Access\Console\Commands\SetupCommand;

/**
 * Class AccessServiceProvider.
 */
class AccessServiceProvider extends ServiceProvider
{
    /**
     * Загрузка сервиса.
     *
     * @return void
     */
    public function boot(): void
    {
        $this->registerConsoleCommands();
        $this->registerPublishes();
        $this->registerViews();
        $this->registerFormComponents();
    }

    /**
     * Регистрация команд.
     *
     * @return void
     */
    protected function registerConsoleCommands(): void
    {
        if ($this->app->runningInConsole()) {
            $this->commands([
                SetupCommand::class,
            ]);
        }
    }

    /**
     * Регистрация ресурсов.
     *
     * @return void
     */
    protected function registerPublishes(): void
    {
        if ($this->app->runningInConsole()) {
            if (! class_exists('CreateAccessTables')) {
                $timestamp = date('Y_m_d_His', time());
                $this->publishes([
                    __DIR__.'/../../database/migrations/create_access_tables.php.stub' => database_path('migrations/'.$timestamp.'_create_access_tables.php'),
                ], 'migrations');
            }
        }
    }

    /**
     * Регистрация представлений.
     *
     * @return void
     */
    protected function registerViews(): void
    {
        $this->loadViewsFrom(__DIR__.'/../../resources/views', 'admin.module.access');
    }

    /**
     * Регистрация компонентов форм.
     *
     * @return void
     */
    protected function registerFormComponents()
    {
        FormBuilder::component('access', 'admin.module.access::back.forms.blocks.access', ['name' => null, 'value' => null, 'attributes' => null]);
    }
}


<?php
//
// +---------------------------------------------------------------------+
// | CODE INC. SOURCE CODE                                               |
// +---------------------------------------------------------------------+
// | Copyright (c) 2017 - Code Inc. SAS - All Rights Reserved.           |
// | Visit https://www.codeinc.fr for more information about licensing.  |
// +---------------------------------------------------------------------+
// | NOTICE:  All information contained herein is, and remains the       |
// | property of Code Inc. SAS. The intellectual and technical concepts  |
// | contained herein are proprietary to Code Inc. SAS are protected by  |
// | trade secret or copyright law. Dissemination of this information or |
// | reproduction of this material  is strictly forbidden unless prior   |
// | written permission is obtained from Code Inc. SAS.                  |
// +---------------------------------------------------------------------+
//
// Author:   Joan Fabrégat <joan@codeinc.fr>
// Date:     15/12/2017
// Time:     11:44
// Project:  ErrorRenderer
//
namespace CodeInc\ErrorRenderer;
use Colors\Color;
use Throwable;

/**
 * Class ConsoleErrorRenderer
 *
 * @package CodeInc\ErrorDisplay
 * @author Joan Fabrégat <joan@codeinc.fr>
 */
class ConsoleErrorRenderer extends AbstractErrorRenderer
{
    // Options
    public const OPT_COLORS = 1024;
    public const OPT_ALL = parent::OPT_ALL | self::OPT_COLORS;
    public const OPT_DEFAULT = self::OPT_ALL;

    // Styles
    private const STYLE_ITALIC = 1;
    private const STYLE_BOLD = 2;
    private const STYLE_CENTER = 4;
    private const STYLE_TITLE = 8;
    private const STYLE_SUBTITLE = 16;

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

    /**
     * @var Color
     */
    private $termColor;

    /**
     * TerminalRenderingEngine constructor.
     *
     * @param Throwable $throwable
     * @param int|null $options
     */
    public function __construct(Throwable $throwable, int $options = null)
    {
        parent::__construct($throwable, $options !== null ? $options : self::OPT_DEFAULT);
        if (class_exists(Color::class)) {
            $this->termColor = new Color();
        }
    }

    /**
     * Returns a blank line.
     *
     * @param int $count Number of lines to be returned
     * @return string
     */
    private function getBlankLine(int $count = null):string
    {
        $out = "";
        for ($i = 0; $i < ($count ?: 1); $i++) {
            $out .= $this->getLine('');
        }
        return $out;
    }

    /**
     * Returns the number of columns in the terminal windows.
     *
     * @return int
     */
    private function countTermCols():int
    {
        if (!$this->termCols) {
            if (!($this->termCols = (int)exec('tput cols'))) {
                $this->termCols = 80;
            }
        }
        return $this->termCols;
    }

    /**
     * Renders the exception.
     */
    public function get():string
    {
        // renders the error
        $out = "\n"
            .$this->getBlankLine()
            .$this->getLine("Error", self::STYLE_TITLE)
            .$this->getBlankLine()
            .$this->getErrorBlock($this->throwable);

        if ($this->options & self::OPT_RENDER_PREVIOUS_EXCEPTIONS
            && $previous = $this->throwable->getPrevious()) {

            $out .= $this->getBlankLine(3)
                .$this->getLine("Previous errors", self::STYLE_SUBTITLE);
            $isFirst = true;
            do {
                if (!$isFirst) {
                    $out .= $this->getBlankLine(2);
                }
                $out .= $this->getErrorBlock($previous, 2);
                $isFirst = false;
            }
            while ($previous = $previous->getPrevious());
        }

        $out .= $this->getBlankLine()
            .$this->getLine("End error",self::STYLE_TITLE)
            .$this->getBlankLine()
            ."\n";
        return $out;
    }

    /**
     * Returns an error block.
     *
     * @param \Throwable $exception
     * @param int|null $linePadding
     * @return string
     */
    private function getErrorBlock(\Throwable $exception, ?int $linePadding = null):string
    {
        // Renders the message
        $out = $this->getLine(get_class($exception), self::STYLE_BOLD | self::STYLE_ITALIC, $linePadding)
            .$this->getLine($exception->getMessage(), null, $linePadding);

        // Renders the position
        if ($this->options & self::OPT_RENDER_LOCATION) {
            $out .= $this->getLine($exception->getFile().':'.$exception->getLine(),
                    self::STYLE_ITALIC, $linePadding)
                .$this->getBlankLine();
        }

        // Renders the backtrace
        if ($this->options & self::OPT_RENDER_BACKTRACE) {
            $out .= $this->getLine("Backtrace",
                    self::STYLE_BOLD | self::STYLE_ITALIC,$linePadding + 2)
                .$this->getLine($exception->getTraceAsString(),
                    self::STYLE_ITALIC, $linePadding + 2);
        }

        return $out;
    }

    /**
     * Adds padding and line breaks to the content to make it fit inside the terminal windows with a
     * proper word cesure.
     *
     * @param string $content
     * @param int|null $styles Rendering style (see STYLE_XXX class constants)
     * @param int|null $paddingLength
     * @return string
     */
    private function getLine(string $content, int $styles = null, int $paddingLength = null):string
    {
        $termCols = $this->countTermCols();

        // title lines
        if ($styles & self::STYLE_TITLE || $styles & self::STYLE_SUBTITLE) {
            $styles |= self::STYLE_BOLD | self::STYLE_CENTER;
            $titleSide = str_pad("", $styles & self::STYLE_TITLE ? 4 : 2, "-");
            $content = ($titleSide ? "$titleSide " : "").strtoupper($content).($titleSide ? " $titleSide" : "");
        }

        // centering
        if ($styles & self::STYLE_CENTER && strlen($content) < $termCols) {
            $leftPadding = ceil(($termCols - strlen($content)) / 2) + strlen($content);
            $content = str_pad(str_pad($content, $leftPadding, " ", STR_PAD_LEFT),
                $termCols, " ");
        }

        // adding padding
        $paddedContent = "";
        $paddingLength = $paddingLength === null ? 2 : $paddingLength + 2;
        $padding = str_pad("", $paddingLength, " ");
        $availableCols = $termCols - $paddingLength * 2;
        // processing the content by line
        foreach (explode("\n", $content) as $contentLine) {
            $paddedLine = "";

            // processing the content word by word
            foreach (explode(" ", $contentLine) as $word) {
                if (strlen("$paddedLine $word") >= $availableCols) {
                    $paddedContent .= (!empty($paddedContent) ? "\n" : "")
                        .$padding
                        .str_pad($paddedLine, $availableCols, " ")
                        .$padding;
                    $paddedLine = "";
                }
                $paddedLine .= "$word ";
            }

            if (!empty($paddedLine)) {
                $paddedContent .= (!empty($paddedContent) ? "\n" : "")
                    .$padding
                    .str_pad($paddedLine, $availableCols, " ")
                    .$padding;
            }
        }

        // applying colors
        if ($this->options & self::OPT_COLORS && $this->termColor instanceof Color) {
            $paddedContent = $this->termColor->bg('red', $this->termColor->apply('white', $paddedContent));
            if ($styles & self::STYLE_BOLD) {
                $paddedContent = $this->termColor->apply('bold', $paddedContent);
            }
            if ($styles & self::STYLE_ITALIC) {
                $paddedContent = $this->termColor->apply('italic', $paddedContent);
            }
        }
        return "$paddedContent\n";
    }
}


<?php

namespace CatLab\Charon\Laravel\Middleware;

use Closure;
use CatLab\Charon\Models\ResourceResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class ResourceToOutput
{
    const RETURN_TYPE_TEXT = 'text';
    const RETURN_TYPE_JSON = 'json';

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        if ($response instanceof ResourceResponse) {

            $format = $this->getReturnFormat($request);
            switch($format) {
                case self::RETURN_TYPE_TEXT:
                    return $this->toText($response);

                case self::RETURN_TYPE_JSON:
                default:
                    return $this->toJSON($response);
            }

        }

        return $response;
    }

    /**
     * @param ResourceResponse $response
     * @return \Illuminate\Http\JsonResponse
     */
    protected function toJSON(ResourceResponse $response)
    {
        return \Response::json($response->getResource()->toArray());
    }

    /**
     * @param ResourceResponse $response
     * @return Response
     */
    protected function toText(ResourceResponse $response)
    {
        return new Response(
            print_r($response->getResource()->toArray(), true),
            200,
            [
                'Content-type' => 'text/text'
            ]
        );
    }

    /**
     * @param Request $request
     * @return string
     */
    protected function getReturnFormat(Request $request)
    {
        $format = $request->route('format');
        switch (strtolower($format)) {
            case 'txt':
            case 'text':
                return self::RETURN_TYPE_TEXT;

            case 'json':
            default:
                return self::RETURN_TYPE_JSON;
        }
    }
}


<?php

declare(strict_types=1);

namespace NAttreid\Utils;

/**
 * Pomocna trida pro pole
 *
 * @author Attreid <attreid@gmail.com>
 */
class Arrays extends \Nette\Utils\Arrays
{

	/**
	 * Je pole asociativni
	 * @param array $arr
	 * @return bool
	 */
	public static function isAssoc(array $arr): bool
	{
		return array_keys($arr) !== range(0, count($arr) - 1);
	}

	/**
	 * Vlozi do pole na dane misto
	 * @param array $array
	 * @param int $position
	 * @param mixed $insert
	 */
	public static function slice(array &$array, int $position, $insert): void
	{
		if (isset($array[$position])) {
			array_splice($array, $position, 0, [$insert]);
		} else {
			$array[$position] = $insert;
		}
	}

	/**
	 * Je pole vicerozmerne
	 * @param array $a
	 * @return bool
	 */
	public static function isMultidimensional(array $a): bool
	{
		$rv = array_filter($a, 'is_array');
		return count($rv) > 0;
	}

}


<?php

namespace Amcms\Services;

use Slim\Http\Request as Request;
use Amcms\Services\Service;
use Awurth\SlimValidation\Validator as Engine;
use Respect\Validation\Validator as v;

class ValidatorService extends Service
{
    protected $engine;

    public function __construct($container)
    {
        parent::__construct($container);
        $this->engine = new Engine();
    }

    /**
     * Validator wrapper
     * @param  RequestInterface $request
     * @param  array            $rules
     * @return mixed
     */
    public function check(Request $request, $rules = [])
    {
        $forReturn = [];

        foreach ($rules as $param => $rule) {
            $forReturn[$param] = $request->getParam($param);

            if (is_array($rule)) {
                list($rule, $message) = $rule;
            }

            if (is_callable($rule)) {
                /**
                 * @todo check this possibility
                 */
                $validateAr[$param] = call_user_func($rule)
                                            ->setName('"' . ucfirst($param) . '"');
            } else {
                $ruleAr = explode(',', $rule);
                $validateAr[$param] = $this->setRules($ruleAr)
                                            ->setName('"' . ucfirst($param) . '"');
            }

            if (isset($message)) {
                $validateAr[$param] = ['rules' => $validateAr[$param], 'message' => $message];
                unset($message);
            }

        }

        if (is_array($validateAr)) {
            $this->engine->validate($request, $validateAr);

            if ($this->failed()) {
                $this->flash->addMessage('form.old', $request->getParsedBody()); // or getParams()?
                $this->flash->addMessage('form.errors', $this->getErrors());
                return false;
            }
        }

        // return true;

        /**
         * Testing
         * Return all request body params
         */
        return $forReturn;
    }

    /**
     * Create rules chain
     * @param array $ruleAr string-based rules
     * @return  Respect\Validation\Validator
     */
    protected function setRules($ruleAr)
    {
        v::with('Amcms\\Services\\ValidatorRules\\');
        $vObj = v::initValidator();

        if (!is_array($ruleAr)) {
            return $vObj;
        }

        foreach ($ruleAr as $ruleStr) {
            $data = explode(':', trim($ruleStr));
            switch ($data[0]) {
                case 'required':
                    $vObj->notEmpty();
                    break;

                case 'email':
                    $vObj->email();
                    break;

                default:
                    break;
            }
        }

        return $vObj;
    }

    /**
     * Wrapper for validate engine
     * @return mixed error array
     */
    public function getErrors()
    {
        return $this->engine->getErrors();
    }

    /**
     * Wrapper for validate engine
     * @return boolean
     */
    public function failed()
    {
        return !$this->engine->isValid();
    }
}


<?php

namespace Maduser\Minimal\Assets;

use Maduser\Minimal\Config\Exceptions\KeyDoesNotExistException;
use Maduser\Minimal\Modules\Contracts\ModulesInterface;
use Maduser\Minimal\Assets\Contracts\AssetsInterface;
use Maduser\Minimal\Config\Contracts\ConfigInterface;
use Maduser\Minimal\Http\Contracts\RequestInterface;
use Maduser\Minimal\Http\Contracts\ResponseInterface;
use Maduser\Minimal\Routing\Contracts\RouterInterface;
use Maduser\Minimal\Views\Contracts\ViewInterface;

class AssetsController
{
    /**
     * @var ConfigInterface
     */
    protected $config;

    /**
     * @var ResponseInterface
     */
    protected $response;

    /**
     * AssetsController constructor.
     *
     * @param ConfigInterface   $config
     * @param ResponseInterface $response
     */
    public function __construct(
        ConfigInterface $config,
        ResponseInterface $response
    ) {
        /** @var \Maduser\Minimal\Config\Config $config */
        /** @var \Maduser\Minimal\Http\Response $response */
        $this->config = $config;
        $this->response = $response;
    }

    /**
     * @param $alias
     * @param $path
     *
     * @return string
     */
    public function serve($alias, $path)
    {
        $filePath = '';

        try {
            $filePath = $this->config->item('assets.routes.' . $alias) . '/' . $path;
        } catch (KeyDoesNotExistException $e) {
            $this->response->status404();
        }

        if (!file_exists($filePath)) {
            $this->response->status404();
        }

        ob_start();

        $fileName = basename($filePath);
        $fileSize = filesize($filePath);
        $fileTime = filemtime($filePath);
        $fileType = $this->mimeContentType($filePath);
        $maxAge = (60 * 60 * 24 * 30);
        $expires = date('r', $fileTime + $maxAge);
        $lastModified = date('r', $fileTime);

        $this->response->header('Pragma: public'); // required
        $this->response->header('Cache-Control: public, must-revalidate, proxy-revalidate, max-age="' . $maxAge . '", s-maxage="' . $maxAge . '"');
        $this->response->header('Last-Modified: ' . $lastModified);
        $this->response->header('Expires: ' . $expires);
        $this->response->header('Content-Type: ' . $fileType);
        $this->response->header('Content-Disposition: inline; filename="' . $fileName . '";');
        $this->response->header('Content-Transfer-Encoding: binary');
        $this->response->header('Content-Length: ' . $fileSize);

        readfile($filePath);

        $contents = ob_get_contents();
        ob_end_clean();

        return $contents;
    }

    /**
     * @param $filename
     *
     * @return mixed|string
     */
    protected function mimeContentType($filename)
    {
        $mimeTypes = [
            'txt' => 'text/plain',
            'htm' => 'text/html',
            'html' => 'text/html',
            'php' => 'text/html',
            'css' => 'text/css',
            'js' => 'application/javascript',
            'json' => 'application/json',
            'xml' => 'application/xml',
            'swf' => 'application/x-shockwave-flash',
            'flv' => 'video/x-flv',

            // images
            'png' => 'image/png',
            'jpe' => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'jpg' => 'image/jpeg',
            'gif' => 'image/gif',
            'bmp' => 'image/bmp',
            'ico' => 'image/vnd.microsoft.icon',
            'tiff' => 'image/tiff',
            'tif' => 'image/tiff',
            'svg' => 'image/svg+xml',
            'svgz' => 'image/svg+xml',

            // archives
            'zip' => 'application/zip',
            'rar' => 'application/x-rar-compressed',
            'exe' => 'application/x-msdownload',
            'msi' => 'application/x-msdownload',
            'cab' => 'application/vnd.ms-cab-compressed',

            // audio/video
            'mp3' => 'audio/mpeg',
            'qt' => 'video/quicktime',
            'mov' => 'video/quicktime',

            // adobe
            'pdf' => 'application/pdf',
            'psd' => 'image/vnd.adobe.photoshop',
            'ai' => 'application/postscript',
            'eps' => 'application/postscript',
            'ps' => 'application/postscript',

            // ms office
            'doc' => 'application/msword',
            'rtf' => 'application/rtf',
            'xls' => 'application/vnd.ms-excel',
            'ppt' => 'application/vnd.ms-powerpoint',

            // open office
            'odt' => 'application/vnd.oasis.opendocument.text',
            'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
        ];

        $ext = strtolower(pathinfo($filename)['extension']);

        if (array_key_exists($ext, $mimeTypes)) {
            return $mimeTypes[$ext];
        }

        return 'application/octet-stream';
    }

}


<?php
/**
 * OAuth 2.0 Password grant
 *
 */

namespace OAuth2\Server\Grant;

use OAuth2\Server\Entity\AccessTokenEntity;
use OAuth2\Server\Entity\ClientEntity;
use OAuth2\Server\Entity\RefreshTokenEntity;
use OAuth2\Server\Entity\SessionEntity;
use OAuth2\Server\Exception;
use OAuth2\Server\Util\SecureKey;

/**
 * Password grant class
 */
class PasswordGrant extends AbstractGrant
{
    /**
     * Grant identifier
     *
     * @var string
     */
    protected $identifier = 'password';

    /**
     * Response type
     *
     * @var string
     */
    protected $responseType;

    /**
     * Callback to authenticate a user's name and password
     *
     * @var callable
     */
    protected $callback;

    /**
     * Access token expires in override
     *
     * @var int
     */
    protected $accessTokenTTL;

    /**
     * Set the callback to verify a user's username and password
     *
     * @param callable $callback The callback function
     *
     * @return void
     */
    public function setVerifyCredentialsCallback(callable $callback)
    {
        $this->callback = $callback;
    }

    /**
     * Return the callback function
     *
     * @return callable
     *
     * @throws
     */
    protected function getVerifyCredentialsCallback()
    {
        if (is_null($this->callback) || !is_callable($this->callback)) {
            throw new Exception\ServerErrorException('Null or non-callable callback set on Password grant');
        }

        return $this->callback;
    }

    /**
     * Complete the password grant
     *
     * @return array
     *
     * @throws
     */
    public function completeFlow(ClientEntity $client)
    {
        $username = $this->server->getRequestHandler()->getParam('username');
        if (is_null($username)) {
            throw new Exception\InvalidRequestException('username');
        }

        $password = $this->server->getRequestHandler()->getParam('password');
        if (is_null($password)) {
            throw new Exception\InvalidRequestException('password');
        }

        // Check if user's username and password are correct
        $userId = call_user_func($this->getVerifyCredentialsCallback(), $username, $password);

        if ($userId === false) {
            throw new Exception\InvalidCredentialsException();
        }

        // Validate any scopes that are in the request
        $scopeParam = $this->server->getRequestHandler()->getParam('scope');
        $scopes = $this->validateScopes($scopeParam, $client);

        // Create a new session
        $session = new SessionEntity($this->server);
        $session->setOwner('user', $userId);
        $session->associateClient($client);

        // Generate an access token
        $accessToken = new AccessTokenEntity($this->server);
        $accessToken->setId();
        $accessToken->setExpireTime($this->getAccessTokenTTL() + time());

        // Associate scopes with the session and access token
        foreach ($scopes as $scope) {
            $session->associateScope($scope);
        }

        foreach ($session->getScopes() as $scope) {
            $accessToken->associateScope($scope);
        }

        $this->server->getTokenType()->setSession($session);
        $this->server->getTokenType()->setParam('access_token', $accessToken->getId());
        $this->server->getTokenType()->setParam('expires_in', $this->getAccessTokenTTL());

        // Associate a refresh token if set
        if ($this->server->hasGrantType('refresh_token')) {
            $refreshToken = new RefreshTokenEntity($this->server);
            $refreshToken->setId();
            $refreshToken->setExpireTime($this->server->getGrantType('refresh_token')->getRefreshTokenTTL() + time());
            $this->server->getTokenType()->setParam('refresh_token', $refreshToken->getId());
        }

        // Save everything
        $session->save();
        $accessToken->setSession($session);
        $accessToken->save();

        if ($this->server->hasGrantType('refresh_token')) {
            $refreshToken->setAccessToken($accessToken);
            $refreshToken->save();
        }

        return $this->server->getTokenType()->generateResponse();
    }
}


<?php
/**
 * @author    Antoine Hedgecock <antoine.hedgecock@gmail.com>
 *
 * @copyright Interactive Solutions
 */

declare(strict_types = 1);

namespace InteractiveSolutions\Bernard\Factory\Router;

use InteractiveSolutions\Bernard\Router\ConsumerTaskManager;
use Zend\ServiceManager\Config;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class ConsumerTaskManagerFactory implements FactoryInterface
{
    /**
     * Create service
     *
     * @param ServiceLocatorInterface $serviceLocator
     *
     * @return mixed
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        /* @var $config array */
        $config = $serviceLocator->get('config');
        $config = $config['interactive_solutions']['bernard_consumer_manager'];

        return new ConsumerTaskManager($serviceLocator, $config);
    }
}


<?php
declare(strict_types = 1);

namespace Innmind\Rest\Client\Server;

use Innmind\Rest\Client\{
    Server as ServerInterface,
    Request\Range,
    Identity,
    HttpResource,
    Translator\SpecificationTranslator,
    Exception\ResourceNotRangeable,
    Exception\UnsupportedResponse,
    Exception\DomainException,
    Exception\NormalizationException,
    Definition\Access,
    Formats,
    Format\Format,
    Link,
    Link\Parameter,
    Definition\HttpResource as Definition,
    Response\ExtractIdentity,
    Response\ExtractIdentities,
    Serializer\Denormalizer\DenormalizeResource,
    Serializer\Normalizer\NormalizeResource,
    Serializer\Encode,
    Serializer\Decode,
};
use Innmind\HttpTransport\Transport;
use Innmind\Url\{
    UrlInterface,
    Url,
};
use Innmind\UrlResolver\ResolverInterface;
use Innmind\Http\{
    Message\Request\Request,
    Message\Method\Method,
    ProtocolVersion\ProtocolVersion,
    Headers\Headers,
    Header,
    Header\Value,
    Header\Range as RangeHeader,
    Header\RangeValue,
    Header\Accept,
    Header\AcceptValue,
    Header\ContentType,
    Header\ContentTypeValue,
    Header\Parameter as HeaderParameter,
    Header\Link as LinkHeader,
    Header\LinkValue,
};
use Innmind\Immutable\{
    SetInterface,
    Map,
    Set,
};
use Innmind\Specification\Specification;

final class Server implements ServerInterface
{
    private $url;
    private $fulfill;
    private $capabilities;
    private $resolver;
    private $extractIdentity;
    private $extractIdentities;
    private $denormalizeResource;
    private $normalizeResource;
    private $encode;
    private $decode;
    private $translate;
    private $formats;

    public function __construct(
        UrlInterface $url,
        Transport $fulfill,
        Capabilities $capabilities,
        ResolverInterface $resolver,
        ExtractIdentity $extractIdentity,
        ExtractIdentities $extractIdentities,
        DenormalizeResource $denormalizeResource,
        NormalizeResource $normalizeResource,
        Encode $encode,
        Decode $decode,
        SpecificationTranslator $translate,
        Formats $formats
    ) {
        $this->url = $url;
        $this->fulfill = $fulfill;
        $this->capabilities = $capabilities;
        $this->resolver = $resolver;
        $this->extractIdentity = $extractIdentity;
        $this->extractIdentities = $extractIdentities;
        $this->denormalizeResource = $denormalizeResource;
        $this->normalizeResource = $normalizeResource;
        $this->encode = $encode;
        $this->decode = $decode;
        $this->translate = $translate;
        $this->formats = $formats;
    }

    /**
     * {@inheritdoc}
     */
    public function all(
        string $name,
        Specification $specification = null,
        Range $range = null
    ): SetInterface {
        $definition = $this->capabilities->get($name);

        if ($range !== null && !$definition->isRangeable()) {
            throw new ResourceNotRangeable;
        }

        if ($specification !== null) {
            $query = '?'.($this->translate)($specification);
        }

        $url = $this->resolver->resolve(
            (string) $definition->url(),
            $query ?? (string) $definition->url()
        );
        $url = Url::fromString($url);
        $headers = Headers::of();

        if ($range !== null) {
            $headers = Headers::of(
                new RangeHeader(
                    new RangeValue(
                        'resource',
                        $range->firstPosition(),
                        $range->lastPosition()
                    )
                )
            );
        }

        $response = ($this->fulfill)(
            new Request(
                $url,
                Method::get(),
                new ProtocolVersion(1, 1),
                $headers
            )
        );

        return ($this->extractIdentities)($response, $definition);
    }

    public function read(string $name, Identity $identity): HttpResource
    {
        $definition = $this->capabilities->get($name);
        $response = ($this->fulfill)(
            new Request(
                $this->resolveUrl(
                    $definition->url(),
                    $identity
                ),
                Method::get(),
                new ProtocolVersion(1, 1),
                Headers::of(
                    $this->generateAcceptHeader()
                )
            )
        );

        try {
            $format = $this->formats->matching(
                (string) $response
                    ->headers()
                    ->get('Content-Type')
                    ->values()
                    ->join(', ')
            );
        } catch (\Exception $e) {
            throw new UnsupportedResponse('', 0, $e);
        }

        $data = ($this->decode)(
            $format->name(),
            $response->body()
        );

        return ($this->denormalizeResource)(
            $data,
            $definition,
            new Access(Access::READ)
        );
    }

    public function create(HttpResource $resource): Identity
    {
        $definition = $this->capabilities->get($resource->name());
        $response = ($this->fulfill)(
            new Request(
                $definition->url(),
                Method::post(),
                new ProtocolVersion(1, 1),
                Headers::of(
                    new ContentType(
                        new ContentTypeValue(
                            'application',
                            'json'
                        )
                    ),
                    $this->generateAcceptHeader()
                ),
                ($this->encode)(
                    ($this->normalizeResource)(
                        $resource,
                        $definition,
                        new Access(Access::CREATE)
                    )
                )
            )
        );

        return ($this->extractIdentity)($response, $definition);
    }

    public function update(
        Identity $identity,
        HttpResource $resource
    ): ServerInterface {
        $definition = $this->capabilities->get($resource->name());
        ($this->fulfill)(
            new Request(
                $this->resolveUrl(
                    $definition->url(),
                    $identity
                ),
                Method::put(),
                new ProtocolVersion(1, 1),
                Headers::of(
                    new ContentType(
                        new ContentTypeValue(
                            'application',
                            'json'
                        )
                    ),
                    $this->generateAcceptHeader()
                ),
                ($this->encode)(
                    ($this->normalizeResource)(
                        $resource,
                        $definition,
                        new Access(Access::UPDATE)
                    )
                )
            )
        );

        return $this;
    }

    public function remove(string $name, Identity $identity): ServerInterface
    {
        $definition = $this->capabilities->get($name);
        ($this->fulfill)(
            new Request(
                $this->resolveUrl(
                    $definition->url(),
                    $identity
                ),
                Method::delete(),
                new ProtocolVersion(1, 1)
            )
        );

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function link(
        string $name,
        Identity $identity,
        SetInterface $links
    ): ServerInterface {
        if ((string) $links->type() !== Link::class) {
            throw new \TypeError(sprintf(
                'Argument 3 must be of type SetInterface<%s>',
                Link::class
            ));
        }

        if ($links->size() === 0) {
            throw new DomainException;
        }

        $definition = $this->capabilities->get($name);
        $this->validateLinks($definition, $links);
        ($this->fulfill)(
            new Request(
                $this->resolveUrl(
                    $definition->url(),
                    $identity
                ),
                Method::link(),
                new ProtocolVersion(1, 1),
                Headers::of(
                    $this->generateAcceptHeader(),
                    $this->generateLinkHeader($links)
                )
            )
        );

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function unlink(
        string $name,
        Identity $identity,
        SetInterface $links
    ): ServerInterface {
        if ((string) $links->type() !== Link::class) {
            throw new \TypeError(sprintf(
                'Argument 3 must be of type SetInterface<%s>',
                Link::class
            ));
        }

        if ($links->size() === 0) {
            throw new DomainException;
        }

        $definition = $this->capabilities->get($name);
        $this->validateLinks($definition, $links);
        ($this->fulfill)(
            new Request(
                $this->resolveUrl(
                    $definition->url(),
                    $identity
                ),
                Method::unlink(),
                new ProtocolVersion(1, 1),
                Headers::of(
                    $this->generateAcceptHeader(),
                    $this->generateLinkHeader($links)
                )
            )
        );

        return $this;
    }

    public function capabilities(): Capabilities
    {
        return $this->capabilities;
    }

    public function url(): UrlInterface
    {
        return $this->url;
    }

    private function resolveUrl(
        UrlInterface $url,
        Identity $identity
    ): UrlInterface {
        $url = (string) $url;
        $url = \rtrim($url, '/').'/'.$identity;

        return Url::fromString($url);
    }

    private function generateAcceptHeader(): Accept
    {
        return new Accept(
            ...$this
                ->formats
                ->all()
                ->values()
                ->sort(function(Format $a, Format $b): bool {
                    return $a->priority() < $b->priority();
                })
                ->reduce(
                    new Set(Value::class),
                    function(Set $values, Format $format): Set {
                        return $values->add(new AcceptValue(
                            $format->preferredMediaType()->topLevel(),
                            $format->preferredMediaType()->subType()
                        ));
                    }
                )
        );
    }

    private function generateLinkHeader(SetInterface $links): LinkHeader
    {
        return new LinkHeader(
            ...$links->reduce(
                new Set(Value::class),
                function(Set $carry, Link $link): Set {
                    $url = $this->resolveUrl(
                        $this
                            ->capabilities
                            ->get($link->definition())
                            ->url(),
                        $link->identity()
                    );

                    return $carry->add(
                        new LinkValue(
                            Url::fromString((string) $url->path()),
                            $link->relationship(),
                            $link
                                ->parameters()
                                ->reduce(
                                    new Map('string', HeaderParameter::class),
                                    function(Map $carry, string $name, Parameter $parameter): Map {
                                        return $carry->put(
                                            $name,
                                            new HeaderParameter\Parameter(
                                                $parameter->key(),
                                                $parameter->value()
                                            )
                                        );
                                    }
                                )
                        )
                    );
                }
            )
        );
    }

    /**
     * @param SetInterface<link> $links
     *
     * @throws NormalizationException
     */
    private function validateLinks(Definition $definition, SetInterface $links): void
    {
        $links->foreach(function(Link $link) use ($definition): void {
            if (!$definition->allowsLink($link)) {
                throw new NormalizationException;
            }
        });
    }
}


<?PHP

/**
 * Openbizx Framework
 *
 * Based on Openbiz Framework by Rocky Swen (Openbiz LLC)
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: ObjectFactory.php 5155 2013-01-17 07:07:34Z agus.suhartono@gmail.com $
 */

namespace Openbizx\Object;

use Openbizx\Openbizx;
use Openbizx\ClassLoader;
use Openbizx\Object\ObjectFactoryHelper;

/**
 * ObjectFactory is factory class to create metadata based objects
 * (bizview, bizform, bizdataobj...)
 *
 * @package   openbiz.bin
 * @author    Rocky Swen <rocky@phpopenbiz.org>
 * @copyright Copyright (c) 2005-2009, Rocky Swen
 * @access    public
 */
class ObjectFactory
{

    /**
     * Internal array for cache Openbizx\Object\MetaObject
     * @var array
     */
    private $_objectsMap = array();

    /**
     * @var array service definitions
     */
    private $_definitions = [];

    public function setDefinition( $name, $definition )
    {

    }

    public function getDefinition()
    {

    }

    public function __construct()
    {

    }

    public function __destruct()
    {

    }

    /**
     * Get a metadata based object instance.
     * It returns the instance the internal object map or create a new one and save it in the map.
     *
     * @param string $objectName name of object that want to get
     * @return object
     */
    public function getObject($objectName, $new = 0)
    {
        if (isset($this->_objectsMap[$objectName]) && $new == 0) {
            return $this->_objectsMap[$objectName];
        }

        $obj = $this->constructObject($objectName);
        if (!$obj) {
            return null;
        }
        // save object to cache
        $this->_objectsMap[$objectName] = $obj;
        if ($new != 1) {
            if (method_exists($obj, "loadStatefullVars")) {
                $obj->loadStatefullVars(Openbizx::$app->getSessionContext());
            }
        }

        return $obj;
    }

    /**
     * Create a new metadata based object instance
     *
     * @param string $objName name of object will be create
     * @param array $xmlArr propery array of object
     * @return object
     */
    public function createObject($objName, &$xmlArr = null)
    {
        $obj = $this->constructObject($objName, $xmlArr);
        return $obj;
    }

    public function setObject($objName, $obj)
    {
        $this->_objectsMap[$objName] = $obj;
    }

    /**
     * Get all object from the internal object array (object cache)
     *
     * @return array array of object
     */
    public function getAllObjects()
    {
        return $this->_objectsMap;
    }

    /**
     * Construct an instance of an object
     *
     * @param string $objName object name
     * @param array $xmlArr xml array
     * @return object the instance of the object
     */
    protected function constructObject($objName, &$xmlArr = null)
    {

        if (!$xmlArr) {
            $xmlFile = ObjectFactoryHelper::getXmlFileWithPath($objName);
            if ($xmlFile) {
                $xmlArr = ObjectFactoryHelper::getXmlArray($xmlFile);
            } else {

                //$this->_createObjectFromClass($objName);
                /*
                 * if not have metadata, create object from class directly
                 * metadata is on the class it self.                 *
                 */

                $class = str_replace('.', '\\', $objName);

                /*
                $dotPos = strrpos($objName, ".");
                if ($dotPos > 0) { // if has package/namespace
                    $objectPackage =  substr($objName, 0, $dotPos) ;
                    $class = substr($objName, $dotPos + 1);
                } else {
                    $objectPackage = null;
                    $class = $objName;
                }
                *
                */

            }
        }

        if ($xmlArr) {
            $keys = array_keys($xmlArr);
            $root = $keys[0];

            // add by mr_a_ton , atrubut name must match with object name
            $dotPos = strrpos($objName, ".");
            $shortObjectName = $dotPos > 0 ? substr($objName, $dotPos + 1) : $objName;
            if ($xmlArr[$root]["ATTRIBUTES"]["NAME"] == "") {
                $xmlArr[$root]["ATTRIBUTES"]["NAME"] = $shortObjectName;
            } else {
                if ($shortObjectName != $xmlArr[$root]["ATTRIBUTES"]["NAME"]) {
                    trigger_error("Metadata file parsing error for object $objName. Name attribut [" . $xmlArr[$root]["ATTRIBUTES"]["NAME"] . "] not same with object name. Please double check your metadata xml file again.", E_USER_ERROR);
                }
            }

            $class = $xmlArr[$root]["ATTRIBUTES"]["CLASS"];

            //echo __METHOD__.'-'.__LINE__ . ' class : ' . $class . '
';

            // if class has package name as prefix, change the package to the prefix
            $dotPos = strrpos($class, ".");
            if ($dotPos > 0) {
                $classPrefix = substr($class, 0, $dotPos);
                $classPackage = $classPrefix;
                $shortClass = substr($class, $dotPos + 1);
            } else {
                $classPrefix = null;
                $classPackage = null;
                $shortClass = $class;
            }

            //echo 'shortclass : ' . $shortClass .'
' ;
            // set object package
            $dotPos = strrpos($objName, ".");
            $objectPackage = $dotPos > 0 ? substr($objName, 0, $dotPos) : null;
            if (strpos($objectPackage, '@') === 0) {
                $objectPackage = substr($objectPackage, 1);
            }
            if (!$classPackage) {
                $classPackage = $objectPackage;
            }
            $xmlArr[$root]["ATTRIBUTES"]["PACKAGE"] = $objectPackage;
        }

        //$package = $xmlArr[$root]["ATTRIBUTES"]["PACKAGE"];
        //$class = $xmlArr[$root]["ATTRIBUTES"]["CLASS"];

        $class = $shortClass;

        // echo $class . '
';

        $class = $this->getClassNameFromAlias($class);

        if (strrpos($class, '\\' ) !== false) {
            $obj_ref = new $class($xmlArr);
            return $obj_ref;
        }

        //echo $class . '
';
        //echo $classPackage . '
';

        if (!class_exists($class, false)) {
            //echo 'class not exist
';
            $classFile = ClassLoader::getLibFileWithPath($class, $classPackage);
            //echo 'classFile: '.$classFile .'
';
            if (!$classFile) {
                if ($objectPackage) {
                    trigger_error("Cannot find the class with name as $objectPackage.$class", E_USER_ERROR);
                } else {
                    trigger_error("Cannot find the class with name as $class of $objName", E_USER_ERROR);
                }
                exit();
            }
            include_once($classFile);
        }

        //echo 'class_exists($class, false): '. (class_exists($class, false)? 'true':'false') . '
';
        if (class_exists($class, false)) {
            //if ($objName == "collab.calendar.form.EventListForm") { print_r($xmlArr); exit; }
            $obj_ref = new $class($xmlArr);
            if ($obj_ref) {
                return $obj_ref;
            }
        } else {
            trigger_error("Cannot find the class with name as $class in $classFile", E_USER_ERROR);
        }
        return null;
    }

    private function _createObjectFromMetadata() {

    }

    private function _createObjectFromClass($param)
    {

    }

    private $_prefix=[];
    private $_path=[];
    private $_ext=[];

    /**
     * Register Prefix, location and extension of MetaObject
     *
     * @param string $prefix prefix of metaobject, like "Contact" for "Contact.form.ContactForm"
     * @param string $path location of metaobject with $prefix
     * @param array|string $ext array of string, collection of extension that support by prefix
     * @return null
     * @since OpenbizX CubiX
     */
    public function register($prefix, $path, $ext=null) {
        $this->_prefix = $prefix;
        $this->_path = $path;
        if ($ext == null) {
            $this->_ext[] = array('xml');
        } else if (is_array($ext)) {
            $this->_ext[] = $ext;
        } else if (is_string($ext)) {
            $ext[] = array($ext);
        }
    }

    private $_classAlias = [];

    public function setClassAlias($classAlias, $className)
    {
        $this->_classAlias[$classAlias] = $className;
    }

    public function getClassNameFromAlias($className) {
        if ( isset($this->_classAlias[$className])) {
            return $this->_classAlias[$className];
        } else {
            return $className;
        }
    }

    public function setClassAliases($classAliases)
    {
        $this->_classAlias = $classAliases ;
    }

}


<?php

/**
 * Instaphp
 *
 * Copyright (c) 2011 randy sesser <randy@instaphp.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author randy sesser <randy@instaphp.com>
 * @copyright 2011, randy sesser
 * @license http://www.opensource.org/licenses/mit-license The MIT License
 * @package Instaphp
 * @filesource
 */

namespace Instaphp\Instagram;

use Instaphp\Request;
use Instaphp\Response;

/**
 * Users
 * The Users class handles all users request to the API
 * @package Instaphp
 * @version 1.0
 * @author randy sesser <randy@instagram.com>
 */
class Users extends InstagramBase
{

    public function __construct($token = null, $config = array())
    {
        parent::__construct($token, $config);
        $this->api_path = '/users';
    }

    /**
     * Gets the access token from an oAuth request
     * @access public
     * @param string $code The authorization code returned by the oAuth call
     * @param string $scope The scope of the oAuth request
     * @return Response
     */
    public function Authenticate($code, $scope = null)
    {
        if (!empty($code)) {
            $this->AddParams(array(
                'code' => $code,
                'client_secret' => $this->config['client_secret'],
                'grant_type' => 'authorization_code',
                'redirect_uri' => $this->config['redirect_uri']
            ));

            return $this->Post($this->config['oauth_token_uri']);
        }
    }

    /**
     * Gets info about a particular user
     * @access public
     * @param mixed $user_id A user ID or 'self' to get info about the currently authenticated user
     * @return Response
     */
    public function Info($user_id = 'self')
    {
        return $this->Get($this->buildUrl($user_id));
    }

    /**
     * Gets a users feed
     * @access public
     * @param string $token An access token
     * @param Array $params An associative array of key/value pairs to pass to the API.
     * @return Response
     */
    public function Feed(Array $params = array())
    {
        if (!empty($params))
            $this->AddParams($params);

        return $this->Get($this->buildUrl('self/feed/'));
    }

    /**
     * Gets a user most recent media
     * @access public
     * @param mixed $user_id A user ID or 'self' to get info about the currently authenticated user
     * @param Array $params An associative array of key/value pairs to pass to the API
     * @return Response
     */
    public function Recent($user_id, Array $params = array())
    {
        if (!empty($params))
            $this->AddParams($params);

        return $this->Get($this->buildUrl($user_id . '/media/recent/'));
    }

	/**
	 * Gets media liked by the current user
	 * @access public
	 * @param Array $params An associative array of key/value pairs to pass to the API
	 * @return Response
	 */
	public function Liked(Array $params = array())
	{
		if (!empty($params))
			$this->AddParams($params);
		return $this->Get($this->buildUrl('self/media/liked/'));
	}

    /**
     * Search for a user by username
     * @access public
     * @param string $query A username
     * @return Response
     */
    public function Find($query = '')
    {
        $this->AddParam('q', $query);
        return $this->Get($this->buildUrl('search'));
    }

    /**
     * Gets followers of a particular user
     * @access public
     * @param mixed $user_id A user ID or 'self' to get info about the currently authenticated user
     * @param Array $params Additional params to pass to the API
     * @return Response
     */
    public function Following($user_id, Array $params = array())
    {
        if (!empty($params))
            $this->AddParams($params);

        return $this->Get($this->buildUrl($user_id . '/follows'));
    }

    /**
     * Gets a user's followers
     * @access public
     * @param mixed $user_id A user ID or 'self' to get info about the currently authenticated user
     * @param Array $params Additional params to pass to the API
     * @return Response
     */
    public function Followers($user_id, Array $params = array())
    {
        if (!empty($params))
            $this->AddParams($params);

        return $this->Get($this->buildUrl($user_id . '/followed-by'));
    }

    /**
     * Gets requests for follows for a particular user
     * @access public
     * @param mixed $user_id A user ID or 'self' to get info about the currently authenticated user
     * @return Response
     */
    public function Requests($user_id)
    {

    }

    /**
     * Gets the relationship of a user based on the currently authenticated user
     * @access public
     * @param mixed $user_id A user ID or 'self' to get info about the currently authenticated user
     * @return Response
     */
    public function Relationship($user_id)
    {
        return $this->Get($this->buildUrl($user_id . '/relationship'));
    }

    /**
     * Sets a relationship between a particular user and the currently authenticated user
     * @access public
     * @param int $user_id A user ID
     * @param Array $token An associative array of key/value pairs to pass to the API
     * @return Response
     */
    protected function SetRelationship($user_id, $action)
    {
        $this->AddParam('action', $action);
        return $this->Post($this->buildUrl($user_id . '/relationship'));
    }

    /**
     * Follow a user...
     * @access public
     * @param int $user_id A user ID
     * @return Response
     */
    public function Follow($user_id)
    {
        return $this->SetRelationship($user_id, 'follow');
    }

    /**
     * Unfollow a user...
     * @access public
     * @param int $user_id A user ID
     * @return Response
     */
    public function Unfollow($user_id)
    {
        return $this->SetRelationship($user_id, 'unfollow');
    }

    /**
     * Block a user...
     * @access public
     * @param int $user_id A user ID
     * @return Response
     */
    public function Block($user_id)
    {
        return $this->SetRelationship($user_id, 'block');
    }

    /**
     * Unblock a user...
     * @access public
     * @param int $user_id A user ID
     * @return Response
     */
    public function Unblock($user_id)
    {
        $this->SetRelationship($user_id, 'unblock');
    }

    /**
     * Approve a user request...
     * @access public
     * @param int $user_id A user ID
     * @return Response
     */
    public function Approve($user_id)
    {
        $this->SetRelationship($user_id, 'approve');
    }

    /**
     * Deny a user request...
     * @access public
     * @param int $user_id A user ID
     * @return Response
     */
    public function Deny($user_id)
    {
        $this->SetRelationship($user_id, 'deny');
    }
}


<?php
/**
 * @author    Antoine Hedgecock <antoine.hedgecock@gmail.com>
 *
 * @copyright Interactive Solutions
 */

declare(strict_types = 1);

namespace InteractiveSolutions\Bernard\Factory;

use InteractiveSolutions\Bernard\BernardOptions;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class BernardOptionsFactory implements FactoryInterface
{
    /**
     * {@inheritdoc}
     */
    public function createService(ServiceLocatorInterface $serviceLocator):BernardOptions
    {
        return $this->build($serviceLocator);
    }

    public function __invoke(ContainerInterface $container, $requestedName, array $options = null):BernardOptions
    {
        return $this->build($container);
    }

    /**
     * @param ServiceLocatorInterface|ContainerInterface $container
     *
     * @return BernardOptions
     */
    private function build($container):BernardOptions
    {
        /* @var $config array */
        $config = $container->get('config');
        $config = $config['interactive_solutions']['options'][BernardOptions::class] ?? [];

        return new BernardOptions($config);
    }
}


<?php

namespace D4rk4ng3l\Console;

use Symfony\Component\Console\Application as SFApp;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class Application extends SFApp
{

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

    /**
     * @return ContainerInterface
     */
    public function getContainer()
    {
        return $this->container;
    }

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

    /**
     * @param InputInterface  $input
     * @param OutputInterface $output
     */
    protected function configureIO(InputInterface $input, OutputInterface $output)
    {
        parent::configureIO($input, $output);
        if (null !== $this->container) {
            $this->container->set('console.input', $input);
            $this->container->set('console.output', $output);
        }
    }

    /**
     * @param string $name
     *
     * @return \Symfony\Component\Console\Command\Command
     */
    public function find($name)
    {
        $command = parent::find($name);

        if ($command instanceof ContainerAwareInterface) {
            $command->setContainer($this->container);
        }

        return $command;
    }
}


<?php
namespace Chp\MVC;

/**
 * Model for database-methods.
 *
 */
class CDatabaseModel implements \Anax\DI\IInjectionAware
{
  use \Anax\DI\TInjectable;

  /**
   * Get the table name
   *
   * @Return    String    The table name
   */
  public function getSource(){
    return strtolower(implode('', array_slice(explode('\\', get_class($this)), -1)));
  }

  /**
   * Get object properties.
   *
   * @Return    Array   With object properties.
   */
  public function getProperties()
  {
      $properties = get_object_vars($this);
      unset($properties['di']);
      unset($properties['db']);
      unset($properties['user']);

      return $properties;
  }

  /**
   * Set object properties
   *
   * @Param   Array   $properties   Properties to set
   * @Return  Void
   */
  public function setProperties($properties){
    // Update object with incoming values, if any
    if(!empty($properties)){
      foreach($properties as $key => $val){
        $this->$key = $val;
      }
    }
  }

  /**
   * Find and return all
   *
   * @param  	  int	      $page				Wich page paging are at
	 * @param  	  int	      $perPage		Threads per page
   * @return    object                Object of database rows
   */
  public function findAll($page = 1, $perPage = 0)
  {
    $this->db->select()
             ->from($this->getSource());

    if(is_numeric($perPage) && $perPage > 0){
      $this->db->limit($perPage);

      if(is_numeric($page) && $page > 1){
        $offset = $this->paging->getOffset($page, $perPage);
        $this->db->offset($offset);
      }
    }

    $this->db->execute();
    $this->db->setFetchModeClass(__CLASS__);
    return $this->db->fetchAll();
  }

  /**
   * Count all rows in database table
   *
   * @return  int   $row->countRows   Count of rows
   */
  public function countAll(){
	  $this->db->select('COUNT(id) as countRows')
	           ->from($this->getSource());

    $this->db->execute();
    $this->db->setFetchModeClass(__CLASS__);
    $row = $this->db->fetchOne();
    return $row->countRows;
  }

  /**
   * Find and return specific row
   *
   * @Param   Int   $id   Row index
   * @return  this
   */
  public function find($id = 0){
    $this->db->select()
             ->from($this->getSource())
             ->where("id = ?");

    $this->db->execute([$id]);
    return $this->db->fetchInto($this);
  }

  /**
   * Save current object/row
   *
   * @Param   Array     $values     Key/values to save or empty to use object properties
   * @Return  Boolean   True/false  If saving went okey
   */
  public function save($values = []){
    $this->setProperties($values);
    $values = $this->getProperties();

    if(isset($values['id']))
      return $this->update($values);
    else
      return $this->create($values);
  }

  /**
   * Create new row
   *
   * @Param   Array     $values     Key/values to save
   * @Return  Boolean   True/false  If saving went okey
   */
  public function create($values = []){
    $keys   = array_keys($values);
    $values = array_values($values);

    $this->db->insert(
      $this->getSource(),
      $keys
    );

    $res = $this->db->execute($values);

    $this->id = $this->db->lastInsertId();

    return $res;
  }

  /**
   * Update row
   *
   * @Param   Array     $values     Key/values to save
   * @Return  Boolean   True/false  If saving went okey
   */
  public function update($values = []){
    if(key_exists('id', $values)){
      $this->id = $values['id'];
      unset($values['id']);
    }

    $keys   = array_keys($values);
    $values = array_values($values);

    // Its update, remove id and use where-clause
    $values[] = $this->id;

    $this->db->update(
      $this->getSource(),
      $keys,
      "id = ?"
    );

    return $this->db->execute($values);
  }

  /**
   * Delete row
   *
   * @Param   Int       $id         Row index
   * @Return  Boolean   True/false  If deleting went okey
   */
  public function delete($id = 0){
    $this->db->delete(
      $this->getSource(),
      'id = ?'
    );

    return $this->db->execute([$id]);
  }

  /**
   * Build a select-query
   *
   * @Param   String    $columns   Columns to select
   * @Return  Object    $this
   */
  public function query($columns = "*"){
    $this->db->select($columns)
             ->from($this->getSource());

    return $this;
  }

  /**
   * Build the where part
   *
   * @Param   String    $condition    For bulding the where part of the query
   * @Return  Object    $this
   */
  public function where($condition){
    $this->db->where($condition);

    return $this;
  }

  /**
   * Build more on the where part
   *
   * @Param   string    $condition    For bulding the where part of the query
   * @Return  Object    $this
   */
  public function andWhere($condition){
    $this->db->andWhere($condition);

    return $this;
  }

  /**
   * Build a limit for query-request
   *
   * @Param   Integer    $condition    For building limit part of query
   * @Return  Object    $this
   */
  public function limit($condition){
    $this->db->limit($condition);

    return $this;
  }

  /**
   * Build a offset for query-request
   *
   * @Param   Integer    $condition    For building offset part of query
   * @Return  Object     $this
   */
  public function offset($condition){
    $this->db->offset($condition);

    return $this;
  }

  /**
   * Execute the query built
   *
   * @Param   String    $query    Custom query
   * @Return  Object    $this
   */
  public function execute($params = []){
    $this->db->execute($this->db->getSQL(), $params);
    $this->db->setFetchModeClass(__CLASS__);

    return $this->db->fetchAll();
  }
}
?>


<?php

namespace Environaut\Export\Formatter;

use Environaut\Report\IReport;
use Environaut\Export\Formatter\BaseFormatter;

/**
 * Writes all or specific groups of settings as JSON to a file.
 *
 * Supported parameters include:
 * - "location": Path and filename to write (defaults to 'environaut-config.json').
 * - "groups": Array of group names. Only settings with those groups are written.
 *             By default all settings regardless of their group are written.
 * - "pretty": Whether to write the JSON object pretty printed to the file.
 *             Defaults to true, but only works from PHP 5.4 upwards.
 * - "nested": Defines whether to group settings by their group (defaults to true).
 */
class JsonSettingsWriter extends BaseFormatter
{
    /**
     * Writes all or specific groups of settings as a JSON file and
     * returns a message with some information about that.
     *
     * @param IReport $report report to take results (and settings) from
     *
     * @return string messages for CLI output
     */
    public function format(IReport $report)
    {
        $output = '';
        $params = $this->getParameters();

        $file = $params->get('location', 'environaut-config.json');
        $pretty = $params->get('pretty', true);
        $nested = $params->get('nested', true);
        $groups = $params->get('groups');

        if (is_writable($file)) {
            $output .= '<comment>Overwriting</comment> ';
        } else {
            $output .= 'Writing ';
        }

        if (empty($groups)) {
            $output .= 'all groups ';
        } else {
            $output .= 'group(s) "' . implode(', ', $groups) . '" ';
        }

        $output .= 'to file "<comment>' . $file . '</comment>"...';

        $flags = JSON_FORCE_OBJECT;
        if ($pretty && version_compare(PHP_VERSION, '5.4.0') >= 0) {
            $flags |= JSON_PRETTY_PRINT;
        }

        $all_settings = $report->getSettingsAsArray($groups);

        $grouped_settings = array();
        foreach ($all_settings as $setting) {
            if ($nested === true) {
                $grouped_settings[$setting['group']][$setting['name']] = $setting['value'];
            } else {
                $grouped_settings[$setting['name']] = $setting['value'];
            }
        }

        $content = json_encode($grouped_settings, $flags);

        $ok = file_put_contents($file, $content, LOCK_EX);

        if ($ok !== false) {
            $output .= '<info>ok</info>.';
        } else {
            $output .= '<error>FAILED</error>.';
        }

        return $output;
    }
}


<?php

namespace CatLab\Charon\Laravel\Middleware;

use CatLab\Base\Helpers\ArrayHelper;
use CatLab\Charon\Library\TransformerLibrary;
use Closure;

/**
 * Class InputTransformer
 *
 * Run all applicable parameters through a transformer.
 *
 * @package CatLab\Charon\Laravel\Middleware
 */
class InputTransformer extends AbstractMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @param string $in What container should contain the input?
     * @param string $type Container of parameter that should be transformed (query, header, ...)
     * @param string $name Name of parameter that should be transformed
     * @param string $transformer Transformer that should be used to transform the parameter.
     * @return mixed
     * @throws \CatLab\Charon\Exceptions\InvalidTransformer
     */
    public function handle($request, Closure $next, $in, $type, $name, $transformer)
    {
        $this->transformParameter($request, $in, $type, $name, $transformer);
        return $next($request);
    }

    /**
     * @param \Illuminate\Http\Request $request
     * @param $in
     * @param $type
     * @param $name
     * @param $transformerName
     * @throws \CatLab\Charon\Exceptions\InvalidTransformer
     */
    protected function transformParameter($request, $in, $type, $name, $transformerName)
    {
        $value = $this->getInput($request, $in, $name);

        if ($value === null) {
            return;
        }

        $transformer = TransformerLibrary::make($transformerName);
        if (!$transformer) {
            throw new \InvalidArgumentException("Transformer " . $transformerName . " could not be created");
        }

        if (ArrayHelper::isIterable($value)) {
            foreach ($value as $k => $v) {
                $value[$k] = $transformer->toParameterValue($v);
            }
        } else {
            $value = $transformer->toParameterValue($value);
        }

        // Actually set the input in the request
        $this->setInput($request, $in, $name, $value);
    }
}


<?php

namespace vr\core;

use yii\base\InvalidConfigException;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;

/**
 * Class ActiveQueryTrait
 * @package vr\core
 */
trait ActiveQueryTrait
{
    /**
     * @var
     */
    private $_forUpdate;

    /**
     * @return self
     */
    public function first()
    {
        /** @var ActiveQuery $this */

        $primaryKey = call_user_func([$this->modelClass, 'primaryKey']);

        /** @noinspection PhpUndefinedMethodInspection */
        return $this->orderBy([
            $primaryKey[0] => SORT_ASC,
        ])->one();
    }

    /**
     * @return self
     */
    public function last()
    {
        /** @var self $this */

        $primaryKey = call_user_func([$this->modelClass, 'primaryKey']);

        /** @noinspection PhpUndefinedMethodInspection */
        return $this->orderBy([
            $primaryKey[0] => SORT_DESC,
        ])->one();
    }

    /**
     * @param $condition
     *
     * @return self
     * @throws InvalidConfigException
     */
    public function identifiedBy($condition)
    {
        /** @var ActiveQuery $this */

        if (!ArrayHelper::isAssociative($condition)) {

            $primaryKey = call_user_func([$this->modelClass, 'primaryKey']);

            $table = call_user_func([$this->modelClass, 'tableName']);

            if (isset($primaryKey[0])) {
                $condition = [$table . '.' . $primaryKey[0] => $condition];
            } else {
                throw new InvalidConfigException('"' . get_called_class() . '" must have a primary key.');
            }
        }

        return $this->andWhere($condition);
    }

    /**
     * @param bool $forUpdate
     *
     * @return $this
     */
    public function forUpdate($forUpdate = true)
    {
        $this->_forUpdate = $forUpdate;

        return $this;
    }

    /**
     * @return self
     */
    public function random()
    {
        /** @var self $this */
        return $this->orderBy('rand()');
    }

    /**
     * @param null $db
     *
     * @return \yii\db\Command
     */
    public function createCommand($db = null)
    {
        /* @var $modelClass ActiveRecord */
        $modelClass = $this->modelClass;
        if ($db === null) {
            $db = $modelClass::getDb();
        }

        if ($this->sql === null) {
            /** @noinspection PhpParamsInspection */
            list($sql, $params) = $db->getQueryBuilder()->build($this);
        } else {
            $sql    = $this->sql;
            $params = $this->params;
        }

        if ($this->_forUpdate) {
            $sql .= ' FOR UPDATE';
        }

        $command = $db->createCommand($sql, $params);
        $this->setCommandCache($command);

        return $command;
    }
}