<?php

namespace Reaction\Web;

use React\Promise\PromiseInterface;
use Reaction;
use Reaction\Base\ComponentAutoloadInterface;
use Reaction\Base\ComponentInitBlockingInterface;
use Reaction\Exceptions\Error;
use Reaction\Exceptions\Http\ForbiddenException;
use Reaction\Exceptions\InvalidConfigException;
use Reaction\Exceptions\InvalidValueException;
use Reaction\Promise\ExtendedPromiseInterface;
use Reaction\Rbac\CheckAccessInterface;
use function Reaction\Promise\reject;
use function Reaction\Promise\resolve;

/**
 * User is the class for the `user` application component that manages the user authentication status.
 *
 * You may use [[isGuest]] to determine whether the current user is a guest or not.
 * If the user is a guest, the [[identity]] property would return `null`. Otherwise, it would
 * be an instance of [[IdentityInterface]].
 *
 * You may call various methods to change the user authentication status:
 *
 * - [[login()]]: sets the specified identity and remembers the authentication status in session and cookie;
 * - [[logout()]]: marks the user as a guest and clears the relevant information from session and cookie;
 * - [[setIdentity()]]: changes the user identity without touching session or cookie
 *   (this is best used in stateless RESTful API implementation).
 *
 * Note that User only maintains the user authentication status. It does NOT handle how to authenticate
 * a user. The logic of how to authenticate a user should be done in the class implementing [[IdentityInterface]].
 * You are also required to set [[identityClass]] with the name of this class.
 *
 * User is configured as an application component in [[\yii\web\Application]] by default.
 * You can access that instance via `Yii::$app->user`.
 *
 * You can modify its configuration by adding an array to your application config under `components`
 * as it is shown in the following example:
 *
 * ```php
 * 'user' => [
 *     'identityClass' => 'App\Models\User', // User must implement the IdentityInterface
 *     'enableAutoLogin' => true,
 *     // 'loginUrl' => ['user/login'],
 *     // ...
 * ]
 * ```
 *
 * @property string|int $id The unique identifier for the user. If `null`, it means the user is a guest. This
 * property is read-only.
 * @property IdentityInterface|null $identity The identity object associated with the currently logged-in
 * user. `null` is returned if the user is not logged in (not authenticated).
 * @property bool $isGuest Whether the current user is a guest. This property is read-only.
 * @property string $returnUrl The URL that the user should be redirected to after login. Note that the type
 * of this property differs in getter and setter. See [[getReturnUrl()]] and [[setReturnUrl()]] for details.
 * @property RequestHelper $request
 */
class User extends Reaction\Base\RequestAppServiceLocator implements UserInterface, ComponentAutoloadInterface, ComponentInitBlockingInterface
{
    const EVENT_BEFORE_LOGIN = 'beforeLogin';
    const EVENT_AFTER_LOGIN = 'afterLogin';
    const EVENT_BEFORE_LOGOUT = 'beforeLogout';
    const EVENT_AFTER_LOGOUT = 'afterLogout';

    const PERMISSION_LOGGED_IN = '@';
    const PERMISSION_NOT_LOGGED_IN = '?';

    /**
     * @var string the class name of the [[identity]] object.
     */
    public $identityClass;
    /**
     * @var bool whether to enable cookie-based login. Defaults to `false`.
     * Note that this property will be ignored if [[enableSession]] is `false`.
     */
    public $enableAutoLogin = false;
    /**
     * @var bool whether to use session to persist authentication status across multiple requests.
     * You set this property to be `false` if your application is stateless, which is often the case
     * for RESTful APIs.
     */
    public $enableSession = true;
    /**
     * @var string|array the URL for login when [[loginRequired()]] is called.
     * If an array is given, [[UrlManager::createUrl()]] will be called to create the corresponding URL.
     * The first element of the array should be the route to the login action, and the rest of
     * the name-value pairs are GET parameters used to construct the login URL. For example,
     *
     * ```php
     * ['site/login', 'ref' => 1]
     * ```
     *
     * If this property is `null`, a 403 HTTP exception will be raised when [[loginRequired()]] is called.
     */
    public $loginUrl = ['site/login'];
    /**
     * @var array the configuration of the identity cookie. This property is used only when [[enableAutoLogin]] is `true`.
     * @see Cookie
     */
    public $identityCookie = ['name' => '_identity', 'httpOnly' => true];
    /**
     * @var int the number of seconds in which the user will be logged out automatically if he
     * remains inactive. If this property is not set, the user will be logged out after
     * the current session expires (c.f. [[Session::timeout]]).
     * Note that this will not work if [[enableAutoLogin]] is `true`.
     */
    public $authTimeout;
    /**
     * @var CheckAccessInterface The access checker to use for checking access.
     * If not set the application auth manager will be used.
     */
    public $accessChecker;
    /**
     * @var int the number of seconds in which the user will be logged out automatically
     * regardless of activity.
     * Note that this will not work if [[enableAutoLogin]] is `true`.
     */
    public $absoluteAuthTimeout;
    /**
     * @var bool whether to automatically renew the identity cookie each time a page is requested.
     * This property is effective only when [[enableAutoLogin]] is `true`.
     * When this is `false`, the identity cookie will expire after the specified duration since the user
     * is initially logged in. When this is `true`, the identity cookie will expire after the specified duration
     * since the user visits the site the last time.
     * @see enableAutoLogin
     */
    public $autoRenewCookie = true;
    /**
     * @var string the session variable name used to store the value of [[id]].
     */
    public $idParam = '__id';
    /**
     * @var string the session variable name used to store the value of expiration timestamp of the authenticated state.
     * This is used when [[authTimeout]] is set.
     */
    public $authTimeoutParam = '__expire';
    /**
     * @var string the session variable name used to store the value of absolute expiration timestamp of the authenticated state.
     * This is used when [[absoluteAuthTimeout]] is set.
     */
    public $absoluteAuthTimeoutParam = '__absoluteExpire';
    /**
     * @var string the session variable name used to store the value of [[returnUrl]].
     */
    public $returnUrlParam = '__returnUrl';
    /**
     * @var array MIME types for which this component should redirect to the [[loginUrl]].
     */
    public $acceptableRedirectTypes = ['text/html', 'application/xhtml+xml'];
    /**
     * @var array
     */
    protected $_access = [];
    /**
     * @var bool Initialization flag
     */
    protected $_initialized = false;

    /**
     * Initializes the application component.
     * @throws InvalidConfigException
     */
    public function init()
    {
        parent::init();

        if ($this->identityClass === null) {
            throw new InvalidConfigException('User::identityClass must be set.');
        }
        if ($this->enableAutoLogin && !isset($this->identityCookie['name'])) {
            throw new InvalidConfigException('User::identityCookie must contain the "name" element.');
        }
        if (!empty($this->accessChecker) && is_string($this->accessChecker)) {
            $this->accessChecker = Reaction::create($this->accessChecker);
        }
    }

    /**
     * Init callback. Called by parent container/service/component on init and must return a fulfilled Promise
     * @return PromiseInterface
     */
    public function initComponent()
    {
        return $this->getIdentityAsync()
            ->always(function() {
                $this->_initialized = true;
            })
            ->then(function() {
                return true;
            }, function() {
                return false;
            });
    }

    protected $_identity = false;

    /**
     * Returns the identity object associated with the currently logged-in user.
     * This is only useful when [[enableSession]] is true.
     * @return IdentityInterface|null|false the identity object associated with the currently logged-in user.
     * `null` is returned if the user is not logged in (not authenticated).
     * @see login()
     * @see logout()
     * @see getIdentityAsync()
     */
    public function getIdentity()
    {
        if ($this->_identity === false || $this->_identity === null) {
            return null;
        }

        return $this->_identity;
    }

    /**
     * Returns the identity object associated with the currently logged-in user.
     * When [[enableSession]] is true, this method may attempt to read the user's authentication data
     * stored in session and reconstruct the corresponding identity object, if it has not done so before.
     * @param bool $autoRenew whether to automatically renew authentication status if it has not been done so before.
     * This is only useful when [[enableSession]] is true.
     * @return ExtendedPromiseInterface with IdentityInterface|null|false the identity object associated with the currently logged-in user.
     * `null` is returned if the user is not logged in (not authenticated).
     * @see login()
     * @see logout()
     * @see getIdentity()
     */
    public function getIdentityAsync($autoRenew = true)
    {
        if ($this->_identity === false) {
            if ($this->enableSession && $autoRenew) {
                $this->_identity = null;
                return $this->renewAuthStatus()
                    ->then(null, function($e) {
                        $this->_identity = false;
                        return reject($e);
                    })->then(function() {
                        return $this->_identity;
                    });
            } else {
                return reject(null);
            }
        } else {
            return resolve($this->_identity);
        }
    }

    /**
     * Sets the user identity object.
     *
     * Note that this method does not deal with session or cookie. You should usually use [[switchIdentity()]]
     * to change the identity of the current user.
     *
     * @param IdentityInterface|null $identity the identity object associated with the currently logged user.
     * If null, it means the current user will be a guest without any associated identity.
     * @throws InvalidValueException if `$identity` object does not implement [[IdentityInterface]].
     */
    public function setIdentity($identity)
    {
        if ($identity instanceof IdentityInterface) {
            $this->_identity = $identity;
            $this->_access = [];
        } elseif ($identity === null) {
            $this->_identity = null;
        } else {
            throw new InvalidValueException('The identity object must implement IdentityInterface.');
        }
    }

    /**
     * Logs in a user.
     *
     * After logging in a user:
     * - the user's identity information is obtainable from the [[identity]] property
     *
     * If [[enableSession]] is `true`:
     * - the identity information will be stored in session and be available in the next requests
     * - in case of `$duration == 0`: as long as the session remains active or till the user closes the browser
     * - in case of `$duration > 0`: as long as the session remains active or as long as the cookie
     *   remains valid by it's `$duration` in seconds when [[enableAutoLogin]] is set `true`.
     *
     * If [[enableSession]] is `false`:
     * - the `$duration` parameter will be ignored
     *
     * @param IdentityInterface $identity the user identity (which should already be authenticated)
     * @param int $duration number of seconds that the user can remain in logged-in status, defaults to `0`
     * @return ExtendedPromiseInterface with bool whether the user is logged in
     */
    public function login(IdentityInterface $identity, $duration = 0)
    {
        //Using root resolve function for promise conversion
        return resolve(true)
            ->then(function() use (&$identity, $duration) {
                return $this->beforeLogin($identity, false, $duration);
            })->then(function() use (&$identity, $duration) {
                $this->switchIdentity($identity, $duration);
                $id = $identity->getId();
                $ip = $this->request->getUserIP();
                if ($this->enableSession) {
                    $log = "User '$id' logged in from $ip with duration $duration.";
                } else {
                    $log = "User '$id' logged in from $ip. Session not enabled.";
                }

                $this->regenerateCsrfToken();

                if (Reaction::isDebug()) {
                    Reaction::info($log);
                }
                return $this->afterLogin($identity, false, $duration);
            });
    }

    /**
     * Regenerates CSRF token
     */
    protected function regenerateCsrfToken()
    {
        $request = $this->request;
        if ($request->enableCsrfCookie || $this->enableSession) {
            $request->getCsrfToken(true);
        }
    }

    /**
     * Logs in a user by the given access token.
     * This method will first authenticate the user by calling [[IdentityInterface::findIdentityByAccessToken()]]
     * with the provided access token. If successful, it will call [[login()]] to log in the authenticated user.
     * If authentication fails or [[login()]] is unsuccessful, it will return null.
     * @param string $token the access token
     * @param mixed $type the type of the token. The value of this parameter depends on the implementation.
     * For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`.
     * @return ExtendedPromiseInterface with IdentityInterface|null the identity associated with the given access token. Null is returned if
     * the access token is invalid or [[login()]] is unsuccessful.
     */
    public function loginByAccessToken($token, $type = null)
    {
        /* @var $class IdentityInterface */
        $class = $this->identityClass;
        return $class::findIdentityByAccessToken($token, $type)
            ->then(function($identity) {
                return $this->login($identity)
                    ->then(function() use (&$identity) {
                        return $identity;
                    });
            });
    }

    /**
     * Logs in a user by cookie.
     *
     * This method attempts to log in a user using the ID and authKey information
     * provided by the [[identityCookie|identity cookie]].
     * @return ExtendedPromiseInterface
     */
    protected function loginByCookie()
    {
        return $this->getIdentityAndDurationFromCookie()
            ->then(function($data) {
                if (isset($data['identity'], $data['duration'])) {
                    /** @var IdentityInterface $identity */
                    $identity = $data['identity'];
                    $duration = $data['duration'];
                    return $this->beforeLogin($identity, true, $duration)
                        ->then(function() use (&$identity, $duration) {
                            $this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0);
                            $id = $identity->getId();
                            $ip = $this->request->getUserIP();
                            Reaction::info("User '$id' logged in from $ip via cookie.");
                            return $this->afterLogin($identity, true, $duration);
                        });
                } else {
                    return reject(new Error("Invalid cookie value or user identity"));
                }
            });
    }

    /**
     * Logs out the current user.
     * This will remove authentication-related session data.
     * If `$destroySession` is true, all session data will be removed.
     * @param bool $destroySession whether to destroy the whole session. Defaults to true.
     * This parameter is ignored if [[enableSession]] is false.
     * @return ExtendedPromiseInterface with bool whether the user is logged out
     * @throws \Throwable
     */
    public function logout($destroySession = true)
    {
        $identity = $this->getIdentity();
        if ($identity === null) {
            return $this->getIsGuest() ? resolve(true) : reject(false);
        }

        //Using root resolve function for promise conversion
        return resolve(true)
            ->then(function() use (&$identity) { return $this->beforeLogout($identity); })
            ->then(function() use (&$identity, $destroySession) {
                $this->switchIdentity(null);
                $id = $identity->getId();
                $ip = $this->request->getUserIP();
                Reaction::info("User '$id' logged out from $ip.");
                if ($destroySession && $this->enableSession) {
                    return $this->app->session->destroy();
                } else {
                    return true;
                }
            })->always(function() use (&$identity) {
                return $this->afterLogout($identity);
            })->then(function() use (&$identity) {
                return $this->getIsGuest() ? true : reject("User logout failed");
            });
    }

    /**
     * Returns a value indicating whether the user is a guest (not authenticated).
     * @return bool whether the current user is a guest.
     * @see getIdentity()
     */
    public function getIsGuest()
    {
        return $this->getIdentity() === null;
    }

    /**
     * Returns a value that uniquely represents the user.
     * @return string|int the unique identifier for the user. If `null`, it means the user is a guest.
     * @see getIdentity()
     */
    public function getId()
    {
        $identity = $this->getIdentity();

        return $identity !== null ? $identity->getId() : null;
    }

    /**
     * Returns the URL that the browser should be redirected to after successful login.
     *
     * This method reads the return URL from the session. It is usually used by the login action which
     * may call this method to redirect the browser to where it goes after successful authentication.
     *
     * @param string|array $defaultUrl the default return URL in case it was not set previously.
     * If this is null and the return URL was not set previously, [[Application::homeUrl]] will be redirected to.
     * Please refer to [[setReturnUrl()]] on accepted format of the URL.
     * @return string the URL that the user should be redirected to after login.
     * @see loginRequired()
     */
    public function getReturnUrl($defaultUrl = null)
    {
        $url = $this->app->session->get($this->returnUrlParam, $defaultUrl);
        if (is_array($url)) {
            if (isset($url[0])) {
                return $this->app->urlManager->createUrl($url);
            }

            $url = null;
        }

        return $url === null ? $this->app->urlManager->getHomeUrl() : $url;
    }

    /**
     * Remembers the URL in the session so that it can be retrieved back later by [[getReturnUrl()]].
     * @param string|array $url the URL that the user should be redirected to after login.
     * If an array is given, [[UrlManager::createUrl()]] will be called to create the corresponding URL.
     * The first element of the array should be the route, and the rest of
     * the name-value pairs are GET parameters used to construct the URL. For example,
     *
     * ```php
     * ['admin/index', 'ref' => 1]
     * ```
     */
    public function setReturnUrl($url)
    {
        $this->app->session->set($this->returnUrlParam, $url);
    }

    /**
     * Redirects the user browser to the login page.
     *
     * Before the redirection, the current URL (if it's not an AJAX url) will be kept as [[returnUrl]] so that
     * the user browser may be redirected back to the current page after successful login.
     *
     * Make sure you set [[loginUrl]] so that the user browser can be redirected to the specified login URL after
     * calling this method.
     *
     * Note that when [[loginUrl]] is set, calling this method will NOT terminate the application execution.
     *
     * @param bool $checkAjax whether to check if the request is an AJAX request. When this is true and the request
     * is an AJAX request, the current URL (for AJAX request) will NOT be set as the return URL.
     * @param bool $checkAcceptHeader whether to check if the request accepts HTML responses. Defaults to `true`. When this is true and
     * the request does not accept HTML responses the current URL will not be SET as the return URL. Also instead of
     * redirecting the user an ForbiddenHttpException is thrown. This parameter is available since version 2.0.8.
     * @return ResponseBuilderInterface the redirection response if [[loginUrl]] is set
     * @throws ForbiddenException the "Access Denied" HTTP exception if [[loginUrl]] is not set or a redirect is
     * not applicable.
     */
    public function loginRequired($checkAjax = true, $checkAcceptHeader = true)
    {
        $request = $this->request;
        $canRedirect = !$checkAcceptHeader || $this->checkRedirectAcceptable();
        if ($this->enableSession
            && $request->getIsGet()
            && (!$checkAjax || !$request->getIsAjax())
            && $canRedirect
        ) {
            $this->setReturnUrl($request->getUrl());
        }
        if ($this->loginUrl !== null && $canRedirect) {
            $loginUrl = (array)$this->loginUrl;
            if ($loginUrl[0] !== $this->app->getRoute()->getRoutePath(true)) {
                return $this->app->response->redirect($this->loginUrl);
            }
        }
        throw new ForbiddenException(Reaction::t('rct', 'Login Required'));
    }

    /**
     * This method is called before logging in a user.
     * The default implementation will trigger the [[EVENT_BEFORE_LOGIN]] event.
     * If you override this method, make sure you call the parent implementation
     * so that the event is triggered.
     * @param IdentityInterface $identity the user identity information
     * @param bool              $cookieBased whether the login is cookie-based
     * @param int               $duration number of seconds that the user can remain in logged-in status.
     * If 0, it means login till the user closes the browser or the session is manually destroyed.
     * @return \React\Promise\PromiseInterface
     */
    protected function beforeLogin($identity, $cookieBased, $duration)
    {
        return $this->emitAndWait(static::EVENT_BEFORE_LOGIN, [&$identity, $cookieBased, $duration]);
    }

    /**
     * This method is called after the user is successfully logged in.
     * The default implementation will trigger the [[EVENT_AFTER_LOGIN]] event.
     * If you override this method, make sure you call the parent implementation
     * so that the event is triggered.
     * @param IdentityInterface $identity the user identity information
     * @param bool              $cookieBased whether the login is cookie-based
     * @param int               $duration number of seconds that the user can remain in logged-in status.
     * If 0, it means login till the user closes the browser or the session is manually destroyed.
     * @return \React\Promise\PromiseInterface
     */
    protected function afterLogin($identity, $cookieBased, $duration)
    {
        return $this->emitAndWait(static::EVENT_AFTER_LOGIN, [&$identity, $cookieBased, $duration]);
    }

    /**
     * This method is invoked when calling [[logout()]] to log out a user.
     * The default implementation will trigger the [[EVENT_BEFORE_LOGOUT]] event.
     * If you override this method, make sure you call the parent implementation
     * so that the event is triggered.
     * @param IdentityInterface $identity the user identity information
     * @return \React\Promise\PromiseInterface whether the user should continue to be logged out
     */
    protected function beforeLogout($identity)
    {
        return $this->emitAndWait(static::EVENT_BEFORE_LOGOUT, [&$identity]);
    }

    /**
     * This method is invoked right after a user is logged out via [[logout()]].
     * The default implementation will trigger the [[EVENT_AFTER_LOGOUT]] event.
     * If you override this method, make sure you call the parent implementation
     * so that the event is triggered.
     * @param IdentityInterface $identity the user identity information
     * @return \React\Promise\PromiseInterface
     */
    protected function afterLogout($identity)
    {
        return $this->emitAndWait(static::EVENT_AFTER_LOGOUT, [&$identity]);
    }

    /**
     * Renews the identity cookie.
     * This method will set the expiration time of the identity cookie to be the current time
     * plus the originally specified cookie duration.
     */
    protected function renewIdentityCookie()
    {
        $name = $this->identityCookie['name'];
        $value = $this->request->getCookies()->getValue($name);
        if ($value !== null) {
            $data = json_decode($value, true);
            if (is_array($data) && isset($data[2])) {
                $cookie = Reaction::create(array_merge($this->identityCookie, [
                    'class' => 'Reaction\Web\Cookie',
                    'value' => $value,
                    'expire' => time() + (int)$data[2],
                ]));
                $this->app->response->getCookies()->add($cookie);
            }
        }
    }

    /**
     * Sends an identity cookie.
     * This method is used when [[enableAutoLogin]] is true.
     * It saves [[id]], [[IdentityInterface::getAuthKey()|auth key]], and the duration of cookie-based login
     * information in the cookie.
     * @param IdentityInterface $identity
     * @param int               $duration number of seconds that the user can remain in logged-in status.
     * @see loginByCookie()
     */
    protected function sendIdentityCookie($identity, $duration)
    {
        $cookie = Reaction::create(array_merge($this->identityCookie, [
            'class' => 'Reaction\Web\Cookie',
            'value' => json_encode([
                $identity->getId(),
                $identity->getAuthKey(),
                $duration,
            ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
            'expire' => time() + $duration,
        ]));
        $this->app->response->getCookies()->add($cookie);
    }

    /**
     * Determines if an identity cookie has a valid format and contains a valid auth key.
     * This method is used when [[enableAutoLogin]] is true.
     * This method attempts to authenticate a user using the information in the identity cookie.
     * @return ExtendedPromiseInterface with array|null Returns an array of 'identity' and 'duration' if valid, otherwise null.
     * @see loginByCookie()
     */
    protected function getIdentityAndDurationFromCookie()
    {
        $value = $this->request->getCookies()->getValue($this->identityCookie['name']);
        if ($value === null) {
            return reject(null);
        }
        $data = json_decode($value, true);
        if (is_array($data) && count($data) == 3) {
            list($id, $authKey, $duration) = $data;
            /* @var $class IdentityInterface */
            $class = $this->identityClass;
            return $class::findIdentity($id)
                ->then(null, function($error) {
                    $this->removeIdentityCookie();
                    return reject($error);
                })->then(function($identity) use ($id, $authKey, $class, $duration) {
                    if (!$identity instanceof IdentityInterface) {
                        throw new InvalidValueException("$class::findIdentity() must return an object implementing IdentityInterface.");
                    } elseif (!$identity->validateAuthKey($authKey)) {
                        Reaction::warning("Invalid auth key attempted for user '$id': $authKey");
                        throw new InvalidValueException("Invalid auth key attempted for user '$id': $authKey");
                    } else {
                        return ['identity' => $identity, 'duration' => $duration];
                    }
                });
        }
        $this->removeIdentityCookie();
        return reject(null);
    }

    /**
     * Removes the identity cookie.
     * This method is used when [[enableAutoLogin]] is true.
     */
    protected function removeIdentityCookie()
    {
        $cookie = Reaction::create(array_merge($this->identityCookie, [
            'class' => 'Reaction\Web\Cookie',
        ]));
        $this->app->response->getCookies()->remove($cookie);
    }

    /**
     * Switches to a new identity for the current user.
     *
     * When [[enableSession]] is true, this method may use session and/or cookie to store the user identity information,
     * according to the value of `$duration`. Please refer to [[login()]] for more details.
     *
     * This method is mainly called by [[login()]], [[logout()]] and [[loginByCookie()]]
     * when the current user needs to be associated with the corresponding identity information.
     *
     * @param IdentityInterface|null $identity the identity information to be associated with the current user.
     * If null, it means switching the current user to be a guest.
     * @param int $duration number of seconds that the user can remain in logged-in status.
     * This parameter is used only when `$identity` is not null.
     */
    public function switchIdentity($identity, $duration = 0)
    {
        $this->setIdentity($identity);

        if (!$this->enableSession) {
            return;
        }

        /* Ensure any existing identity cookies are removed. */
        if ($this->enableAutoLogin && ($this->autoRenewCookie || $identity === null)) {
            $this->removeIdentityCookie();
        }

        $session = $this->app->session;
        if (!Reaction::isTest()) {
            $session->regenerateID(true);
        }
        $session->remove($this->idParam);
        $session->remove($this->authTimeoutParam);

        if ($identity) {
            $session->set($this->idParam, $identity->getId());
            if ($this->authTimeout !== null) {
                $session->set($this->authTimeoutParam, time() + $this->authTimeout);
            }
            if ($this->absoluteAuthTimeout !== null) {
                $session->set($this->absoluteAuthTimeoutParam, time() + $this->absoluteAuthTimeout);
            }
            if ($this->enableAutoLogin && $duration > 0) {
                $this->sendIdentityCookie($identity, $duration);
            }
        }
    }

    /**
     * Updates the authentication status using the information from session and cookie.
     *
     * This method will try to determine the user identity using the [[idParam]] session variable.
     *
     * If [[authTimeout]] is set, this method will refresh the timer.
     *
     * If the user identity cannot be determined by session, this method will try to [[loginByCookie()|login by cookie]]
     * if [[enableAutoLogin]] is true.
     * @return ExtendedPromiseInterface
     */
    protected function renewAuthStatus()
    {
        $session = $this->app->session;
        $id = $session->getHasSessionId() || $session->getIsActive() ? $session->get($this->idParam) : null;

        if ($id === null) {
            $identityPromise = resolve(null);
        } else {
            /* @var $class IdentityInterface */
            $class = $this->identityClass;
            $identityPromise = $class::findIdentity($id);
        }

        return $identityPromise
            ->then(function($identity) use ($session) {
                /** @var IdentityInterface $identity */
                $this->setIdentity($identity);

                $logoutPromise = resolve(true);
                if ($identity !== null && ($this->authTimeout !== null || $this->absoluteAuthTimeout !== null)) {
                    $expire = $this->authTimeout !== null ? $session->get($this->authTimeoutParam) : null;
                    $expireAbsolute = $this->absoluteAuthTimeout !== null ? $session->get($this->absoluteAuthTimeoutParam) : null;
                    if ($expire !== null && $expire < time() || $expireAbsolute !== null && $expireAbsolute < time()) {
                        $logoutPromise = $this->logout(false);
                    } elseif ($this->authTimeout !== null) {
                        $session->set($this->authTimeoutParam, time() + $this->authTimeout);
                    }
                }

                return $logoutPromise->then(function() {
                    if ($this->enableAutoLogin) {
                        if ($this->getIsGuest()) {
                            return $this->loginByCookie();
                        } elseif ($this->autoRenewCookie) {
                            $this->renewIdentityCookie();
                        }
                    }
                    return true;
                });
            });
    }

    /**
     * Checks if the user can perform the operation as specified by the given permission.
     *
     * Note that you must configure "authManager" application component in order to use this method.
     * Otherwise it will always return false.
     *
     * @param string $permissionName the name of the permission (e.g. "edit post") that needs access check.
     * @param array $params name-value pairs that would be passed to the rules associated
     * with the roles and permissions assigned to the user.
     * @param bool $allowCaching whether to allow caching the result of access check.
     * When this parameter is true (default), if the access check of an operation was performed
     * before, its result will be directly returned when calling this method to check the same
     * operation. If this parameter is false, this method will always call
     * [[\Reaction\Rbac\CheckAccessInterface::checkAccess()]] to obtain the up-to-date access result. Note that this
     * caching is effective only within the same request and only works when `$params = []`.
     * @return ExtendedPromiseInterface with bool whether the user can perform the operation as specified by the given permission.
     */
    public function can($permissionName, $params = [], $allowCaching = true)
    {
        //Special permissions for logged in status handling
        if (in_array($permissionName, [static::PERMISSION_NOT_LOGGED_IN, static::PERMISSION_LOGGED_IN])) {
            $isGuest = $this->getIsGuest();
            if ($isGuest && static::PERMISSION_NOT_LOGGED_IN || !$isGuest && static::PERMISSION_LOGGED_IN) {
                return resolve(true);
            }
            return reject(new Error("Uses::can() - denied by logged in status"));
        }
        if ($allowCaching && empty($params) && isset($this->_access[$permissionName])) {
            return $this->_access[$permissionName]
                ? resolve(true)
                : reject(new Error("Uses::can() - denied"));
        }
        if (($accessChecker = $this->getAccessChecker()) === null) {
            return reject(new Error("Uses::can() - denied (no access checker)"));
        }
        return $accessChecker->checkAccess($this->getId(), $permissionName, $params)
            ->otherwise(function() {
                return false;
            })
            ->then(function($access) use ($allowCaching, $permissionName) {
                if ($allowCaching && empty($params)) {
                    $this->_access[$permissionName] = $access;
                }
                return $access ? resolve(true) : reject(new Error("Uses::can() - denied"));
            });
    }

    /**
     * Check that component was initialized earlier
     * @return bool
     */
    public function isInitialized()
    {
        return $this->_initialized;
    }

    /**
     * Checks if the `Accept` header contains a content type that allows redirection to the login page.
     * The login page is assumed to serve `text/html` or `application/xhtml+xml` by default. You can change acceptable
     * content types by modifying [[acceptableRedirectTypes]] property.
     * @return bool whether this request may be redirected to the login page.
     * @see acceptableRedirectTypes
     */
    protected function checkRedirectAcceptable()
    {
        $acceptableTypes = $this->request->getAcceptableContentTypes();
        if (empty($acceptableTypes) || count($acceptableTypes) === 1 && array_keys($acceptableTypes)[0] === '*/*') {
            return true;
        }

        foreach ($acceptableTypes as $type => $params) {
            if (in_array($type, $this->acceptableRedirectTypes, true)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Returns the access checker used for checking access.
     * @return CheckAccessInterface|null
     */
    protected function getAccessChecker()
    {
        return $this->accessChecker !== null ? $this->accessChecker : Reaction::$app->getAuthManager();
    }

    /**
     * Get Request helper
     * @return RequestHelper
     */
    protected function getRequest() {
        return $this->app->reqHelper;
    }
}


<?php

declare(strict_types = 1);

namespace Speicher210\BusinessHours\Day;

/**
 * Represents a standard business day.
 */
class Day extends AbstractDay
{
    /**
     * Get the days of week.
     *
     * @return integer[]
     */
    public static function getDaysOfWeek(): array
    {
        return [
            self::WEEK_DAY_MONDAY,
            self::WEEK_DAY_TUESDAY,
            self::WEEK_DAY_WEDNESDAY,
            self::WEEK_DAY_THURSDAY,
            self::WEEK_DAY_FRIDAY,
            self::WEEK_DAY_SATURDAY,
            self::WEEK_DAY_SUNDAY,
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function jsonSerialize()
    {
        return [
            'dayOfWeek' => $this->dayOfWeek,
            'openingIntervals' => $this->openingHoursIntervals,
        ];
    }
}


<?php
namespace cymapgt\core\utility\notifier;

use cymapgt\Exception\NotifierEmailException;
use cymapgt\core\utility\notifier\abstractclass\NotifierInterface;

/**
 * class NotifierSmsService
 *
 * This interface implements the Notifier interface to provide a standard
 * method of configuring and using SMS Notification library of AfricasTalking
 *
 * PHP versions 7.0+
 *
 * @category    utility
 * @package     cymapgt.core.utility.notifier
 * @author      Cyril Ogana <cogana@gmail.com>
 * @copyright   2017 CYMAPK
 */

class NotifierSmsAfricasTalkingService implements NotifierInterface
{
    //the notifier type e.g. Email, SMS
    protected $notifierType  = null;

    //array of configurations required
    protected $configuration = array (
                                    "SMS_CLIENT"      => "AfricasTalking",
                                    "USERNAME"        => "",
                                    "PASSWORD"        => "",
                                    "APIKEY"          => "",
                                    "IS_API"          => true,
                                    "IS_BEHIND_PROXY" => false,
                                    "PROXY_AUTH"      => -1,
                                    "PROXY_TYPE"      => -1,
                                    "PROXY_SERVER"    => "",
                                    "PROXY_LOGIN"     => "",
                                    "MAX_CHARS"       => 140,
                                    "SMS_FROM_NAME"   => ""
                               );

    //template settings e.g. if using php, smarty or twig
    protected $templatePath = "";
    protected $templateName = "";

    //init array, for additional data needed to do the job, after configuration
    protected $initArr = array();

    //messages array, where message payloads are stored before sending
    protected $messages = array();

    protected $mailHandler = null;

    /**
     * function __construct() - Constructor method
     */
    public function __construct($configurationArr, $isBehindProxy = false){
        //bootstrap the handler immediately
        $this->_bootstrapSmsHandler($configurationArr, $isBehindProxy);
    }

    /**
     * function setNotifierType() - Set the notifier type as per NotifierType data store
     * @param   string $type  - The notification type
     *
     * @return  void
     */
    public function setNotifierType($type){
        $this->notifierType = $type;
    }

    /**
     * function getNotifierType() - Get the notifier type as per NotifierType data store
     *
     * @return  string
     */
    public function getNotifierType(){
        return $this->notifierType;
    }

    /**
     * function setConfiguration() - Set all required configurations, passed in as an array
     * @param   array $configuration  - Array of various required configuration options
     *
     * @return  void
     */
    public function setConfiguration($configuration){
        $emailRequiredConfigurations = $this->configuration;
        $configDiff = array_diff($emailRequiredConfigurations, $configuration);

        //validate that all required email settings are present
        if(is_array($configDiff
           && count($configDiff))
        ){
            throw new NotifierEmailException("The configuration array does not contain all required Email configurations");
        }

        //set the configuration provided
        $this->configuration = $configuration;
    }

    /**
     * function getConfiguration() - Return the set configuration option array
     *
     * @return  array
     */
    public function getConfiguration(){
        return $this->configuration;
    }

    /**
     * function setTemplatePath() - Set the path to template files to use for the notifier service
     *
     * @param   string $path     - Path to the notification template file
     * @param   string $name     - Name of the notification template file
     *
     * @return  void
     */
    public function setTemplatePath($path, $name){
        $this->templateName = $name;
        $this->templatePath = $path;
    }

    /**
     * function getTemplatePath() - Return the set template path
     *
     * @return  string
     */
    public function getTemplatePath(){
        return $this->templatePath;
    }

    /**
     * function getTemplateName() - Return the set template name
     *
     * @return  string
     */
    public function getTemplateName(){
        return $this->templateName;
    }

     /**
     * function initialize() - Initialize the object to workable state, should be called after
     *                         setting the configurations
     * @param   array $initArr     - Any additional initialization parameters
     *
     * @return  void
     */
    public function initialize($initArr){
        $this->initArr = $initArr;
    }

    /**
     * function setMessage() - Input the actual message payload
     * @param   array $message - Array containing message payload e.g head,body,subject
     *
     * @return  void
     */
    public function setMessage($message){
        $this->messages[] = $message;
    }

     /**
     * function getMessage() - Return all message payloads
     *
     * @return  array
     */
    public function getMessage(){
        return $this->messages;
    }

    /**
     * function getMessageById() - Return a message by its id
     *
     * @param mixed  $messageId
     *
     * @return array
     */
    public function getMessageById($messageId){
        if(isset($this->messages[$messageId])){
            return $this->messages[$messageId];
        }else{
            return false;
        }
    }

    /**
     * function resetMessageById() - Unset the message from $messages array
     *                               based on its ID
     * @param   mixed $messageId
     *
     * @return  boolean
     */
    public function resetMessageById($messageId){
        if(isset($this->messages[$messageId])){
            unset($this->messages[$messageId]);
            return true;
        }else{
            return false;
        }
    }

    /**
     * function resetMessagesAll() - Unset all messages in $messages array
     *
     * @return  boolean
     */
    public function resetMessagesAll(){
        foreach($this->messages as $key => $message){
            unset($this->messages[$key]);
        }
    }

    /**
     * function resetMessageById() - Send message where the payload has only
     *                               one message in its listing
     * @param   mixed $messageId
     *
     * @return  boolean
     */
    public function sendMessageOne($sendSettings){
        //get the key of the first message
        reset($this->messages);
        $key = key($this->messages);
        $recipients = $this->messages[$key]["RECIPIENTS"];
        $message    = $this->messages[$key]["MESSAGE"];
        $senderName = $this->configuration["SMS_FROM_NAME"];

        //phpmailer exception used
        try {
            $this->mailHandler->sendMessage($recipients, $message, $senderName);
        } catch (AfricasTalkingGatewayException $ex) {
            die($ex->errorMessage());
        }

        //pop the message stack
        $msgStack = $this->messages;
        array_shift($msgStack);
        $this->messages = $msgStack;
    }

    /**
     * function sendMessageById() - Set message using its id
     *
     * @param   array $sendSettings - Additional send settings
     * @param   int   $messageId    - The message Id
     *
     * @return  boolean
     */
    public function sendMessageById($sendSettings, $messageId) {
        $messageId = (int) $messageId;

        if (!isset($this->messages[$messageId])) {
            throw new NotifierEmailException('Trying to send Message by Id, for an Id that is not set');
        }

        $recipients = $this->messages[$messageId]['RECIPIENTS'];
        $message    = $this->messages[$messageId]['MESSAGE'];
        $senderName = $this->configuration['SMS_FROM_NAME'];

        //AfricasTalkingGatewayException used
        try {
            $this->mailHandler->sendMessage($recipients, $message, $senderName);
        } catch (Exception $ex) {
            die($ex->errorMessage());
        }
    }

    /**
     * function sendMessagesAll() - Send all messages in the messages
     *                              array
     *
     * @param   array $sendSettings - Additional send settings
     *
     * @return  boolean
     */
    public function sendMessagesAll($sendSettings){
        while(count($this->messages) > 0) {
            $this->sendMessageOne($sendSettings);
        }
    }

    /**
     * function _bootstrapSmsHandler() - Prepare the mailHandler by setting the configurations
     *
     * @return void
     *
     * @access private
     */
    private function _bootstrapSmsHandler($configurationArr, $isBehindProxy = false){
        //validate that username and APIKEY exist in the configuration
        if (
            !isset($configurationArr["USERNAME"])
            && !isset($configurationArr["APIKEY"])
        ) {
            throw new NotifierEmailException("The username or APIKEY is not configured");
        }

        $userName = $configurationArr["USERNAME"];
        $apiKey   = $configurationArr["APIKEY"];

        //if behind proxy, we also need proxy settings
        if($isBehindProxy){
            if (
                !isset($configurationArr["PROXY_AUTH"])
                && !isset($configurationArr["PROXY_TYPE"])
                && !isset($configurationArr["PROXY_SERVER"])
                && !isset($configurationArr["PROXY_LOGIN"])
            ){
                throw new NotifierEmailException("The proxy settings are not configured properly");
            }

            $proxySettings = array (
                "PROXYAUTH"   => $configurationArr["PROXY_AUTH"],
                "PROXYTYPE"   => $configurationArr["PROXY_TYPE"],
                "PROXYSERVER" => $configurationArr["PROXY_SERVER"],
                "PROXYLOGIN"  => $configurationArr["PROXY_LOGIN"]
            );

            //initiate the handler with credentials
            $this->mailHandler = new \AfricasTalkingGatewayWithProxy(
                $userName,
                $apiKey,
                $proxySettings
            );
        } else {
            $this->mailHandler = new \AfricasTalkingGateway(
                $userName,
                $apiKey
            );
        }

        //Set the configuration array
        $this->setConfiguration($configurationArr);
    }
}


<?php

namespace Colorium\Http\Request;

class File
{

    const OK = 0;
    const MAX_SIZE = 1;
    const FORM_SIZE = 2;
    const PARTIAL = 3;
    const NO_FILE = 4;
    const NO_TMP_DIR = 6;
    const CANT_WRITE = 7;
    const ERR_EXTENSION = 8;

    /** @var string */
    public $name;

    /** @var string */
    public $ext;

    /** @var string */
    public $tmp;

    /** @var string */
    public $type;

    /** @var int */
    public $size;

    /** @var int */
    public $error = self::OK;

    /**
     * Create from $_FILES
     *
     * @param array $file
     */
    public function __construct(array $file)
    {
        $this->name = basename($file['name']);
        $this->ext = pathinfo($this->name, PATHINFO_EXTENSION);
        $this->tmp = $file['tmp_name'];
        $this->type = $file['type'];
        $this->size = $file['size'];
        $this->error = (int)$file['error'];
    }

    /**
     * Save file to directory
     *
     * @param string $dir
     * @param string $filename
     *
     * @return bool
     */
    public function save($dir, $filename = null)
    {
        // clean
        $dir = rtrim($dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
        if(!$filename) {
            $filename = $this->name;
        }

        return move_uploaded_file($this->tmp, $dir . $filename);
    }

}


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

namespace FSth\Framework\Dao;

use Doctrine\DBAL\Query\Expression\CompositeExpression;
use Doctrine\DBAL\Connection;

/**
 * QueryBuilder class is responsible to dynamically create SQL queries.
 *
 * Important: Verify that every feature you use will work with your database vendor.
 * SQL Query Builder does not attempt to validate the generated SQL at all.
 *
 * The query builder does no validation whatsoever if certain features even work with the
 * underlying database vendor. Limit queries and joins are NOT applied to UPDATE and DELETE statements
 * even if some vendors such as MySQL support it.
 *
 * @link   www.doctrine-project.org
 * @since  2.1
 * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author Benjamin Eberlei <kontakt@beberlei.de>
 */
class QueryBuilder
{
    /*
     * The query types.
     */
    const SELECT = 0;
    const DELETE = 1;
    const UPDATE = 2;
    const INSERT = 3;

    /*
     * The builder states.
     */
    const STATE_DIRTY = 0;
    const STATE_CLEAN = 1;

    /**
     * The DBAL Connection.
     *
     * @var \Doctrine\DBAL\Connection
     */
    private $connection;

    /**
     * @var array The array of SQL parts collected.
     */
    private $sqlParts = array(
        'select' => array(),
        'from' => array(),
        'join' => array(),
        'set' => array(),
        'where' => null,
        'groupBy' => array(),
        'having' => null,
        'orderBy' => array(),
        'values' => array(),
    );

    /**
     * The complete SQL string for this query.
     *
     * @var string
     */
    private $sql;

    /**
     * The query parameters.
     *
     * @var array
     */
    private $params = array();

    /**
     * The parameter type map of this query.
     *
     * @var array
     */
    private $paramTypes = array();

    /**
     * The type of query this is. Can be select, update or delete.
     *
     * @var integer
     */
    private $type = self::SELECT;

    /**
     * The state of the query object. Can be dirty or clean.
     *
     * @var integer
     */
    private $state = self::STATE_CLEAN;

    /**
     * The index of the first result to retrieve.
     *
     * @var integer
     */
    private $firstResult = null;

    /**
     * The maximum number of results to retrieve.
     *
     * @var integer
     */
    private $maxResults = null;

    /**
     * The counter of bound parameters used with {@see bindValue).
     *
     * @var integer
     */
    private $boundCounter = 0;

    /**
     * Initializes a new <tt>QueryBuilder</tt>.
     *
     * @param \Doctrine\DBAL\Connection $connection The DBAL Connection.
     */
    public function __construct($connection)
    {
        $this->connection = $connection;
    }

    /**
     * Gets an ExpressionBuilder used for object-oriented construction of query expressions.
     * This producer method is intended for convenient inline usage. Example:
     *
     *
     *     $qb = $conn->createQueryBuilder()
     *         ->select('u')
     *         ->from('users', 'u')
     *         ->where($qb->expr()->eq('u.id', 1));
     *
     *
     * For more complex expression construction, consider storing the expression
     * builder object in a local variable.
     *
     * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
     */
    public function expr()
    {
        return $this->connection->getExpressionBuilder();
    }

    /**
     * Gets the type of the currently built query.
     *
     * @return integer
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * Gets the associated DBAL Connection for this query builder.
     *
     * @return \Doctrine\DBAL\Connection
     */
    public function getConnection()
    {
        return $this->connection;
    }

    /**
     * Gets the state of this query builder instance.
     *
     * @return integer Either QueryBuilder::STATE_DIRTY or QueryBuilder::STATE_CLEAN.
     */
    public function getState()
    {
        return $this->state;
    }

    /**
     * Executes this query using the bound parameters and their types.
     *
     * Uses {@see Connection::executeQuery} for select statements and {@see Connection::executeUpdate}
     * for insert, update and delete statements.
     *
     * @return \Doctrine\DBAL\Driver\Statement|int
     */
    public function execute()
    {
        if ($this->type == self::SELECT) {
            return $this->connection->executeQuery($this->getSQL(), $this->params, $this->paramTypes);
        } else {
            return $this->connection->executeUpdate($this->getSQL(), $this->params, $this->paramTypes);
        }
    }

    /**
     * Gets the complete SQL string formed by the current specifications of this QueryBuilder.
     *
     *
     *     $qb = $em->createQueryBuilder()
     *         ->select('u')
     *         ->from('User', 'u')
     *     echo $qb->getSQL(); // SELECT u FROM User u
     *
     *
     * @return string The SQL query string.
     */
    public function getSQL()
    {
        if ($this->sql !== null && $this->state === self::STATE_CLEAN) {
            return $this->sql;
        }

        switch ($this->type) {
            case self::INSERT:
                $sql = $this->getSQLForInsert();
                break;
            case self::DELETE:
                $sql = $this->getSQLForDelete();
                break;

            case self::UPDATE:
                $sql = $this->getSQLForUpdate();
                break;

            case self::SELECT:
            default:
                $sql = $this->getSQLForSelect();
                break;
        }

        $this->state = self::STATE_CLEAN;
        $this->sql = $sql;

        return $sql;
    }

    /**
     * Sets a query parameter for the query being constructed.
     *
     *
     *     $qb = $conn->createQueryBuilder()
     *         ->select('u')
     *         ->from('users', 'u')
     *         ->where('u.id = :user_id')
     *         ->setParameter(':user_id', 1);
     *
     *
     * @param string|integer $key The parameter position or name.
     * @param mixed $value The parameter value.
     * @param string|null $type One of the PDO::PARAM_* constants.
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
     */
    public function setParameter($key, $value, $type = null)
    {
        if ($type !== null) {
            $this->paramTypes[$key] = $type;
        }

        $this->params[$key] = $value;

        return $this;
    }

    /**
     * Sets a collection of query parameters for the query being constructed.
     *
     *
     *     $qb = $conn->createQueryBuilder()
     *         ->select('u')
     *         ->from('users', 'u')
     *         ->where('u.id = :user_id1 OR u.id = :user_id2')
     *         ->setParameters(array(
     *             ':user_id1' => 1,
     *             ':user_id2' => 2
     *         ));
     *
     *
     * @param array $params The query parameters to set.
     * @param array $types The query parameters types to set.
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
     */
    public function setParameters(array $params, array $types = array())
    {
        $this->paramTypes = $types;
        $this->params = $params;

        return $this;
    }

    /**
     * Gets all defined query parameters for the query being constructed indexed by parameter index or name.
     *
     * @return array The currently defined query parameters indexed by parameter index or name.
     */
    public function getParameters()
    {
        return $this->params;
    }

    /**
     * Gets a (previously set) query parameter of the query being constructed.
     *
     * @param mixed $key The key (index or name) of the bound parameter.
     *
     * @return mixed The value of the bound parameter.
     */
    public function getParameter($key)
    {
        return isset($this->params[$key]) ? $this->params[$key] : null;
    }

    /**
     * Gets all defined query parameter types for the query being constructed indexed by parameter index or name.
     *
     * @return array The currently defined query parameter types indexed by parameter index or name.
     */
    public function getParameterTypes()
    {
        return $this->paramTypes;
    }

    /**
     * Gets a (previously set) query parameter type of the query being constructed.
     *
     * @param mixed $key The key (index or name) of the bound parameter type.
     *
     * @return mixed The value of the bound parameter type.
     */
    public function getParameterType($key)
    {
        return isset($this->paramTypes[$key]) ? $this->paramTypes[$key] : null;
    }

    /**
     * Sets the position of the first result to retrieve (the "offset").
     *
     * @param integer $firstResult The first result to return.
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
     */
    public function setFirstResult($firstResult)
    {
        $this->state = self::STATE_DIRTY;
        $this->firstResult = $firstResult;

        return $this;
    }

    /**
     * Gets the position of the first result the query object was set to retrieve (the "offset").
     * Returns NULL if {@link setFirstResult} was not applied to this QueryBuilder.
     *
     * @return integer The position of the first result.
     */
    public function getFirstResult()
    {
        return $this->firstResult;
    }

    /**
     * Sets the maximum number of results to retrieve (the "limit").
     *
     * @param integer $maxResults The maximum number of results to retrieve.
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
     */
    public function setMaxResults($maxResults)
    {
        $this->state = self::STATE_DIRTY;
        $this->maxResults = $maxResults;

        return $this;
    }

    /**
     * Gets the maximum number of results the query object was set to retrieve (the "limit").
     * Returns NULL if {@link setMaxResults} was not applied to this query builder.
     *
     * @return integer The maximum number of results.
     */
    public function getMaxResults()
    {
        return $this->maxResults;
    }

    /**
     * Either appends to or replaces a single, generic query part.
     *
     * The available parts are: 'select', 'from', 'set', 'where',
     * 'groupBy', 'having' and 'orderBy'.
     *
     * @param string $sqlPartName
     * @param string $sqlPart
     * @param boolean $append
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
     */
    public function add($sqlPartName, $sqlPart, $append = false)
    {
        $isArray = is_array($sqlPart);
        $isMultiple = is_array($this->sqlParts[$sqlPartName]);

        if ($isMultiple && !$isArray) {
            $sqlPart = array($sqlPart);
        }

        $this->state = self::STATE_DIRTY;

        if ($append) {
            if ($sqlPartName == "orderBy" || $sqlPartName == "groupBy" || $sqlPartName == "select" || $sqlPartName == "set") {
                foreach ($sqlPart as $part) {
                    $this->sqlParts[$sqlPartName][] = $part;
                }
            } elseif ($isArray && is_array($sqlPart[key($sqlPart)])) {
                $key = key($sqlPart);
                $this->sqlParts[$sqlPartName][$key][] = $sqlPart[$key];
            } elseif ($isMultiple) {
                $this->sqlParts[$sqlPartName][] = $sqlPart;
            } else {
                $this->sqlParts[$sqlPartName] = $sqlPart;
            }

            return $this;
        }

        $this->sqlParts[$sqlPartName] = $sqlPart;

        return $this;
    }

    /**
     * Specifies an item that is to be returned in the query result.
     * Replaces any previously specified selections, if any.
     *
     *
     *     $qb = $conn->createQueryBuilder()
     *         ->select('u.id', 'p.id')
     *         ->from('users', 'u')
     *         ->leftJoin('u', 'phonenumbers', 'p', 'u.id = p.user_id');
     *
     *
     * @param mixed $select The selection expressions.
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
     */
    public function select($select = null)
    {
        $this->type = self::SELECT;

        if (empty($select)) {
            return $this;
        }

        $selects = is_array($select) ? $select : func_get_args();

        return $this->add('select', $selects, false);
    }

    /**
     * Adds an item that is to be returned in the query result.
     *
     *
     *     $qb = $conn->createQueryBuilder()
     *         ->select('u.id')
     *         ->addSelect('p.id')
     *         ->from('users', 'u')
     *         ->leftJoin('u', 'phonenumbers', 'u.id = p.user_id');
     *
     *
     * @param mixed $select The selection expression.
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
     */
    public function addSelect($select = null)
    {
        $this->type = self::SELECT;

        if (empty($select)) {
            return $this;
        }

        $selects = is_array($select) ? $select : func_get_args();

        return $this->add('select', $selects, true);
    }

    /**
     * Turns the query being built into a bulk delete query that ranges over
     * a certain table.
     *
     *
     *     $qb = $conn->createQueryBuilder()
     *         ->delete('users', 'u')
     *         ->where('u.id = :user_id');
     *         ->setParameter(':user_id', 1);
     *
     *
     * @param string $delete The table whose rows are subject to the deletion.
     * @param string $alias The table alias used in the constructed query.
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
     */
    public function delete($delete = null, $alias = null)
    {
        $this->type = self::DELETE;

        if (!$delete) {
            return $this;
        }

        return $this->add('from', array(
            'table' => $delete,
            'alias' => $alias
        ));
    }

    /**
     * Turns the query being built into a bulk update query that ranges over
     * a certain table
     *
     *
     *     $qb = $conn->createQueryBuilder()
     *         ->update('users', 'u')
     *         ->set('u.password', md5('password'))
     *         ->where('u.id = ?');
     *
     *
     * @param string $update The table whose rows are subject to the update.
     * @param string $alias The table alias used in the constructed query.
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
     */
    public function update($update = null, $alias = null)
    {
        $this->type = self::UPDATE;

        if (!$update) {
            return $this;
        }

        return $this->add('from', array(
            'table' => $update,
            'alias' => $alias
        ));
    }

    /**
     * Turns the query being built into an insert query that inserts into
     * a certain table
     *
     *
     *     $qb = $conn->createQueryBuilder()
     *         ->insert('users')
     *         ->values(
     *             array(
     *                 'name' => '?',
     *                 'password' => '?'
     *             )
     *         );
     *
     *
     * @param string $insert The table into which the rows should be inserted.
     *
     * @return QueryBuilder This QueryBuilder instance.
     */
    public function insert($insert = null)
    {
        $this->type = self::INSERT;

        if (!$insert) {
            return $this;
        }

        return $this->add('from', array(
            'table' => $insert
        ));
    }

    /**
     * Creates and adds a query root corresponding to the table identified by the
     * given alias, forming a cartesian product with any existing query roots.
     *
     *
     *     $qb = $conn->createQueryBuilder()
     *         ->select('u.id')
     *         ->from('users', 'u')
     *
     *
     * @param string $from The table.
     * @param string|null $alias The alias of the table.
     *
     * @return QueryBuilder This QueryBuilder instance.
     */
    public function from($from, $alias = null)
    {
        return $this->add('from', array(
            'table' => $from,
            'alias' => $alias
        ), true);
    }

    /**
     * Creates and adds a join to the query.
     *
     *
     *     $qb = $conn->createQueryBuilder()
     *         ->select('u.name')
     *         ->from('users', 'u')
     *         ->join('u', 'phonenumbers', 'p', 'p.is_primary = 1');
     *
     *
     * @param string $fromAlias The alias that points to a from clause.
     * @param string $join The table name to join.
     * @param string $alias The alias of the join table.
     * @param string $condition The condition for the join.
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
     */
    public function join($fromAlias, $join, $alias, $condition = null)
    {
        return $this->innerJoin($fromAlias, $join, $alias, $condition);
    }

    /**
     * Creates and adds a join to the query.
     *
     *
     *     $qb = $conn->createQueryBuilder()
     *         ->select('u.name')
     *         ->from('users', 'u')
     *         ->innerJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1');
     *
     *
     * @param string $fromAlias The alias that points to a from clause.
     * @param string $join The table name to join.
     * @param string $alias The alias of the join table.
     * @param string $condition The condition for the join.
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
     */
    public function innerJoin($fromAlias, $join, $alias, $condition = null)
    {
        return $this->add('join', array(
            $fromAlias => array(
                'joinType' => 'inner',
                'joinTable' => $join,
                'joinAlias' => $alias,
                'joinCondition' => $condition
            )
        ), true);
    }

    /**
     * Creates and adds a left join to the query.
     *
     *
     *     $qb = $conn->createQueryBuilder()
     *         ->select('u.name')
     *         ->from('users', 'u')
     *         ->leftJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1');
     *
     *
     * @param string $fromAlias The alias that points to a from clause.
     * @param string $join The table name to join.
     * @param string $alias The alias of the join table.
     * @param string $condition The condition for the join.
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
     */
    public function leftJoin($fromAlias, $join, $alias, $condition = null)
    {
        return $this->add('join', array(
            $fromAlias => array(
                'joinType' => 'left',
                'joinTable' => $join,
                'joinAlias' => $alias,
                'joinCondition' => $condition
            )
        ), true);
    }

    /**
     * Creates and adds a right join to the query.
     *
     *
     *     $qb = $conn->createQueryBuilder()
     *         ->select('u.name')
     *         ->from('users', 'u')
     *         ->rightJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1');
     *
     *
     * @param string $fromAlias The alias that points to a from clause.
     * @param string $join The table name to join.
     * @param string $alias The alias of the join table.
     * @param string $condition The condition for the join.
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
     */
    public function rightJoin($fromAlias, $join, $alias, $condition = null)
    {
        return $this->add('join', array(
            $fromAlias => array(
                'joinType' => 'right',
                'joinTable' => $join,
                'joinAlias' => $alias,
                'joinCondition' => $condition
            )
        ), true);
    }

    /**
     * Sets a new value for a column in a bulk update query.
     *
     *
     *     $qb = $conn->createQueryBuilder()
     *         ->update('users', 'u')
     *         ->set('u.password', md5('password'))
     *         ->where('u.id = ?');
     *
     *
     * @param string $key The column to set.
     * @param string $value The value, expression, placeholder, etc.
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
     */
    public function set($key, $value)
    {
        return $this->add('set', $key . ' = ' . $value, true);
    }

    /**
     * Specifies one or more restrictions to the query result.
     * Replaces any previously specified restrictions, if any.
     *
     *
     *     $qb = $conn->createQueryBuilder()
     *         ->select('u.name')
     *         ->from('users', 'u')
     *         ->where('u.id = ?');
     *
     *     // You can optionally programatically build and/or expressions
     *     $qb = $conn->createQueryBuilder();
     *
     *     $or = $qb->expr()->orx();
     *     $or->add($qb->expr()->eq('u.id', 1));
     *     $or->add($qb->expr()->eq('u.id', 2));
     *
     *     $qb->update('users', 'u')
     *         ->set('u.password', md5('password'))
     *         ->where($or);
     *
     *
     * @param mixed $predicates The restriction predicates.
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
     */
    public function where($predicates)
    {
        if (!(func_num_args() == 1 && $predicates instanceof CompositeExpression)) {
            $predicates = new CompositeExpression(CompositeExpression::TYPE_AND, func_get_args());
        }

        return $this->add('where', $predicates);
    }

    /**
     * Adds one or more restrictions to the query results, forming a logical
     * conjunction with any previously specified restrictions.
     *
     *
     *     $qb = $conn->createQueryBuilder()
     *         ->select('u')
     *         ->from('users', 'u')
     *         ->where('u.username LIKE ?')
     *         ->andWhere('u.is_active = 1');
     *
     *
     * @param mixed $where The query restrictions.
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
     *
     * @see where()
     */
    public function andWhere($where)
    {
        $args = func_get_args();
        $where = $this->getQueryPart('where');

        if ($where instanceof CompositeExpression && $where->getType() === CompositeExpression::TYPE_AND) {
            $where->addMultiple($args);
        } else {
            array_unshift($args, $where);
            $where = new CompositeExpression(CompositeExpression::TYPE_AND, $args);
        }

        return $this->add('where', $where, true);
    }

    /**
     * Adds one or more restrictions to the query results, forming a logical
     * disjunction with any previously specified restrictions.
     *
     *
     *     $qb = $em->createQueryBuilder()
     *         ->select('u.name')
     *         ->from('users', 'u')
     *         ->where('u.id = 1')
     *         ->orWhere('u.id = 2');
     *
     *
     * @param mixed $where The WHERE statement.
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
     *
     * @see where()
     */
    public function orWhere($where)
    {
        $args = func_get_args();
        $where = $this->getQueryPart('where');

        if ($where instanceof CompositeExpression && $where->getType() === CompositeExpression::TYPE_OR) {
            $where->addMultiple($args);
        } else {
            array_unshift($args, $where);
            $where = new CompositeExpression(CompositeExpression::TYPE_OR, $args);
        }

        return $this->add('where', $where, true);
    }

    /**
     * Specifies a grouping over the results of the query.
     * Replaces any previously specified groupings, if any.
     *
     *
     *     $qb = $conn->createQueryBuilder()
     *         ->select('u.name')
     *         ->from('users', 'u')
     *         ->groupBy('u.id');
     *
     *
     * @param mixed $groupBy The grouping expression.
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
     */
    public function groupBy($groupBy)
    {
        if (empty($groupBy)) {
            return $this;
        }

        $groupBy = is_array($groupBy) ? $groupBy : func_get_args();

        return $this->add('groupBy', $groupBy, false);
    }

    /**
     * Adds a grouping expression to the query.
     *
     *
     *     $qb = $conn->createQueryBuilder()
     *         ->select('u.name')
     *         ->from('users', 'u')
     *         ->groupBy('u.lastLogin');
     *         ->addGroupBy('u.createdAt')
     *
     *
     * @param mixed $groupBy The grouping expression.
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
     */
    public function addGroupBy($groupBy)
    {
        if (empty($groupBy)) {
            return $this;
        }

        $groupBy = is_array($groupBy) ? $groupBy : func_get_args();

        return $this->add('groupBy', $groupBy, true);
    }

    /**
     * Sets a value for a column in an insert query.
     *
     *
     *     $qb = $conn->createQueryBuilder()
     *         ->insert('users')
     *         ->values(
     *             array(
     *                 'name' => '?'
     *             )
     *         )
     *         ->setValue('password', '?');
     *
     *
     * @param string $column The column into which the value should be inserted.
     * @param string $value The value that should be inserted into the column.
     *
     * @return QueryBuilder This QueryBuilder instance.
     */
    public function setValue($column, $value)
    {
        $this->sqlParts['values'][$column] = $value;

        return $this;
    }

    /**
     * Specifies values for an insert query indexed by column names.
     * Replaces any previous values, if any.
     *
     *
     *     $qb = $conn->createQueryBuilder()
     *         ->insert('users')
     *         ->values(
     *             array(
     *                 'name' => '?',
     *                 'password' => '?'
     *             )
     *         );
     *
     *
     * @param array $values The values to specify for the insert query indexed by column names.
     *
     * @return QueryBuilder This QueryBuilder instance.
     */
    public function values(array $values)
    {
        return $this->add('values', $values);
    }

    /**
     * Specifies a restriction over the groups of the query.
     * Replaces any previous having restrictions, if any.
     *
     * @param mixed $having The restriction over the groups.
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
     */
    public function having($having)
    {
        if (!(func_num_args() == 1 && $having instanceof CompositeExpression)) {
            $having = new CompositeExpression(CompositeExpression::TYPE_AND, func_get_args());
        }

        return $this->add('having', $having);
    }

    /**
     * Adds a restriction over the groups of the query, forming a logical
     * conjunction with any existing having restrictions.
     *
     * @param mixed $having The restriction to append.
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
     */
    public function andHaving($having)
    {
        $args = func_get_args();
        $having = $this->getQueryPart('having');

        if ($having instanceof CompositeExpression && $having->getType() === CompositeExpression::TYPE_AND) {
            $having->addMultiple($args);
        } else {
            array_unshift($args, $having);
            $having = new CompositeExpression(CompositeExpression::TYPE_AND, $args);
        }

        return $this->add('having', $having);
    }

    /**
     * Adds a restriction over the groups of the query, forming a logical
     * disjunction with any existing having restrictions.
     *
     * @param mixed $having The restriction to add.
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
     */
    public function orHaving($having)
    {
        $args = func_get_args();
        $having = $this->getQueryPart('having');

        if ($having instanceof CompositeExpression && $having->getType() === CompositeExpression::TYPE_OR) {
            $having->addMultiple($args);
        } else {
            array_unshift($args, $having);
            $having = new CompositeExpression(CompositeExpression::TYPE_OR, $args);
        }

        return $this->add('having', $having);
    }

    /**
     * Specifies an ordering for the query results.
     * Replaces any previously specified orderings, if any.
     *
     * @param string $sort The ordering expression.
     * @param string $order The ordering direction.
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
     */
    public function orderBy($sort, $order = null)
    {
        return $this->add('orderBy', $sort . ' ' . (!$order ? 'ASC' : $order), false);
    }

    /**
     * Adds an ordering to the query results.
     *
     * @param string $sort The ordering expression.
     * @param string $order The ordering direction.
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
     */
    public function addOrderBy($sort, $order = null)
    {
        return $this->add('orderBy', $sort . ' ' . (!$order ? 'ASC' : $order), true);
    }

    /**
     * Gets a query part by its name.
     *
     * @param string $queryPartName
     *
     * @return mixed
     */
    public function getQueryPart($queryPartName)
    {
        return $this->sqlParts[$queryPartName];
    }

    /**
     * Gets all query parts.
     *
     * @return array
     */
    public function getQueryParts()
    {
        return $this->sqlParts;
    }

    /**
     * Resets SQL parts.
     *
     * @param array|null $queryPartNames
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
     */
    public function resetQueryParts($queryPartNames = null)
    {
        if (is_null($queryPartNames)) {
            $queryPartNames = array_keys($this->sqlParts);
        }

        foreach ($queryPartNames as $queryPartName) {
            $this->resetQueryPart($queryPartName);
        }

        return $this;
    }

    /**
     * Resets a single SQL part.
     *
     * @param string $queryPartName
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder This QueryBuilder instance.
     */
    public function resetQueryPart($queryPartName)
    {
        $this->sqlParts[$queryPartName] = is_array($this->sqlParts[$queryPartName])
            ? array() : null;

        $this->state = self::STATE_DIRTY;

        return $this;
    }

    /**
     * @return string
     *
     * @throws \Doctrine\DBAL\Query\QueryException
     */
    private function getSQLForSelect()
    {
        $query = 'SELECT ' . implode(', ', $this->sqlParts['select']);

        $query .= ($this->sqlParts['from'] ? ' FROM ' . implode(', ', $this->getFromClauses()) : '')
            . ($this->sqlParts['where'] !== null ? ' WHERE ' . ((string)$this->sqlParts['where']) : '')
            . ($this->sqlParts['groupBy'] ? ' GROUP BY ' . implode(', ', $this->sqlParts['groupBy']) : '')
            . ($this->sqlParts['having'] !== null ? ' HAVING ' . ((string)$this->sqlParts['having']) : '')
            . ($this->sqlParts['orderBy'] ? ' ORDER BY ' . implode(', ', $this->sqlParts['orderBy']) : '');

        if ($this->isLimitQuery()) {
            return $this->connection->getDatabasePlatform()->modifyLimitQuery(
                $query,
                $this->maxResults,
                $this->firstResult
            );
        }

        return $query;
    }

    /**
     * @return string[]
     */
    private function getFromClauses()
    {
        $fromClauses = array();
        $knownAliases = array();

        // Loop through all FROM clauses
        foreach ($this->sqlParts['from'] as $from) {
            if ($from['alias'] === null) {
                $tableSql = $from['table'];
                $tableReference = $from['table'];
            } else {
                $tableSql = $from['table'] . ' ' . $from['alias'];
                $tableReference = $from['alias'];
            }

            $knownAliases[$tableReference] = true;

            $fromClauses[$tableReference] = $tableSql . $this->getSQLForJoins($tableReference, $knownAliases);
        }

        $this->verifyAllAliasesAreKnown($knownAliases);

        return $fromClauses;
    }

    /**
     * @param array $knownAliases
     *
     * @throws QueryException
     */
    private function verifyAllAliasesAreKnown(array $knownAliases)
    {
        foreach ($this->sqlParts['join'] as $fromAlias => $joins) {
            if (!isset($knownAliases[$fromAlias])) {
                throw QueryException::unknownAlias($fromAlias, array_keys($knownAliases));
            }
        }
    }

    /**
     * @return bool
     */
    private function isLimitQuery()
    {
        return $this->maxResults !== null || $this->firstResult !== null;
    }

    /**
     * Converts this instance into an INSERT string in SQL.
     *
     * @return string
     */
    private function getSQLForInsert()
    {
        return 'INSERT INTO ' . $this->sqlParts['from']['table'] .
        ' (' . implode(', ', array_keys($this->sqlParts['values'])) . ')' .
        ' VALUES(' . implode(', ', $this->sqlParts['values']) . ')';
    }

    /**
     * Converts this instance into an UPDATE string in SQL.
     *
     * @return string
     */
    private function getSQLForUpdate()
    {
        $table = $this->sqlParts['from']['table'] . ($this->sqlParts['from']['alias'] ? ' ' . $this->sqlParts['from']['alias'] : '');
        $query = 'UPDATE ' . $table
            . ' SET ' . implode(", ", $this->sqlParts['set'])
            . ($this->sqlParts['where'] !== null ? ' WHERE ' . ((string)$this->sqlParts['where']) : '');

        return $query;
    }

    /**
     * Converts this instance into a DELETE string in SQL.
     *
     * @return string
     */
    private function getSQLForDelete()
    {
        $table = $this->sqlParts['from']['table'] . ($this->sqlParts['from']['alias'] ? ' ' . $this->sqlParts['from']['alias'] : '');
        $query = 'DELETE FROM ' . $table . ($this->sqlParts['where'] !== null ? ' WHERE ' . ((string)$this->sqlParts['where']) : '');

        return $query;
    }

    /**
     * Gets a string representation of this QueryBuilder which corresponds to
     * the final SQL query being constructed.
     *
     * @return string The string representation of this QueryBuilder.
     */
    public function __toString()
    {
        return $this->getSQL();
    }

    /**
     * Creates a new named parameter and bind the value $value to it.
     *
     * This method provides a shortcut for PDOStatement::bindValue
     * when using prepared statements.
     *
     * The parameter $value specifies the value that you want to bind. If
     * $placeholder is not provided bindValue() will automatically create a
     * placeholder for you. An automatic placeholder will be of the name
     * ':dcValue1', ':dcValue2' etc.
     *
     * For more information see {@link http://php.net/pdostatement-bindparam}
     *
     * Example:
     *
     * $value = 2;
     * $q->eq( 'id', $q->bindValue( $value ) );
     * $stmt = $q->executeQuery(); // executed with 'id = 2'
     *
     *
     * @license New BSD License
     * @link http://www.zetacomponents.org
     *
     * @param mixed $value
     * @param mixed $type
     * @param string $placeHolder The name to bind with. The string must start with a colon ':'.
     *
     * @return string the placeholder name used.
     */
    public function createNamedParameter($value, $type = \PDO::PARAM_STR, $placeHolder = null)
    {
        if ($placeHolder === null) {
            $this->boundCounter++;
            $placeHolder = ":dcValue" . $this->boundCounter;
        }
        $this->setParameter(substr($placeHolder, 1), $value, $type);

        return $placeHolder;
    }

    /**
     * Creates a new positional parameter and bind the given value to it.
     *
     * Attention: If you are using positional parameters with the query builder you have
     * to be very careful to bind all parameters in the order they appear in the SQL
     * statement , otherwise they get bound in the wrong order which can lead to serious
     * bugs in your code.
     *
     * Example:
     *
     *  $qb = $conn->createQueryBuilder();
     *  $qb->select('u.*')
     *     ->from('users', 'u')
     *     ->where('u.username = ' . $qb->createPositionalParameter('Foo', PDO::PARAM_STR))
     *     ->orWhere('u.username = ' . $qb->createPositionalParameter('Bar', PDO::PARAM_STR))
     *
     *
     * @param mixed $value
     * @param integer $type
     *
     * @return string
     */
    public function createPositionalParameter($value, $type = \PDO::PARAM_STR)
    {
        $this->boundCounter++;
        $this->setParameter($this->boundCounter, $value, $type);

        return "?";
    }

    /**
     * @param string $fromAlias
     * @param array $knownAliases
     *
     * @return string
     */
    private function getSQLForJoins($fromAlias, array &$knownAliases)
    {
        $sql = '';

        if (isset($this->sqlParts['join'][$fromAlias])) {
            foreach ($this->sqlParts['join'][$fromAlias] as $join) {
                if (array_key_exists($join['joinAlias'], $knownAliases)) {
                    throw QueryException::nonUniqueAlias($join['joinAlias'], array_keys($knownAliases));
                }
                $sql .= ' ' . strtoupper($join['joinType'])
                    . ' JOIN ' . $join['joinTable'] . ' ' . $join['joinAlias']
                    . ' ON ' . ((string)$join['joinCondition']);
                $knownAliases[$join['joinAlias']] = true;
            }

            foreach ($this->sqlParts['join'][$fromAlias] as $join) {
                $sql .= $this->getSQLForJoins($join['joinAlias'], $knownAliases);
            }
        }

        return $sql;
    }

    /**
     * Deep clone of all expression objects in the SQL parts.
     *
     * @return void
     */
    public function __clone()
    {
        foreach ($this->sqlParts as $part => $elements) {
            if (is_array($this->sqlParts[$part])) {
                foreach ($this->sqlParts[$part] as $idx => $element) {
                    if (is_object($element)) {
                        $this->sqlParts[$part][$idx] = clone $element;
                    }
                }
            } elseif (is_object($elements)) {
                $this->sqlParts[$part] = clone $elements;
            }
        }

        foreach ($this->params as $name => $param) {
            if (is_object($param)) {
                $this->params[$name] = clone $param;
            }
        }
    }
}


<?php

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

namespace Valkyrja\Logger\Providers;

use Monolog\Handler\StreamHandler;
use Monolog\Logger as Monolog;
use Psr\Log\LoggerInterface;
use Valkyrja\Application;
use Valkyrja\Logger\Logger;
use Valkyrja\Logger\LogLevel;
use Valkyrja\Logger\MonologLogger;
use Valkyrja\Support\Providers\Provider;

/**
 * Class LoggerServiceProvider.
 *
 * @author Melech Mizrachi
 */
class LoggerServiceProvider extends Provider
{
    /**
     * What services are provided.
     *
     * @var array
     */
    public static $provides = [
        LoggerInterface::class,
        Logger::class,
    ];

    /**
     * The items provided by this provider.
     *
     * @return array
     */
    public static function provides(): array
    {
        return static::$provides;
    }

    /**
     * Publish the provider.
     *
     * @param Application $app The application
     *
     * @throws \Exception
     *
     * @return void
     */
    public static function publish(Application $app): void
    {
        static::bindLoggerInterface($app);
        static::bindLogger($app);
    }

    /**
     * Bind the logger interface.
     *
     * @param Application $app The application
     *
     * @throws \Exception
     *
     * @return void
     */
    protected static function bindLoggerInterface(Application $app): void
    {
        $handler = new StreamHandler(
            $app->config()['logger']['filePath'],
            LogLevel::DEBUG
        );

        $app->container()->singleton(
            LoggerInterface::class,
            new Monolog(
                $app->config()['logger']['name'],
                [
                    $handler,
                ]
            )
        );
    }

    /**
     * Bind the logger.
     *
     * @param Application $app The application
     *
     * @return void
     */
    protected static function bindLogger(Application $app): void
    {
        $app->container()->singleton(
            Logger::class,
            new MonologLogger(
                $app->container()->getSingleton(LoggerInterface::class)
            )
        );
    }
}