<?php
/**
 * OpenWebPresence Support Library - openwebpresence.com
 *
 * @copyright 2001 - 2017, Brian Tafoya.
 * @package   OwpFramework
 * @author    Brian Tafoya <btafoya@briantafoya.com>
 * @version   1.0
 * @license   MIT
 * @license   https://opensource.org/licenses/MIT The MIT License
 * @category  OpenWebPresence_Support_Library
 * @link      http://openwebpresence.com OpenWebPresence
 *
 * Copyright (c) 2017, Brian Tafoya
 *
 * 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.
 */

/**
 * OwpFramework Bootstrap Class.
 * Open Presence Framework Class Bootstrap.
 */
class OwpFramework
{

    /**
     * @var string $root_path Set the root file path.
     */
    static public $root_path = null;

    /**
     * @var array $debugging Debugging array.
     */
    static public $debugging = null;

    /**
     * @var boolean $debug Is debugging enabled by default.
     */
    static public $debug = false;

    /**
     * @var int $userID UserID.
     */
    static public $userID = 0;

    /**
     * @var string $uuid Unique uuid().
     */
    static public $uuid = null;

    /**
     * @var object $ezSqlDB The ezSQL Database Object.
     */
    static public $ezSqlDB;

    /**
     * @var string $current_web_root The web root url.
     */
    static public $current_web_root;

    /**
     * @var object $OwpSupportMethods OpenWebPresence support methods.
     */
    static public $OwpSupportMethods;

    /**
     * @var string $default_action Default action.
     */
    static public $default_action = "home";

    /**
     * @var string $requested_action The requested action.
     */
    static public $requested_action;

    /**
     * @var string $modMethods Mod methods object.
     */
    static public $modMethods = null;

    /**
     * @var string $modAvailableMethods Mod methods available.
     */
    static public $modAvailableMethods = array();

    /**
     * @var string $theme Active theme.
     */
    static public $theme = null;

    /**
     * @var object $ezSqlDB ezSQL Database Object.
     */
    static public $userClass;

    /**
     * @var object $frameworkObject Framework Class Object.
     */
    static public $frameworkObject;

    /**
     * @var object $defaultAction Default function.
     */
    static public $defaultAction;

    /**
     * @var object $actionsConfig Default config.
     */
    static public $actionsConfig;

    /**
     * @var object $actionsConfig Default config.
     */
    static public  $actionsConfigFileLocation;

    /**
     * Constructor
     *
     * @method void __construct()
     * @access public
     * @throws Exception Missing theme config directive file.
     *
     * @author  Brian Tafoya <btafoya@briantafoya.com>
     * @version 1.0
     */
    public function __construct()
    {
        $this->build();
    }//end __construct()

    /**
     * build
     *
     * @method void build() Builds the framework objects
     * @return array|object
     * @throws Exception
     *
     * @author  Brian Tafoya <btafoya@briantafoya.com>
     * @version 1.0
     */
    static public function build()
    {

        /*
            * Set the root path
         */
        self::$root_path = ROOT_PATH;

        /*
            * Set the current web root
        */
        self::$current_web_root = CURRENT_WEB_ROOT;

        /*
            * Generate $uuid based on OwpSupportMethods->uuid().
         */
        $_SESSION["uuid"] = OwpSupportMethods::uuid();
        self::$uuid = $_SESSION["uuid"];

        /*
            * Set the theme
         */
        self::$theme = $_ENV["THEME"];

        /*
            * Init the debugger
         */
        self::$debug = ((int) $_ENV["ISDEV"] ? true : false);

        /*
            * Init the database class
         */
        self::$ezSqlDB = new OwpDBMySQLi($_ENV["DB_USER"], $_ENV["DB_PASS"], $_ENV["DB_NAME"], $_ENV["DB_HOST"]);
        self::$ezSqlDB->use_disk_cache = false;
        self::$ezSqlDB->cache_queries  = false;
        self::$ezSqlDB->hide_errors();

        /*
            * Default Request Definition
         */
        self::$defaultAction = [
                                 "none"    => "home",
                                 "isUser"  => "home",
                                 "isAdmin" => "home",
                                ];

        /*
            * Default Action Definition
         */
        self::$actionsConfig = [
                                "404" => [
                                          "view"        => [
                                                            "app/themes/default/common/header.inc.php",
                                                            "app/themes/default/common/nav.inc.php",
                                                            "app/themes/default/pages/404.inc.php",
                                                            "app/themes/default/common/footer.inc.php",
                                                           ],
                                          "mod"         => [],
                                          "js"          => [],
                                          "css"         => [],
                                          "permissions" => [
                                                            "isUser"  => 0,
                                                            "isAdmin" => 0,
                                                           ],
                                         ],
                               ];

        /*
            * ActionsConfigFileLocation
         */
        $actionsConfig = null;
        $defaultAction = null;

        self::$defaultAction = json_decode(file_get_contents(ROOT_PATH."app/themes/" . self::$theme . "/config/defaultAction.json"), 1);
        self::$actionsConfig = json_decode(file_get_contents(ROOT_PATH."app/themes/" . self::$theme . "/config/actionsConfig.json"), 1);

        /*
            * Create the frameworkObject
        */
        self::$frameworkObject = array(
                                  "frameworkVariables" => array(
                                                           "theme"            => self::$theme,
                                                           "current_web_root" => (string) self::$current_web_root,
                                                           "root_path"        => (string) self::$root_path,
                                                           "requested_action" => (string) self::$requested_action,
                                                           "uuid"             => (string) self::$uuid,
                                                          ),
                                  "ezSqlDB"            => (object) self::$ezSqlDB,
                                  "mod_data"           => new OwpMod(),
                                 );

        /*
            * Load the user class
         */
        self::$userClass = new OwpUsers();
        self::$userClass->rememberMe();

        /*
            * Add it to the $frameworkObject array.
         */
        self::$frameworkObject["userClass"] = (object) self::$userClass;

        /*
            * Set the requested action
         */
        if(self::$userClass->isLoggedIn()) {
            if(self::$userClass->isAdmin()) {
                self::$default_action = self::$defaultAction["isAdmin"];
            } else {
                self::$default_action = self::$defaultAction["isUser"];
            }
        } else {
            self::$default_action = self::$defaultAction["none"];
        }

        self::$requested_action = (isset($_GET["_route_"]) ? OwpSupportMethods::filterAction($_GET["_route_"]) : self::$default_action);

        self::$frameworkObject["frameworkVariables"]["requested_action"] = (string) self::$requested_action;
        self::$frameworkObject["frameworkVariables"]["default_action"] = (string) self::$default_action;
        self::$frameworkObject["actionsConfig"] = (array) self::$actionsConfig;
        self::$frameworkObject["defaultAction"] = (array) self::$defaultAction;

        return self::$frameworkObject;

    }//end build()

    /**
     * __get($name)
     *
     * @method __GET($name) Getter
     * @param  $name
     * @return mixed
     */
    public function __get($name)
    {
        if(isset(self::$frameworkObject)) {
            return self::$frameworkObject;
        }
        if(isset($this->$name)) {
            return $this->$name;
        }

        self::build();
        if(isset(self::$frameworkObject)) {
            return self::$frameworkObject;
        }
        if(isset($this->$name)) {
            return $this->$name;
        }

        throw new InvalidArgumentException($name." does not exist!");

    }//end __get()

    /**
     * getFrameworkObject().
     * Return the entire framework object for reference.
     *
     * @method getFrameworkObject() Return the entire framework object for reference.
     * @return array|object
     */
    public function getFrameworkObject()
    {
        return $this->frameworkObject;

    }//end getFrameworkObject()

    /**
     * Debug
     *
     * @method void __debugInfo()
     * @access public
     * @return object
     *
     * @author  Brian Tafoya <btafoya@briantafoya.com>
     * @version 1.0
     */
    public function __debugInfo()
    {
        return $this->frameworkObject;

    }//end __debugInfo()

}//end class


<?php

namespace Reaction\Web;

use Psr\Http\Message\StreamInterface;
use Reaction\Base\RequestAppComponent;
use Reaction\Exceptions\HttpException;
use Reaction\Exceptions\InvalidArgumentException;
use Reaction\Exceptions\InvalidConfigException;
use Reaction\Helpers\ArrayHelper;

/**
 * Class ResponseBuilder
 * @package Reaction\Web
 */
class ResponseBuilder extends RequestAppComponent implements ResponseBuilderInterface
{
    /**
     * @var string|array Response class config array or class name
     */
    public $responseClass = 'Reaction\Web\Response';
    /**
     * @var string HTTP version
     */
    public $version = '1.1';
    /**
     * @var string the charset of the text response. If not set, it will use
     * the value of [[BaseApplication::charset]].
     */
    public $charset;
    /**
     * @var string the response format. This determines how to convert [[data]] into [[content]]
     * when the latter is not set. The value of this property must be one of the keys declared in the [[formatters]] array.
     * By default, the following formats are supported:
     *
     * - [[FORMAT_RAW]]: the data will be treated as the response content without any conversion.
     *   No extra HTTP header will be added.
     * - [[FORMAT_HTML]]: the data will be treated as the response content without any conversion.
     *   The "Content-Type" header will set as "text/html".
     * - [[FORMAT_JSON]]: the data will be converted into JSON format, and the "Content-Type"
     *   header will be set as "application/json".
     * - [[FORMAT_JSONP]]: the data will be converted into JSONP format, and the "Content-Type"
     *   header will be set as "text/javascript". Note that in this case `$data` must be an array
     *   with "data" and "callback" elements. The former refers to the actual data to be sent,
     *   while the latter refers to the name of the JavaScript callback.
     * - [[FORMAT_XML]]: the data will be converted into XML format. Please refer to [[XmlResponseFormatter]]
     *   for more details.
     *
     * You may customize the formatting process or support additional formats by configuring [[formatters]].
     * @see formatters
     */
    public $format = Response::FORMAT_HTML;
    /**
     * @var array the formatters for converting data into the response content of the specified [[format]].
     * The array keys are the format names, and the array values are the corresponding configurations
     * for creating the formatter objects.
     * @see format
     * @see defaultFormatters
     */
    public $formatters = [];

    /**
     * @var int Status code
     */
    protected $_statusCode = 200;
    /**
     * @var int Status text
     */
    protected $_statusText = 'OK';
    /**
     * @var CookieCollection Collection of request cookies.
     */
    protected $_cookies;
    /**
     * @var HeaderCollection Collection of request headers.
     */
    protected $_headers;
    /**
     * @var string|array|StreamInterface Response body
     */
    protected $_body;

    /**
     * @inheritdoc
     */
    public function init()
    {
        if (!isset($this->charset) && isset($this->app)) {
            $this->charset = $this->app->charset;
        }
        $this->formatters = array_merge($this->defaultFormatters(), $this->formatters);
    }

    /**
     * Get status code
     * @return int
     */
    public function getStatusCode() {
        return $this->_statusCode;
    }

    /**
     * Set status code
     * @param int $code
     * @return ResponseBuilderInterface
     */
    public function setStatusCode($code = 200) {
        $this->_statusCode = $code;
        $this->_statusText = isset(Response::$httpStatuses[$this->_statusCode]) ? Response::$httpStatuses[$this->_statusCode] : '';
        return $this;
    }

    /**
     * Sets the response status code based on the exception.
     * @param \Exception|\Error $e the exception object.
     * @throws InvalidArgumentException if the status code is invalid.
     * @return ResponseBuilderInterface the response object itself
     */
    public function setStatusCodeByException($e)
    {
        if ($e instanceof HttpException) {
            $this->setStatusCode($e->statusCode);
        } else {
            $this->setStatusCode(500);
        }

        return $this;
    }

    /**
     * Set Response format
     * @param string $format
     * @return ResponseBuilderInterface
     */
    public function setFormat($format) {
        $this->format = $format;
        return $this;
    }

    /**
     * Set Response body
     * @param string|array|StreamInterface $body
     * @return ResponseBuilderInterface
     */
    public function setBody($body) {
        $this->_body = $body;
        return $this;
    }

    /**
     * Get Response body without formatting
     * @return array|StreamInterface|string
     */
    public function getRawBody() {
        return $this->_body;
    }

    /**
     * Get Response body with formatting
     * @return array|null|StreamInterface|string
     * @throws InvalidConfigException
     */
    public function getFormattedBody() {
        $body = $this->getRawBody();
        $bodyFormatted = null;
        if ($body instanceof StreamInterface) {
            return $body;
        } elseif (isset($this->formatters[$this->format])) {
            $formatter = $this->formatters[$this->format];
            if (!is_object($formatter)) {
                $this->formatters[$this->format] = $formatter = \Reaction::create($formatter);
            }
            if ($formatter instanceof ResponseFormatterInterface) {
                $bodyFormatted = $formatter->format($this);
            } else {
                throw new InvalidConfigException("The '{$this->format}' response formatter is invalid. It must implement the ResponseFormatterInterface.");
            }
        } elseif ($this->format === Response::FORMAT_RAW) {
            $bodyFormatted = $body;
        } else {
            throw new InvalidConfigException("Unsupported response format: {$this->format}");
        }

        if (is_array($bodyFormatted)) {
            throw new InvalidArgumentException('Response content must not be an array.');
        } elseif (is_object($bodyFormatted)) {
            if (method_exists($bodyFormatted, '__toString')) {
                $bodyFormatted = $bodyFormatted->__toString();
            } else {
                throw new InvalidArgumentException('Response content must be a string or an object implementing __toString().');
            }
        }
        return $bodyFormatted;
    }

    /**
     * Get Response body and optionally format it
     * @param bool $format
     * @return array|StreamInterface|string
     * @throws InvalidConfigException
     */
    public function getBody($format = false) {
        if ($format) {
            return $this->getFormattedBody();
        }
        return $this->_body;
    }

    /**
     * Returns the header collection.
     * The header collection contains the currently registered HTTP headers.
     * @return HeaderCollection the header collection
     */
    public function getHeaders()
    {
        if ($this->_headers === null) {
            $this->_headers = new HeaderCollection();
        }

        return $this->_headers;
    }

    /**
     * Returns the cookie collection.
     *
     * Through the returned cookie collection, you add or remove cookies as follows,
     *
     * ```php
     * // add a cookie
     * $response->cookies->add(new Cookie([
     *     'name' => $name,
     *     'value' => $value,
     * ]);
     *
     * // remove a cookie
     * $response->cookies->remove('name');
     * // alternatively
     * unset($response->cookies['name']);
     * ```
     *
     * @return CookieCollection the cookie collection.
     */
    public function getCookies()
    {
        if ($this->_cookies === null) {
            $this->_cookies = new CookieCollection();
        }

        return $this->_cookies;
    }

    /**
     * Redirects the browser to the specified URL.
     *
     * This method adds a "Location" header to the current response. Note that it does not send out
     * the header until [[send()]] is called. In a controller action you may use this method as follows:
     *
     * ```php
     * return $app->response->redirect($url);
     * ```
     *
     * In AJAX mode, this normally will not work as expected unless there are some
     * client-side JavaScript code handling the redirection. To help achieve this goal,
     * this method will send out a "X-Redirect" header instead of "Location".
     *
     * If you use the "yii" JavaScript module, it will handle the AJAX redirection as
     * described above. Otherwise, you should write the following JavaScript code to
     * handle the redirection:
     *
     * ```javascript
     * $document.ajaxComplete(function (event, xhr, settings) {
     *     var url = xhr && xhr.getResponseHeader('X-Redirect');
     *     if (url) {
     *         window.location = url;
     *     }
     * });
     * ```
     *
     * @param string|array $url the URL to be redirected to. This can be in one of the following formats:
     *
     * - a string representing a URL (e.g. "http://example.com")
     * - a string representing a URL alias (e.g. "@example.com")
     * - an array in the format of `[$route, ...name-value pairs...]` (e.g. `['site/index', 'ref' => 1]`).
     *   Note that the route is with respect to the whole application, instead of relative to a controller or module.
     *   [[Url::to()]] will be used to convert the array into a URL.
     *
     * Any relative URL that starts with a single forward slash "/" will be converted
     * into an absolute one by prepending it with the host info of the current request.
     *
     * @param int $statusCode the HTTP status code. Defaults to 302.
     * See <https://tools.ietf.org/html/rfc2616#section-10>
     * for details about HTTP status code
     * @param bool $checkAjax whether to specially handle AJAX (and PJAX) requests. Defaults to true,
     * meaning if the current request is an AJAX or PJAX request, then calling this method will cause the browser
     * to redirect to the given URL. If this is false, a `Location` header will be sent, which when received as
     * an AJAX response, may NOT cause browser redirection.
     * Takes effect only when request header `X-Ie-Redirect-Compatibility` is absent.
     * @return ResponseBuilderInterface
     */
    public function redirect($url, $statusCode = 302, $checkAjax = true)
    {
        if (is_array($url) && isset($url[0])) {
            // ensure the route is absolute
            $url[0] = '/' . ltrim($url[0], '/');
        }
        $url = $this->app->helpers->url->to($url);
        if (strncmp($url, '/', 1) === 0 && strncmp($url, '//', 2) !== 0) {
            $url = $this->app->reqHelper->getHostInfo() . $url;
        }

        if ($checkAjax) {
            if ($this->app->reqHelper->getIsAjax()) {
                if ($this->app->reqHelper->getHeaders()->get('X-Ie-Redirect-Compatibility') !== null && $statusCode === 302) {
                    // Ajax 302 redirect in IE does not work. Change status code to 200. See https://github.com/yiisoft/yii2/issues/9670
                    $statusCode = 200;
                }
                $this->getHeaders()->set('X-Redirect', $url);
            } else {
                $this->getHeaders()->set('Location', $url);
            }
        } else {
            $this->getHeaders()->set('Location', $url);
        }

        $this->setBody(null);
        $this->setStatusCode($statusCode);

        return $this;
    }

    /**
     * Refreshes the current page.
     * The effect of this method call is the same as the user pressing the refresh button of his browser
     * (without re-posting data).
     *
     * In a controller action you may use this method like this:
     *
     * ```php
     * return $app->response->refresh();
     * ```
     *
     * @param string $anchor the anchor that should be appended to the redirection URL.
     * Defaults to empty. Make sure the anchor starts with '#' if you want to specify it.
     * @return ResponseBuilderInterface
     */
    public function refresh($anchor = '')
    {
        return $this->redirect($this->app->reqHelper->getUrl() . $anchor);
    }

    /**
     * Build response object
     * @return Response
     */
    public function build() {
        $response = $this->createEmptyResponse();

        return $response;
    }

    /**
     * Create Response instance
     * @return Response
     */
    protected function createEmptyResponse() {
        $config = [];
        $body = $this->getFormattedBody();
        $params = [
            $this->statusCode,
            $this->getHeadersPrepared(),
            $body,
            $this->version,
            $this->_statusText
        ];
        if (is_array($this->responseClass)) {
            $config = ArrayHelper::merge($config, $this->responseClass);
        } else {
            $config['class'] = $this->responseClass;
        }
        /** @var Response $response */
        $response = \Reaction::create($config, $params);
        return $response;
    }

    /**
     * Get prepared headers array
     * @return array
     * @throws InvalidConfigException
     */
    protected function getHeadersPrepared() {
        $cookiesData = $this->getCookiesPrepared();
        foreach ($cookiesData as $cookieStr) {
            $this->headers->add('Set-Cookie', $cookieStr);
        }
        $headersArray = [];
        if ($this->_headers) {
            foreach ($this->getHeaders() as $name => $values) {
                $name = str_replace(' ', '-', ucwords(str_replace('-', ' ', $name)));
                if (!isset($headersArray[$name])) {
                    $headersArray[$name] = [];
                }
                foreach ($values as $value) {
                    $headersArray[$name][] = $value;
                }
            }
        }
        return $headersArray;
    }

    /**
     * Get cookies prepared for 'Set-Cookie' header
     * @return string[]
     * @throws InvalidConfigException
     */
    protected function getCookiesPrepared() {
        $cookies = [];
        if ($this->_cookies) {
            $request = $this->app->reqHelper;
            if ($request->enableCookieValidation) {
                if ($request->cookieValidationKey == '') {
                    throw new InvalidConfigException(get_class($request) . '::cookieValidationKey must be configured with a secret key.');
                }
                $validationKey = $request->cookieValidationKey;
            } else {
                $validationKey = null;
            }
            foreach ($this->getCookies() as $name => $cookie) {
                /** @var Cookie $cookie */
                $cookies[] = $cookie->getForHeader($validationKey);
            }
        }

        return $cookies;
    }

    protected function prepareBody() {

    }

    /**
     * Get default formatters
     * @return array the formatters that are supported by default
     */
    protected function defaultFormatters()
    {
        return [
            Response::FORMAT_HTML => [
                'class' => 'Reaction\Web\Formatters\HtmlResponseFormatter',
            ],
            Response::FORMAT_XML => [
                'class' => 'Reaction\Web\Formatters\XmlResponseFormatter',
            ],
            Response::FORMAT_JSON => [
                'class' => 'Reaction\Web\Formatters\JsonResponseFormatter',
            ],
            Response::FORMAT_JSONP => [
                'class' => 'Reaction\Web\Formatters\JsonResponseFormatter',
                'useJsonp' => true,
            ],
        ];
    }
}


<?php

namespace Reaction\Base;

use ArrayAccess;
use ArrayIterator;
use ArrayObject;
use IteratorAggregate;
use React\Promise\ExtendedPromiseInterface;
use Reaction;
use Reaction\Exceptions\Model\ValidationError;
use Reaction\Exceptions\InvalidArgumentException;
use Reaction\Exceptions\InvalidConfigException;
use Reaction\Helpers\Inflector;
use Reaction\I18n\TranslatorInterface;
use Reaction\RequestApplicationInterface;
use Reaction\Validators\RequiredValidator;
use Reaction\Validators\Validator;
use function Reaction\Promise\reject;
use ReflectionClass;

/**
 * Model is the base class for data models.
 *
 * Model implements the following commonly used features:
 *
 * - attribute declaration: by default, every public class member is considered as
 *   a model attribute
 * - attribute labels: each attribute may be associated with a label for display purpose
 * - massive attribute assignment
 * - scenario-based validation
 *
 * Model also raises the following events when performing data validation:
 *
 * - [[EVENT_BEFORE_VALIDATE]]: an event raised at the beginning of [[validate()]]
 * - [[EVENT_AFTER_VALIDATE]]: an event raised at the end of [[validate()]]
 *
 * You may directly use Model to store model data, or extend it with customization.
 *
 * For more details and usage information on Model, see the [guide article on models](guide:structure-models).
 *
 * @property \Reaction\Validators\Validator[] $activeValidators The validators applicable to the current
 * [[scenario]]. This property is read-only.
 * @property array $attributes Attribute values (name => value).
 * @property array $errors An array of errors for all attributes. Empty array is returned if no error. The
 * result is a two-dimensional array. See [[getErrors()]] for detailed description. This property is read-only.
 * @property array $firstErrors The first errors. The array keys are the attribute names, and the array values
 * are the corresponding error messages. An empty array will be returned if there is no error. This property is
 * read-only.
 * @property ArrayIterator $iterator An iterator for traversing the items in the list. This property is
 * read-only.
 * @property string $scenario The scenario that this model is in. Defaults to [[SCENARIO_DEFAULT]].
 * @property ArrayObject|\Reaction\Validators\Validator[] $validators All the validators declared in the model.
 * This property is read-only.
 *
 * Borrowed from yii2
 */
class Model extends Component implements StaticInstanceInterface, IteratorAggregate, TranslatorInterface, ArrayAccess, Arrayable
{
    use ArrayableTrait;
    use StaticInstanceTrait;

    /**
     * The name of the default scenario.
     */
    const SCENARIO_DEFAULT = 'default';
    /**
     * @event ModelEvent an event raised at the beginning of [[validate()]]. You may set
     * [[ModelEvent::isValid]] to be false to stop the validation.
     */
    const EVENT_BEFORE_VALIDATE = 'beforeValidate';
    /**
     * @event Event an event raised at the end of [[validate()]]
     */
    const EVENT_AFTER_VALIDATE = 'afterValidate';

    /**
     * @var RequestApplicationInterface|null
     */
    public $app;

    /**
     * @var array validation errors (attribute name => array of errors)
     */
    private $_errors;
    /**
     * @var ArrayObject list of validators
     */
    private $_validators;
    /**
     * @var string current scenario
     */
    private $_scenario = self::SCENARIO_DEFAULT;

    /**
     * Returns the validation rules for attributes.
     *
     * Validation rules are used by [[validate()]] to check if attribute values are valid.
     * Child classes may override this method to declare different validation rules.
     *
     * Each rule is an array with the following structure:
     *
     * ```php
     * [
     *     ['attribute1', 'attribute2'],
     *     'validator type',
     *     'on' => ['scenario1', 'scenario2'],
     *     //...other parameters...
     * ]
     * ```
     *
     * where
     *
     *  - attribute list: required, specifies the attributes array to be validated, for single attribute you can pass a string;
     *  - validator type: required, specifies the validator to be used. It can be a built-in validator name,
     *    a method name of the model class, an anonymous function, or a validator class name.
     *  - on: optional, specifies the [[scenario|scenarios]] array in which the validation
     *    rule can be applied. If this option is not set, the rule will apply to all scenarios.
     *  - additional name-value pairs can be specified to initialize the corresponding validator properties.
     *    Please refer to individual validator class API for possible properties.
     *
     * A validator can be either an object of a class extending [[Validator]], or a model class method
     * (called *inline validator*) that has the following signature:
     *
     * ```php
     * // $params refers to validation parameters given in the rule
     * function validatorName($attribute, $params)
     * ```
     *
     * In the above `$attribute` refers to the attribute currently being validated while `$params` contains an array of
     * validator configuration options such as `max` in case of `string` validator. The value of the attribute currently being validated
     * can be accessed as `$this->$attribute`. Note the `$` before `attribute`; this is taking the value of the variable
     * `$attribute` and using it as the name of the property to access.
     *
     * Reaction also provides a set of [[Validator::builtInValidators|built-in validators]].
     * Each one has an alias name which can be used when specifying a validation rule.
     *
     * Below are some examples:
     *
     * ```php
     * [
     *     // built-in "required" validator
     *     [['username', 'password'], 'required'],
     *     // built-in "string" validator customized with "min" and "max" properties
     *     ['username', 'string', 'min' => 3, 'max' => 12],
     *     // built-in "compare" validator that is used in "register" scenario only
     *     ['password', 'compare', 'compareAttribute' => 'password2', 'on' => 'register'],
     *     // an inline validator defined via the "authenticate()" method in the model class
     *     ['password', 'authenticate', 'on' => 'login'],
     *     // a validator of class "DateRangeValidator"
     *     ['dateRange', 'DateRangeValidator'],
     * ];
     * ```
     *
     * Note, in order to inherit rules defined in the parent class, a child class needs to
     * merge the parent rules with child rules using functions such as `array_merge()`.
     *
     * @return array validation rules
     * @see scenarios()
     */
    public function rules()
    {
        return [];
    }

    /**
     * Returns a list of scenarios and the corresponding active attributes.
     *
     * An active attribute is one that is subject to validation in the current scenario.
     * The returned array should be in the following format:
     *
     * ```php
     * [
     *     'scenario1' => ['attribute11', 'attribute12', ...],
     *     'scenario2' => ['attribute21', 'attribute22', ...],
     *     ...
     * ]
     * ```
     *
     * By default, an active attribute is considered safe and can be massively assigned.
     * If an attribute should NOT be massively assigned (thus considered unsafe),
     * please prefix the attribute with an exclamation character (e.g. `'!rank'`).
     *
     * The default implementation of this method will return all scenarios found in the [[rules()]]
     * declaration. A special scenario named [[SCENARIO_DEFAULT]] will contain all attributes
     * found in the [[rules()]]. Each scenario will be associated with the attributes that
     * are being validated by the validation rules that apply to the scenario.
     *
     * @return array a list of scenarios and the corresponding active attributes.
     */
    public function scenarios()
    {
        $scenarios = [self::SCENARIO_DEFAULT => []];
        $this->fillScenariosKeys($scenarios);

        $this->fillScenariosAttributes($scenarios);

        foreach ($scenarios as $scenario => $attributes) {
            if (!empty($attributes)) {
                $scenarios[$scenario] = array_keys($attributes);
            }
        }

        return $scenarios;
    }

    /**
     * Fill scenarios keys for ::scenarios()
     * @param array $scenarios
     * @throws InvalidConfigException
     * @internal
     */
    protected function fillScenariosKeys(array &$scenarios) {
        foreach ($this->getValidators() as $validator) {
            foreach ($validator->on as $scenario) {
                $scenarios[$scenario] = [];
            }
            foreach ($validator->except as $scenario) {
                $scenarios[$scenario] = [];
            }
        }
    }

    /**
     * Fill scenarios with attributes
     * @param array $scenarios
     * @throws InvalidConfigException
     */
    protected function fillScenariosAttributes(array &$scenarios) {
        $names = array_keys($scenarios);
        foreach ($this->getValidators() as $validator) {
            if (empty($validator->on) && empty($validator->except)) {
                foreach ($names as $name) {
                    foreach ($validator->attributes as $attribute) {
                        $scenarios[$name][$attribute] = true;
                    }
                }
            } elseif (empty($validator->on)) {
                foreach ($names as $name) {
                    if (!in_array($name, $validator->except, true)) {
                        foreach ($validator->attributes as $attribute) {
                            $scenarios[$name][$attribute] = true;
                        }
                    }
                }
            } else {
                foreach ($validator->on as $name) {
                    foreach ($validator->attributes as $attribute) {
                        $scenarios[$name][$attribute] = true;
                    }
                }
            }
        }
    }

    /**
     * Returns the form name that this model class should use.
     *
     * The form name is mainly used by [[\Reaction\Widgets\ActiveForm]] to determine how to name
     * the input fields for the attributes in a model. If the form name is "A" and an attribute
     * name is "b", then the corresponding input name would be "A[b]". If the form name is
     * an empty string, then the input name would be "b".
     *
     * The purpose of the above naming schema is that for forms which contain multiple different models,
     * the attributes of each model are grouped in sub-arrays of the POST-data and it is easier to
     * differentiate between them.
     *
     * By default, this method returns the model class name (without the namespace part)
     * as the form name. You may override it when the model is used in different forms.
     *
     * @return string the form name of this model class.
     * @see load()
     * @throws InvalidConfigException when form is defined with anonymous class and `formName()` method is
     * not overridden.
     */
    public function formName()
    {
        try {
            $reflector = new ReflectionClass($this);
            if (PHP_VERSION_ID >= 70000 && $reflector->isAnonymous()) {
                throw new InvalidConfigException('The "formName()" method should be explicitly defined for anonymous models');
            }
            return $reflector->getShortName();
        } catch (\ReflectionException $exception) {
            $className = explode('\\', static::class);
            return end($className);
        }
    }

    /**
     * Returns the list of attribute names.
     * By default, this method returns all public non-static properties of the class.
     * You may override this method to change the default behavior.
     * @return array list of attribute names.
     */
    public function attributes()
    {
        try {
            $class = new ReflectionClass($this);
            $names = [];
            foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
                if (!$property->isStatic()) {
                    $names[] = $property->getName();
                }
            }
        } catch (\ReflectionException $exception) {
            Reaction::error($exception);
            $names = [];
        }

        return $names;
    }

    /**
     * Returns the attribute labels.
     *
     * Attribute labels are mainly used for display purpose. For example, given an attribute
     * `firstName`, we can declare a label `First Name` which is more user-friendly and can
     * be displayed to end users.
     *
     * By default an attribute label is generated using [[generateAttributeLabel()]].
     * This method allows you to explicitly specify attribute labels.
     *
     * Note, in order to inherit labels defined in the parent class, a child class needs to
     * merge the parent labels with child labels using functions such as `array_merge()`.
     *
     * @return array attribute labels (name => label)
     * @see generateAttributeLabel()
     */
    public function attributeLabels()
    {
        return [];
    }

    /**
     * Returns the attribute hints.
     *
     * Attribute hints are mainly used for display purpose. For example, given an attribute
     * `isPublic`, we can declare a hint `Whether the post should be visible for not logged in users`,
     * which provides user-friendly description of the attribute meaning and can be displayed to end users.
     *
     * Unlike label hint will not be generated, if its explicit declaration is omitted.
     *
     * Note, in order to inherit hints defined in the parent class, a child class needs to
     * merge the parent hints with child hints using functions such as `array_merge()`.
     *
     * @return array attribute hints (name => hint)
     */
    public function attributeHints()
    {
        return [];
    }

    /**
     * Performs the data validation.
     *
     * This method executes the validation rules applicable to the current [[scenario]].
     * The following criteria are used to determine whether a rule is currently applicable:
     *
     * - the rule must be associated with the attributes relevant to the current scenario;
     * - the rules must be effective for the current scenario.
     *
     * This method will call [[beforeValidate()]] and [[afterValidate()]] before and
     * after the actual validation, respectively. If [[beforeValidate()]] returns false,
     * the validation will be cancelled and [[afterValidate()]] will not be called.
     *
     * Errors found during the validation can be retrieved via [[getErrors()]],
     * [[getFirstErrors()]] and [[getFirstError()]].
     *
     * @param string[]|string $attributeNames attribute name or list of attribute names that should be validated.
     * If this parameter is empty, it means any attribute listed in the applicable
     * validation rules should be validated.
     * @param bool $clearErrors whether to call [[clearErrors()]] before performing validation
     * @return ExtendedPromiseInterface with bool whether the validation is successful without any error.
     * @throws InvalidArgumentException if the current scenario is unknown.
     */
    public function validate($attributeNames = null, $clearErrors = true)
    {
        if ($clearErrors) {
            $this->clearErrors();
        }

        if (!$this->beforeValidate()) {
            return reject(new ValidationError("Before validate error"));
        }

        $scenarios = $this->scenarios();
        $scenario = $this->getScenario();
        if (!isset($scenarios[$scenario])) {
            throw new InvalidArgumentException("Unknown scenario: $scenario");
        }

        if ($attributeNames === null) {
            $attributeNames = $this->activeAttributes();
        }

        $attributeNames = (array)$attributeNames;

        $validationPromises = [];
        foreach ($this->getActiveValidators() as $validator) {
            $validationPromises[] = $validator->validateAttributes($this, $attributeNames);
        }
        return Reaction\Promise\allInOrder($validationPromises)
            ->always(function() {
                $this->afterValidate();
            })->then(function() {
                return !$this->hasErrors() ? true : reject(new ValidationError("Validation error"));
            });
    }

    /**
     * This method is invoked before validation starts.
     * The default implementation raises a `beforeValidate` event.
     * You may override this method to do preliminary checks before validation.
     * Make sure the parent implementation is invoked so that the event can be raised.
     * @return bool whether the validation should be executed. Defaults to true.
     * If false is returned, the validation will stop and the model is considered invalid.
     */
    public function beforeValidate()
    {
        return true;
    }

    /**
     * This method is invoked after validation ends.
     * The default implementation raises an `afterValidate` event.
     * You may override this method to do postprocessing after validation.
     * Make sure the parent implementation is invoked so that the event can be raised.
     */
    public function afterValidate()
    {
    }

    /**
     * Returns all the validators declared in [[rules()]].
     *
     * This method differs from [[getActiveValidators()]] in that the latter
     * only returns the validators applicable to the current [[scenario]].
     *
     * Because this method returns an ArrayObject object, you may
     * manipulate it by inserting or removing validators (useful in model behaviors).
     * For example,
     *
     * ```php
     * $model->validators[] = $newValidator;
     * ```
     *
     * @return ArrayObject|\Reaction\Validators\Validator[] all the validators declared in the model.
     * @throws InvalidConfigException
     */
    public function getValidators()
    {
        if ($this->_validators === null) {
            $this->_validators = $this->createValidators();
        }

        return $this->_validators;
    }

    /**
     * Returns the validators applicable to the current [[scenario]].
     * @param string $attribute the name of the attribute whose applicable validators should be returned.
     * If this is null, the validators for ALL attributes in the model will be returned.
     * @return \Reaction\Validators\Validator[] the validators applicable to the current [[scenario]].
     */
    public function getActiveValidators($attribute = null)
    {
        $validators = [];
        $scenario = $this->getScenario();
        try {
            $_validators = $this->getValidators();
        } catch (InvalidConfigException $exception) {
            Reaction::error($exception);
            $_validators = [];
        }
        foreach ($_validators as $validator) {
            if ($validator->isActive($scenario) && ($attribute === null || in_array($attribute, $validator->getAttributeNames(), true))) {
                $validators[] = $validator;
            }
        }

        return $validators;
    }

    /**
     * Creates validator objects based on the validation rules specified in [[rules()]].
     * Unlike [[getValidators()]], each time this method is called, a new list of validators will be returned.
     * @return ArrayObject validators
     * @throws InvalidConfigException if any validation rule configuration is invalid
     */
    public function createValidators()
    {
        $validators = new ArrayObject();
        foreach ($this->rules() as $rule) {
            if ($rule instanceof Validator) {
                $validators->append($rule);
            } elseif (is_array($rule) && isset($rule[0], $rule[1])) { // attributes, validator type
                try {
                    $validator = Validator::createValidator($rule[1], $this, (array)$rule[0], array_slice($rule, 2));
                } catch (\Exception $e) {
                    Reaction::error($e);
                }
                if (isset($validator)) {
                    $validators->append($validator);
                }
            } else {
                throw new InvalidConfigException('Invalid validation rule: a rule must specify both attribute names and validator type.');
            }
        }

        return $validators;
    }

    /**
     * Returns a value indicating whether the attribute is required.
     * This is determined by checking if the attribute is associated with a
     * [[\Reaction\Validators\RequiredValidator|required]] validation rule in the
     * current [[scenario]].
     *
     * Note that when the validator has a conditional validation applied using
     * [[\Reaction\Validators\RequiredValidator::$when|$when]] this method will return
     * `false` regardless of the `when` condition because it may be called be
     * before the model is loaded with data.
     *
     * @param string $attribute attribute name
     * @return bool whether the attribute is required
     */
    public function isAttributeRequired($attribute)
    {
        foreach ($this->getActiveValidators($attribute) as $validator) {
            if ($validator instanceof RequiredValidator && $validator->when === null) {
                return true;
            }
        }

        return false;
    }

    /**
     * Returns a value indicating whether the attribute is safe for massive assignments.
     * @param string $attribute attribute name
     * @return bool whether the attribute is safe for massive assignments
     * @see safeAttributes()
     */
    public function isAttributeSafe($attribute)
    {
        return in_array($attribute, $this->safeAttributes(), true);
    }

    /**
     * Returns a value indicating whether the attribute is active in the current scenario.
     * @param string $attribute attribute name
     * @return bool whether the attribute is active in the current scenario
     * @see activeAttributes()
     */
    public function isAttributeActive($attribute)
    {
        return in_array($attribute, $this->activeAttributes(), true);
    }

    /**
     * Returns the text label for the specified attribute.
     * @param string $attribute the attribute name
     * @return string the attribute label
     * @see generateAttributeLabel()
     * @see attributeLabels()
     */
    public function getAttributeLabel($attribute)
    {
        $labels = $this->attributeLabels();
        return isset($labels[$attribute]) ? $labels[$attribute] : $this->generateAttributeLabel($attribute);
    }

    /**
     * Returns the text hint for the specified attribute.
     * @param string $attribute the attribute name
     * @return string the attribute hint
     * @see attributeHints()
     */
    public function getAttributeHint($attribute)
    {
        $hints = $this->attributeHints();
        return isset($hints[$attribute]) ? $hints[$attribute] : '';
    }

    /**
     * Returns a value indicating whether there is any validation error.
     * @param string|null $attribute attribute name. Use null to check all attributes.
     * @return bool whether there is any error.
     */
    public function hasErrors($attribute = null)
    {
        return $attribute === null ? !empty($this->_errors) : isset($this->_errors[$attribute]);
    }

    /**
     * Returns the errors for all attributes or a single attribute.
     * @param string $attribute attribute name. Use null to retrieve errors for all attributes.
     * @property array An array of errors for all attributes. Empty array is returned if no error.
     * The result is a two-dimensional array. See [[getErrors()]] for detailed description.
     * @return array errors for all attributes or the specified attribute. Empty array is returned if no error.
     * Note that when returning errors for all attributes, the result is a two-dimensional array, like the following:
     *
     * ```php
     * [
     *     'username' => [
     *         'Username is required.',
     *         'Username must contain only word characters.',
     *     ],
     *     'email' => [
     *         'Email address is invalid.',
     *     ]
     * ]
     * ```
     *
     * @see getFirstErrors()
     * @see getFirstError()
     */
    public function getErrors($attribute = null)
    {
        if ($attribute === null) {
            return $this->_errors === null ? [] : $this->_errors;
        }

        return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : [];
    }

    /**
     * Returns the first error of every attribute in the model.
     * @return array the first errors. The array keys are the attribute names, and the array
     * values are the corresponding error messages. An empty array will be returned if there is no error.
     * @see getErrors()
     * @see getFirstError()
     */
    public function getFirstErrors()
    {
        if (empty($this->_errors)) {
            return [];
        }

        $errors = [];
        foreach ($this->_errors as $name => $es) {
            if (!empty($es)) {
                $errors[$name] = reset($es);
            }
        }

        return $errors;
    }

    /**
     * Returns the first error of the specified attribute.
     * @param string $attribute attribute name.
     * @return string the error message. Null is returned if no error.
     * @see getErrors()
     * @see getFirstErrors()
     */
    public function getFirstError($attribute)
    {
        return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
    }

    /**
     * Returns the errors for all attributes as a one-dimensional array.
     * @param bool $showAllErrors boolean, if set to true every error message for each attribute will be shown otherwise
     * only the first error message for each attribute will be shown.
     * @return array errors for all attributes as a one-dimensional array. Empty array is returned if no error.
     * @see getErrors()
     * @see getFirstErrors()
     */
    public function getErrorSummary($showAllErrors)
    {
        $lines = [];
        $errors = $showAllErrors ? $this->getErrors() : $this->getFirstErrors();
        foreach ($errors as $es) {
            $lines = array_merge((array)$es, $lines);
        }
        return $lines;
    }

    /**
     * Adds a new error to the specified attribute.
     * @param string $attribute attribute name
     * @param string $error new error message
     */
    public function addError($attribute, $error = '')
    {
        $this->_errors[$attribute][] = $error;
    }

    /**
     * Adds a list of errors.
     * @param array $items a list of errors. The array keys must be attribute names.
     * The array values should be error messages. If an attribute has multiple errors,
     * these errors must be given in terms of an array.
     * You may use the result of [[getErrors()]] as the value for this parameter.
     */
    public function addErrors(array $items)
    {
        foreach ($items as $attribute => $errors) {
            if (is_array($errors)) {
                foreach ($errors as $error) {
                    $this->addError($attribute, $error);
                }
            } else {
                $this->addError($attribute, $errors);
            }
        }
    }

    /**
     * Removes errors for all attributes or a single attribute.
     * @param string $attribute attribute name. Use null to remove errors for all attributes.
     */
    public function clearErrors($attribute = null)
    {
        if ($attribute === null) {
            $this->_errors = [];
        } else {
            unset($this->_errors[$attribute]);
        }
    }

    /**
     * Generates a user friendly attribute label based on the give attribute name.
     * This is done by replacing underscores, dashes and dots with blanks and
     * changing the first letter of each word to upper case.
     * For example, 'department_name' or 'DepartmentName' will generate 'Department Name'.
     * @param string $name the column name
     * @return string the attribute label
     */
    public function generateAttributeLabel($name)
    {
        return Inflector::camel2words($name, true);
    }

    /**
     * Returns attribute values.
     * @param array $names list of attributes whose value needs to be returned.
     * Defaults to null, meaning all attributes listed in [[attributes()]] will be returned.
     * If it is an array, only the attributes in the array will be returned.
     * @param array $except list of attributes whose value should NOT be returned.
     * @return array attribute values (name => value).
     */
    public function getAttributes($names = null, $except = [])
    {
        $values = [];
        if ($names === null) {
            $names = $this->attributes();
        }
        foreach ($names as $name) {
            $values[$name] = $this->$name;
        }
        foreach ($except as $name) {
            unset($values[$name]);
        }

        return $values;
    }

    /**
     * Sets the attribute values in a massive way.
     * @param array $values attribute values (name => value) to be assigned to the model.
     * @param bool $safeOnly whether the assignments should only be done to the safe attributes.
     * A safe attribute is one that is associated with a validation rule in the current [[scenario]].
     * @see safeAttributes()
     * @see attributes()
     */
    public function setAttributes($values, $safeOnly = true)
    {
        if (is_array($values)) {
            $attributes = array_flip($safeOnly ? $this->safeAttributes() : $this->attributes());
            foreach ($values as $name => $value) {
                if (isset($attributes[$name])) {
                    $this->$name = $value;
                } elseif ($safeOnly) {
                    $this->onUnsafeAttribute($name, $value);
                }
            }
        }
    }

    /**
     * This method is invoked when an unsafe attribute is being massively assigned.
     * The default implementation will log a warning message if Reaction::isDebug() is TRUE.
     * It does nothing otherwise.
     * @param string $name the unsafe attribute name
     * @param mixed $value the attribute value
     */
    public function onUnsafeAttribute($name, $value)
    {
        if (Reaction::isDebug()) {
            Reaction::debug("Failed to set unsafe attribute '$name' in '" . get_class($this) . "'.");
        }
    }

    /**
     * Returns the scenario that this model is used in.
     *
     * Scenario affects how validation is performed and which attributes can
     * be massively assigned.
     *
     * @return string the scenario that this model is in. Defaults to [[SCENARIO_DEFAULT]].
     */
    public function getScenario()
    {
        return $this->_scenario;
    }

    /**
     * Sets the scenario for the model.
     * Note that this method does not check if the scenario exists or not.
     * The method [[validate()]] will perform this check.
     * @param string $value the scenario that this model is in.
     */
    public function setScenario($value)
    {
        $this->_scenario = $value;
    }

    /**
     * Returns the attribute names that are safe to be massively assigned in the current scenario.
     * @return string[] safe attribute names
     */
    public function safeAttributes()
    {
        $scenario = $this->getScenario();
        $scenarios = $this->scenarios();
        if (!isset($scenarios[$scenario])) {
            return [];
        }
        $attributes = [];
        foreach ($scenarios[$scenario] as $attribute) {
            if ($attribute[0] !== '!' && !in_array('!' . $attribute, $scenarios[$scenario])) {
                $attributes[] = $attribute;
            }
        }

        return $attributes;
    }

    /**
     * Returns the attribute names that are subject to validation in the current scenario.
     * @return string[] safe attribute names
     */
    public function activeAttributes()
    {
        $scenario = $this->getScenario();
        $scenarios = $this->scenarios();
        if (!isset($scenarios[$scenario])) {
            return [];
        }
        $attributes = array_keys(array_flip($scenarios[$scenario]));
        foreach ($attributes as $i => $attribute) {
            if ($attribute[0] === '!') {
                $attributes[$i] = substr($attribute, 1);
            }
        }

        return $attributes;
    }

    /**
     * Populates the model with input data.
     *
     * This method provides a convenient shortcut for:
     *
     * ```php
     * if (isset($_POST['FormName'])) {
     *     $model->attributes = $_POST['FormName'];
     *     if ($model->save()) {
     *         // handle success
     *     }
     * }
     * ```
     *
     * which, with `load()` can be written as:
     *
     * ```php
     * if ($model->load($_POST) && $model->save()) {
     *     // handle success
     * }
     * ```
     *
     * `load()` gets the `'FormName'` from the model's [[formName()]] method (which you may override), unless the
     * `$formName` parameter is given. If the form name is empty, `load()` populates the model with the whole of `$data`,
     * instead of `$data['FormName']`.
     *
     * Note, that the data being populated is subject to the safety check by [[setAttributes()]].
     *
     * @param array $data the data array to load, typically `$_POST` or `$_GET`.
     * @param string $formName the form name to use to load the data into the model.
     * If not set, [[formName()]] is used.
     * @return bool whether `load()` found the expected form in `$data`.
     */
    public function load($data, $formName = null)
    {
        $scope = $formName === null ? $this->formName() : $formName;
        if ($scope === '' && !empty($data)) {
            $this->setAttributes($data);

            return true;
        } elseif (isset($data[$scope])) {
            $this->setAttributes($data[$scope]);

            return true;
        }

        return false;
    }

    /**
     * Populates a set of models with the data from end user.
     * This method is mainly used to collect tabular data input.
     * The data to be loaded for each model is `$data[formName][index]`, where `formName`
     * refers to the value of [[formName()]], and `index` the index of the model in the `$models` array.
     * If [[formName()]] is empty, `$data[index]` will be used to populate each model.
     * The data being populated to each model is subject to the safety check by [[setAttributes()]].
     * @param array $models the models to be populated. Note that all models should have the same class.
     * @param array $data the data array. This is usually `$_POST` or `$_GET`, but can also be any valid array
     * supplied by end user.
     * @param string $formName the form name to be used for loading the data into the models.
     * If not set, it will use the [[formName()]] value of the first model in `$models`.
     * This parameter is available since version 2.0.1.
     * @return bool whether at least one of the models is successfully populated.
     */
    public static function loadMultiple($models, $data, $formName = null)
    {
        if ($formName === null) {
            /* @var $first Model|false */
            $first = reset($models);
            if ($first === false) {
                return false;
            }
            $formName = $first->formName();
        }

        $success = false;
        foreach ($models as $i => $model) {
            /* @var $model Model */
            if ($formName == '') {
                if (!empty($data[$i]) && $model->load($data[$i], '')) {
                    $success = true;
                }
            } elseif (!empty($data[$formName][$i]) && $model->load($data[$formName][$i], '')) {
                $success = true;
            }
        }

        return $success;
    }

    /**
     * Validates multiple models.
     * This method will validate every model. The models being validated may
     * be of the same or different types.
     * @param array $models the models to be validated
     * @param array $attributeNames list of attribute names that should be validated.
     * If this parameter is empty, it means any attribute listed in the applicable
     * validation rules should be validated.
     * @return ExtendedPromiseInterface with bool whether all models are valid. RejectedPromise will be returned if one
     * or multiple models have validation error.
     */
    public static function validateMultiple($models, $attributeNames = null)
    {
        $promises = [];
        /* @var $model Model */
        foreach ($models as $model) {
            $promises[] = new Reaction\Promise\LazyPromise(function() use(&$model, $attributeNames) {
                return $model->validate($attributeNames);
            });
        }

        return Reaction\Promise\allInOrder($promises);
    }

    /**
     * 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 ($model, $field) {
     *     // 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;
     *     },
     * ];
     * ```
     *
     * In this method, you may also want to return different lists of fields based on some context
     * information. For example, depending on [[scenario]] or the privilege of the current application user,
     * you may return different sets of visible fields or filter out some fields.
     *
     * The default implementation of this method returns [[attributes()]] indexed by the same attribute names.
     *
     * @return array the list of field names or field definitions.
     * @see toArray()
     */
    public function fields()
    {
        $fields = $this->attributes();

        return array_combine($fields, $fields);
    }

    /**
     * Returns an iterator for traversing the attributes in the model.
     * This method is required by the interface [[\IteratorAggregate]].
     * @return ArrayIterator an iterator for traversing the items in the list.
     */
    public function getIterator()
    {
        $attributes = $this->getAttributes();
        return new ArrayIterator($attributes);
    }

    /**
     * Returns whether there is an element at the specified offset.
     * This method is required by the SPL interface [[\ArrayAccess]].
     * It is implicitly called when you use something like `isset($model[$offset])`.
     * @param mixed $offset the offset to check on.
     * @return bool whether or not an offset exists.
     */
    public function offsetExists($offset)
    {
        return isset($this->$offset);
    }

    /**
     * Returns the element at the specified offset.
     * This method is required by the SPL interface [[\ArrayAccess]].
     * It is implicitly called when you use something like `$value = $model[$offset];`.
     * @param mixed $offset the offset to retrieve element.
     * @return mixed the element at the offset, null if no element is found at the offset
     */
    public function offsetGet($offset)
    {
        return $this->$offset;
    }

    /**
     * Sets the element at the specified offset.
     * This method is required by the SPL interface [[\ArrayAccess]].
     * It is implicitly called when you use something like `$model[$offset] = $item;`.
     * @param int $offset the offset to set element
     * @param mixed $item the element value
     */
    public function offsetSet($offset, $item)
    {
        $this->$offset = $item;
    }

    /**
     * Sets the element value at the specified offset to null.
     * This method is required by the SPL interface [[\ArrayAccess]].
     * It is implicitly called when you use something like `unset($model[$offset])`.
     * @param mixed $offset the offset to unset element
     */
    public function offsetUnset($offset)
    {
        $this->$offset = null;
    }

    /**
     * @inheritdoc
     */
    protected function getInjectionRules()
    {
        return [
            RequestApplicationInterface::class => 'app',
        ];
    }

    /**
     * Translates a message to the specified language.
     * Or returns a TranslationPromise for further translation
     *
     * @param string $category Message category
     * @param string $message Message for translation
     * @param array  $params Parameters array
     * @param string $language Language translate to
     * @return string|Reaction\I18n\TranslationPromise
     */
    public function t($category, $message, $params = [], $language = null)
    {
        if (!isset($language) && isset($this->app)) {
            $language = $this->app->language;
        }
        return isset($language)
            ? Reaction::t($category, $message, $params, $language)
            : Reaction::tp($category, $message, $params, $language);
    }
}


<?php namespace Ordercloud\Services;

use Ordercloud\Entities\Connections\Connection;
use Ordercloud\Entities\Connections\ConnectionType;
use Ordercloud\Entities\Organisations\Organisation;
use Ordercloud\Entities\Organisations\OrganisationAccessToken;
use Ordercloud\Entities\Organisations\OrganisationAddress;
use Ordercloud\Entities\Organisations\OrganisationProfile;
use Ordercloud\Entities\Settings\SettingsCollection;
use Ordercloud\Requests\Auth\Entities\Authorisation;
use Ordercloud\Requests\Exceptions\NotFoundRequestException;
use Ordercloud\Requests\Exceptions\OrdercloudRequestException;
use Ordercloud\Requests\Organisations\CreatenOrganisationRequest;
use Ordercloud\Requests\Organisations\Criteria\AdvancedConnectionCriteria;
use Ordercloud\Requests\Organisations\Criteria\BasicConnectionCriteria;
use Ordercloud\Requests\Organisations\GetOrganisationAccessTokenRequest;
use Ordercloud\Requests\Organisations\GetOrganisationAddressRequest;
use Ordercloud\Requests\Organisations\GetOrganisationBalanceRequest;
use Ordercloud\Requests\Organisations\GetOrganisationConnectionsByTypeRequest;
use Ordercloud\Requests\Organisations\GetOrganisationConnectionsRequest;
use Ordercloud\Requests\Organisations\GetOrganisationRequest;
use Ordercloud\Requests\Organisations\GetSettingsByOrganisationRequest;
use Ordercloud\Requests\Settings\Criteria\SettingsCriteria;

class OrganisationService extends OrdercloudService
{
    /**
     * @param                  $organisationId
     * @param SettingsCriteria $criteria
     *
     * @return SettingsCollection
     */
    public function getSettings($organisationId, SettingsCriteria $criteria = null)
    {
        $criteria = $criteria ?: SettingsCriteria::create();

        return $this->request(
            new GetSettingsByOrganisationRequest($organisationId, $criteria)
        );
    }

    /**
     * @param $organisationId
     *
     * @return SettingsCollection
     */
    public function getAllSettings($organisationId)
    {
        $criteria = SettingsCriteria::create()
            ->setPageSize(-1);

        return $this->request(
            new GetSettingsByOrganisationRequest($organisationId, $criteria)
        );
    }

    /**
     * @param int           $organisationId
     * @param Authorisation $authorisation
     *
     * @return OrganisationAccessToken
     */
    public function getAccessToken($organisationId, Authorisation $authorisation = null)
    {
        return $this->request(
            new GetOrganisationAccessTokenRequest($organisationId, $authorisation)
        );
    }

    /**
     * @param $organisationId
     *
     * @return OrganisationAddress
     */
    public function getAddress($organisationId)
    {
        return $this->request(
            new GetOrganisationAddressRequest($organisationId)
        );
    }

    /**
     * @param int|null $organisationId If no organisation ID is supplied, returns the organisation
     *                                 specified by the X-Ordercloud-Organisation header.
     *
     * @return Organisation
     *
     * @throws NotFoundRequestException
     * @throws OrdercloudRequestException
     */
    public function getOrganisation($organisationId = null)
    {
        return $this->request(new GetOrganisationRequest($organisationId));
    }

    /**
     * @deprecated See ConnectionService for replacement
     *
     * @param int                          $typeCode
     * @param int|null                     $organisationId
     * @param BasicConnectionCriteria|null $criteria
     *
     * @return array|Connection[]
     */
    public function getConnectionsByType($typeCode, $organisationId = null, BasicConnectionCriteria $criteria = null)
    {
        $criteria = $criteria ?: BasicConnectionCriteria::create();

        return $this->request(
            new GetOrganisationConnectionsByTypeRequest($typeCode, $organisationId, $criteria)
        );
    }

    /**
     * @deprecated See ConnectionService for replacement
     *
     * @param int|null                     $organisationId
     * @param BasicConnectionCriteria|null $criteria
     *
     * @return array|Connection[]
     */
    public function getChildConnections($organisationId = null, BasicConnectionCriteria $criteria = null)
    {
        return $this->getConnectionsByType(ConnectionType::CHILD, $organisationId, $criteria);
    }

    /**
     * @deprecated See ConnectionService for replacement
     *
     * @param int|null                     $organisationId
     * @param BasicConnectionCriteria|null $criteria
     *
     * @return array|Connection[]
     */
    public function getMarketplaceConnections($organisationId = null, BasicConnectionCriteria $criteria = null)
    {
        return $this->getConnectionsByType(ConnectionType::MARKETPLACE, $organisationId, $criteria);
    }

    /**
     * @deprecated See ConnectionService for replacement
     *
     * @param int|null                        $organisationId
     * @param AdvancedConnectionCriteria|null $criteria
     *
     * @return array|Connection[]
     */
    public function getConnections($organisationId = null, AdvancedConnectionCriteria $criteria = null)
    {
        $criteria = $criteria ?: AdvancedConnectionCriteria::create();

        return $this->request(
            new GetOrganisationConnectionsRequest($organisationId, $criteria)
        );
    }

    /**
     * @param int            $organisationId
     * @param string|null    $from
     * @param string|null    $upTo
     * @param string[]|array $transactionTypes
     *
     * @return float
     */
    public function getBalance($organisationId, $from = null, $upTo = null, array $transactionTypes = null)
    {
        return $this->request(new GetOrganisationBalanceRequest($organisationId, $from, $upTo, $transactionTypes));
    }

    /**
     * @param $name
     * @param $code
     * @param OrganisationProfile $profile
     * @return mixed
     */
    public function createOrganisation($name, $code, OrganisationProfile $profile)
    {
        return $this->request(new CreatenOrganisationRequest($name, $code,  $profile));
    }
}


<?php

namespace Nip\Config\FileParser;

use Nip\Config\Exception\ParseException;

/**
 * Class Ini
 * @package Nip\Config\FileParser
 */
class Ini extends AbstractFileParser
{
    /**
     * {@inheritDoc}
     * Parses an INI file as an array
     *
     * @throws ParseException If there is an error parsing the INI file
     */
    public function parse()
    {
        if (defined('INI_SCANNER_TYPED')) {
            $data = parse_ini_file($this->getPath(), true, INI_SCANNER_TYPED);
        } else {
            $data = parse_ini_file($this->getPath(), true);
        }
        if ($data === false) {
            $error = error_get_last();
            throw new ParseException($error);
        }

        return $data;
    }

    /**
     * {@inheritDoc}
     */
    public function getSupportedExtensions()
    {
        return ['ini'];
    }
}


<?php namespace Ordercloud\Entities\Orders;

use JsonSerializable;

class MerchantItems implements JsonSerializable
{
    /**
     * @var OrderItemMerchant
     */
    private $merchant;
    /**
     * @var array|OrderItem[]
     */
    private $items;

    /**
     * @param OrderItemMerchant $merchant
     * @param array|OrderItem[] $items
     */
    public function __construct(OrderItemMerchant $merchant, array $items = [])
    {
        $this->merchant = $merchant;
        $this->items = $items;
    }

    /**
     * @param Order $order
     *
     * @return array|static[]
     */
    public static function createFromOrder(Order $order)
    {
        $groupedItems = [];

        foreach ($order->getItems() as $item) {
            $groupedItems = self::groupItem($item, $groupedItems);
        }

        $merchantItems = [];

        foreach ($groupedItems as $grouping) {
            $merchantItems[] = new static($grouping['org'], $grouping['items']);
        }

        return $merchantItems;
    }

    /**
     * @param OrderItem $item
     * @param array     $groupedItems
     *
     * @return array
     */
    protected static function groupItem(OrderItem $item, array $groupedItems)
    {
        $merchantId = $item->getDetail()->getOrganisation()->getId();

        if ( ! array_key_exists($merchantId, $groupedItems)) {
            $groupedItems[$merchantId] = [
                'org' => $item->getDetail()->getOrganisation(),
                'items' => []
            ];
        }

        $groupedItems[$merchantId]['items'][] = $item;

        return $groupedItems;
    }

    /**
     * @return OrderItemMerchant
     */
    public function getMerchant()
    {
        return $this->merchant;
    }

    /**
     * @return array|OrderItem[]
     */
    public function getItems()
    {
        return $this->items;
    }

    /**
     * @return float
     */
    public function getTotalAmount()
    {
        $total = 0.0;

        foreach ($this->getItems() as $item) {
            $total = bcadd($total, $item->getLinePrice(), 2);
        }

        return $total;
    }

    /**
     * Specify data which should be serialized to JSON
     */
    public function jsonSerialize()
    {
        return [
            'merchant' => $this->getMerchant(),
            'totalAmount' => $this->getTotalAmount(),
            'items' => $this->getItems(),
        ];
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: digit
 * Date: 22.05.18
 * Time: 15:21
 */

namespace Reaction\Db\Pgsql;

use Reaction\Helpers\ArrayHelper;
use Reaction\Promise\ExtendedPromiseInterface;
use Reaction\Promise\LazyPromise;
use Reaction\Promise\LazyPromiseInterface;
use Reaction\Promise\Promise;

class Connection extends \Reaction\Db\Connection
{
    /** @var \PgAsync\Connection */
    public $pgConnection;
    /**
     * Execute SQL statement string
     * @param string $sql Statement SQL string
     * @param array  $params Statement parameters
     * @param bool   $lazy Use lazy promise
     * @return ExtendedPromiseInterface|LazyPromiseInterface
     */
    public function executeSql($sql, $params = [], $lazy = true)
    {
        list($sql, $params) = $this->convertSqlToIndexed($sql, $params);
        $promiseResolver = function($r, $c) use ($sql, $params) {
            $this->pgConnection->executeStatement($sql, $params)->subscribe(
                function($row) use (&$result) {
                    $result[] = $row;
                },
                function($error = null) use (&$c) {
                    $c($error);
                },
                function() use (&$r, &$result) {
                    $r($result);
                }
            );
        };
        if (!$lazy) {
            return new Promise($promiseResolver);
        }
        $promiseCreator = function() use (&$promiseResolver) {
            return new Promise($promiseResolver);
        };
        return new LazyPromise($promiseCreator);
    }

    /**
     * Close connection
     */
    public function close()
    {
        $this->pgConnection->disconnect();
        parent::close();
    }

    /**
     * Convert keyed SQL and params to indexed by `$`
     * @param string $sql
     * @param array  $params
     * @return array
     */
    protected function convertSqlToIndexed($sql, $params = [])
    {
        if (empty($params) || ArrayHelper::isIndexed($params)) {
            return [$sql, $params];
        }
        $newParams = array_values($params);
        $replace = [];
        $num = 1;
        foreach ($params as $key => $value) {
            $replace[$key] = '$' . $num;
            $num++;
        }
        $newSql = strtr($sql, $replace);
        return [$newSql, $newParams];
    }
}


<?php

namespace Pompdelux\PHPRedisBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;

/**
 * This is the class that loads and manages bundle configuration
 */
class PHPRedisExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.xml');

        $config = $this->getConfiguration($configs, $container);
        $config = $this->processConfiguration($config, $configs);

        foreach ($config['class'] as $name => $settings) {
            $def = new Definition($container->getParameter('pdl.phpredis.class'));
            $def->setPublic(true);
            $def->setScope(ContainerInterface::SCOPE_CONTAINER);
            $def->addArgument($name);
            $def->addArgument($container->getParameter('kernel.environment'));
            $def->addArgument($settings);
            $def->addMethodCall('setLogger', [new Reference('pdl.phpredis.logger')]);
            $container->setDefinition(sprintf('pdl.phpredis.%s', $name), $def);
        }
    }
}


<?php namespace m8rge;

/**
 * Class AlternativeMail
 *
 * Simple class for utf8 html/text emails with small attachments (they are loaded in memory)
 */
class AlternativeMail
{
    /**
     * @var array
     */
    protected $to = array();

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

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

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

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

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

    function __construct()
    {
        mb_internal_encoding('UTF-8');
    }

    /**
     * @param string $email
     * @param string $name
     * @return $this
     */
    public function setFrom($email, $name = '')
    {
        $this->from = array(
            'email' => $email,
            'name' => $name
        );

        return $this;
    }

    /**
     * @param string $email
     * @param string $name
     * @return $this
     */
    public function addTo($email, $name = '')
    {
        $this->to[] = array(
            'email' => $email,
            'name' => $name
        );

        return $this;
    }

    /**
     * Autodetect mime type relies on php fileinfo extension
     * @param string $file
     * @param string $forceFileName
     * @param string $forceMimeType
     * @return $this
     */
    public function addAttachment($file, $forceFileName = '', $forceMimeType = '')
    {
        $this->attachments[] = array(
            'file' => $file,
            'fileName' => $forceFileName,
            'mimeType' => $forceMimeType,
        );

        return $this;
    }

    /**
     * @param string $html
     * @return $this
     */
    public function setHtmlBody($html)
    {
        $this->htmlBody = $html;

        return $this;
    }

    /**
     * @param string $text
     * @return $this
     */
    public function setTextBody($text)
    {
        $this->textBody = $text;

        return $this;
    }

    /**
     * @param string $text
     * @return $this
     */
    public function setSubject($text)
    {
        $this->subject = $text;

        return $this;
    }

    /**
     * @param string $boundary
     * @param string[] $headers
     * @param string $body
     * @return string
     */
    protected function compilePart($boundary, $headers, $body)
    {
        array_unshift($headers, '--' . $boundary);
        $headers = implode("\r\n", $headers);
        $body = $headers . "\r\n\r\n" . $body . "\r\n\r\n";

        return $body;
    }

    /**
     * @param string $part 'html' or 'text'
     * @return array
     */
    protected function getTextPartData($part)
    {
        $contentTypes = array(
            'text' => 'text/plain',
            'html' => 'text/html',
        );
        $headers[] = "Content-Type: {$contentTypes[$part]}; charset=UTF-8";
        $headers[] = 'Content-Transfer-Encoding: base64';
        $bodyVarName = $part . 'Body';
        /** @noinspection PhpUndefinedFieldInspection */
        $body = substr(chunk_split(base64_encode($this->$bodyVarName)), 0 ,-2);

        return array($headers, $body);
    }

    /**
     * @return array
     */
    protected function getMergedTextPartData()
    {
        $body = '';
        $boundary = md5(microtime());
        $headers = array();
        if (!empty($this->textBody) && !empty($this->htmlBody)) {
            $headers[] = 'Content-Type: multipart/alternative; boundary=' . $boundary;

            list($textHeaders, $textBody) = $this->getTextPartData('text');
            list($htmlHeaders, $htmlBody) = $this->getTextPartData('html');
            $body .= $this->compilePart($boundary, $textHeaders, $textBody);
            $body .= $this->compilePart($boundary, $htmlHeaders, $htmlBody);
            $body .= '--' . $boundary . '--';
        } elseif (!empty($this->textBody)) {
            list($headers, $body) = $this->getTextPartData('text');
        } elseif (!empty($this->htmlBody)) {
            list($headers, $body) = $this->getTextPartData('html');
        }

        return array($headers, $body);
    }

    /**
     * @return array
     */
    protected function getAttachmentPartsData()
    {
        $attachments = array();
        if (!empty($this->attachments)) {
            foreach ($this->attachments as $attachment) {
                $mimeType = $attachment['mimeType'];
                if (empty($mimeType)) {
                    $info = finfo_open(FILEINFO_MIME_TYPE);
                    $mimeType = finfo_file($info, $attachment['file']);
                }
                $fileName = $attachment['fileName'];
                if (empty($fileName)) {
                    $fileName = pathinfo($attachment['file'], PATHINFO_BASENAME);
                }
                $fileName = mb_encode_mimeheader($fileName);
                $headers[] = "Content-Type: $mimeType; name=\"$fileName\"";
                $headers[] = "Content-Disposition: attachment; filename=\"$fileName\"";
                $headers[] = 'Content-Transfer-Encoding: base64';
                $body = substr(chunk_split(base64_encode(file_get_contents($attachment['file']))), 0, -2);
                $attachments[] = array($headers, $body);
            }
        }

        return $attachments;
    }

    /**
     * @return array
     */
    protected function getMailData()
    {
        list($textHeaders, $textBody) = $this->getMergedTextPartData();

        $body = '';
        $boundary = md5(microtime());
        if (!empty($this->attachments)) {
            $headers[] = 'Content-Type: multipart/mixed; boundary=' . $boundary;

            $body .= $this->compilePart($boundary, $textHeaders, $textBody);
            foreach ($this->getAttachmentPartsData() as $attachmentPartData) {
                list($attachmentHeaders, $attachmentBody) = $attachmentPartData;
                $body .= $this->compilePart($boundary, $attachmentHeaders, $attachmentBody);
            }
            $body .= '--' . $boundary . '--';
        } else {
            $headers = $textHeaders;
            $body = $textBody;
        }

        return array($headers, $body);
    }

    /**
     * @return bool
     */
    public function send()
    {
        list($additionalHeaders, $body) = $this->getMailData();

        $to = array_map(
            function ($value) {
                if (!empty($value['name'])) {
                    return mb_encode_mimeheader($value['name']) . " <{$value['email']}>";
                } else {
                    return $value['email'];
                }
            },
            $this->to
        );
        $to = implode(', ', $to);
        if (strlen($to) > 78) {
            $to = wordwrap($to, 78, "\r\n\t");
        }
        if (!empty($this->from['email'])) {
            if (!empty($this->from['name'])) {
                $from = mb_encode_mimeheader($this->from['name']) . " <{$this->from['email']}>";
            } else {
                $from = $this->from['email'];
            }
            $additionalHeaders[] = 'From: ' . $from;
        }

        $subject = mb_encode_mimeheader($this->subject, 'UTF-8');
        $additionalHeaders = implode("\r\n", $additionalHeaders);
        return mail($to, $subject, $body, $additionalHeaders);
    }
}


<?php namespace RestGalleries\Http\Guzzle;

use Guzzle\Http\Client;
use RestGalleries\Http\Request;
use RestGalleries\Http\Plugins\RequestPluginAdapter;

/**
 * Specific http client based on Guzzle Client.
 */
class GuzzleRequest extends Request
{
    /**
     * Instance var for the Http client.
     *
     * @var \Guzzle\Http\Client
     */
    protected $request;

    /**
     * Initializes the Http client in an instance var.
     *
     * @return void
     */
    public function __construct()
    {
        $this->request = new Client;
    }

    /**
     * Receives Http client response object with the response data and creates an ResponseAdapter object.
     *
     * @param  \Guzzle\Http\Client $data
     * @return \RestGalleries\Http\Guzzle\GuzzleResponse
     */
    protected function newResponse($data)
    {
        return new GuzzleResponse($data);
    }

    /**
     * Adds normalized plugins to the Http client.
     *
     * @param \RestGalleries\Http\Plugins\RequestPluginAdapter $plugin
     */
    public function addPlugin(RequestPluginAdapter $plugin)
    {
        $subscriber = $plugin->add();
        $this->request->addSubscriber($subscriber);

        return $this;
    }

    /**
     * Gets the request options, creates the request, sends it and returns new response object.
     *
     * @param  string $method
     * @param  string $endPoint
     * @return \RestGalleries\Http\Guzzle\GuzzleResponse
     */
    public function sendRequest($method = 'GET', $endPoint = '')
    {
        $options = array_filter([
            'query'   => $this->getQuery(),
            'headers' => $this->getHeaders(),
            'body'    => $this->getBody()
        ]);
        $url = $this->url . $endPoint;

        $request     = $this->request->createRequest($method, $url, $options);
        $rawResponse = $this->request->send($request);

        return $this->newResponse($rawResponse);

    }

}


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

namespace CarteBlanche\App;

use \CarteBlanche\CarteBlanche;
use \CarteBlanche\App\Locator;
use \CarteBlanche\Exception\ErrorException;

/**
 * This is the global file loader
 *
 * @author  Piero Wbmstr <me@e-piwi.fr>
 */
class Loader
{

    /**
     * System file loader : will load a class file and its helper if so
     *
     * @param   string  $filename   The file path to load
     * @return  bool    TRUE if the class file has been found
     */
    public static function load($filename)
    {
        if (empty($filename)) return false;
        $hlp_file = (string) str_replace('.php', '.helper.php', $filename);
        if ($_f = Locator::locate($filename)) {
            if ($hlp_file!=$filename && $_hf = Locator::locate($hlp_file)) require_once $_hf;
            require_once $_f;
            return true;
        }
        return false;
    }

    /**
     * Class autoloader to scan bundles directory
     *
     * @param   string          $classname  The name of the class to load
     * @param   null/string     $type       The namespace type (Controller for example)
     * @param   bool            $silent     Exit silently if not found (default is false)
     * @return  bool/string     TRUE if the classfile had been found
     * @throws  \CarteBlanche\Exception\ErrorException if the class can't be found & $silent is false
     */
    public static function loadClass($classname, $type = null, $silent = false)
    {
        // search in bundles
        $bundles = CarteBlanche::getContainer()->get('bundles');
        $full_classname = $type.$classname;
        $classfile = ucfirst($classname).'.php';
        if (!empty($bundles)) {
            foreach($bundles as $_n=>$_bundle) {
                $_namespace = $_bundle->getNamespace();
                if (!empty($type)) {
                    $bundle_file = rtrim($_bundle->getDirectory(), '/').'/'
                        .rtrim($type, '/').'/'
                        .$classfile;
                    $full_namespace = '\\'.$_namespace.'\\'.$type.'\\'.ucfirst($classname);
                    if ($_ce = self::classExists($full_namespace)) {
                        return $full_namespace;
                    } elseif ($_f = Locator::locate($bundle_file)) {
                        if (true===self::load($_f)) {
                            return $full_namespace;
                        }
                    }
                } else {
                    if ($_namespace == substr(trim($classname, '\\'), 0, strlen($_namespace))) {
                        $bundle_file = str_replace('\\', DIRECTORY_SEPARATOR,
                            rtrim($_bundle->getDirectory(), '/')
                            .substr(trim($classname, '\\'), strlen($_namespace))
                            .'.php'
                        );
                        $full_namespace = $classname;
                        if ($_ce = self::classExists($full_namespace)) {
                            return $full_namespace;
                        } elseif ($_f = Locator::locate($bundle_file)) {
                            if (true===self::load($_f)) {
                                return $classname;
                            }
                        }
                    }
                }
            }
        }

        // silently return if the class has not been found
        if (0!==error_reporting() && true!==$silent) {
            throw new ErrorException("Class '$classname' not found!");
        }
        return false;
    }

    /**
     * Application specific "class_exists()" function with silent SPL autoload
     *
     * This will not throw exception or error if the class doesn't exist but return false
     *
     * @param   string  $classname  The class name to test
     * @param   bool    $autoload
     * @param   bool    $fail_error
     * @return  bool    TRUE if the class exists
     * @throws  \Exception if the class was not found and `$fail_error = true`
     */
    public static function classExists($classname, $autoload = true, $fail_error = false)
    {
        if (true===@class_exists($classname, false)) return true;
        if ($autoload) {
            try {
                if (true===class_exists($classname)) return true;
            } catch (\Exception $e) {
                if (true===$fail_error) throw $e;
            }
        }
        return false;
    }

    /**
     * System autoloader : will load a class file
     *
     * @param   string  $classname  The name of the class to load
     * @return  bool    TRUE if the class file has been found
     * @throws  \CarteBlanche\Exception\ErrorException if the class was not found
     */
    public static function autoload($classname)
    {
        $classname = str_replace('\\\\', '\\', $classname);

        // already exists in application
        if (true===self::classExists($classname, true)) return $classname;

        // exists in internal application
        $cls = Kernel::CARTE_BLANCHE_NAMESPACE.$classname;
        if (true===@class_exists($cls, false)) return $cls;

        // from dependencies
        $tool_path = Locator::getToolPath($classname, true);
        if ($tool_path) {
            $cls_file = $tool_path;
        } else {
            $cls_file = (string) str_replace('\\', DIRECTORY_SEPARATOR, $classname.'.php');
        }
        if ($_f = Locator::locate($cls_file)) {
            return self::load($_f);
        } elseif (0!==error_reporting() && count(spl_autoload_functions())==1) {
            throw new ErrorException("Class '$classname' not found!");
        }
        return false;
    }

}

// Endfile