<?php

namespace Reaction\Helpers;

use Reaction\Exceptions\ErrorException;
use Reaction\Exceptions\InvalidArgumentException;
use Reaction\Exceptions\InvalidConfigException;

/**
 * File system helper.
 *
 * Borrowed from yii2
 */
class FileHelper
{
    const PATTERN_NODIR = 1;
    const PATTERN_ENDSWITH = 4;
    const PATTERN_MUSTBEDIR = 8;
    const PATTERN_NEGATIVE = 16;
    const PATTERN_CASE_INSENSITIVE = 32;

    /**
     * @var string the path (or alias) of a PHP file containing MIME type information.
     */
    public static $mimeMagicFile = '@reaction/Helpers/mimeTypes.php';
    /**
     * @var string the path (or alias) of a PHP file containing MIME aliases.
     */
    public static $mimeAliasesFile = '@reaction/Helpers/mimeAliases.php';

    /**
     * Normalizes a file/directory path.
     *
     * The normalization does the following work:
     *
     * - Convert all directory separators into `DIRECTORY_SEPARATOR` (e.g. "\a/b\c" becomes "/a/b/c")
     * - Remove trailing directory separators (e.g. "/a/b/c/" becomes "/a/b/c")
     * - Turn multiple consecutive slashes into a single one (e.g. "/a///b/c" becomes "/a/b/c")
     * - Remove ".." and "." based on their meanings (e.g. "/a/./b/../c" becomes "/a/c")
     *
     * @param string $path the file/directory path to be normalized
     * @param string $ds the directory separator to be used in the normalized result. Defaults to `DIRECTORY_SEPARATOR`.
     * @return string the normalized file/directory path
     */
    public static function normalizePath($path, $ds = DIRECTORY_SEPARATOR)
    {
        $path = rtrim(strtr($path, '/\\', $ds . $ds), $ds);
        if (strpos($ds . $path, "{$ds}.") === false && strpos($path, "{$ds}{$ds}") === false) {
            return $path;
        }
        // the path may contain ".", ".." or double slashes, need to clean them up
        if (strpos($path, "{$ds}{$ds}") === 0 && $ds == '\\') {
            $parts = [$ds];
        } else {
            $parts = [];
        }
        foreach (explode($ds, $path) as $part) {
            if ($part === '..' && !empty($parts) && end($parts) !== '..') {
                array_pop($parts);
            } elseif ($part === '.' || $part === '' && !empty($parts)) {
                continue;
            } else {
                $parts[] = $part;
            }
        }
        $path = implode($ds, $parts);
        return $path === '' ? '.' : $path;
    }

    /**
     * Returns the localized version of a specified file.
     *
     * The searching is based on the specified language code. In particular,
     * a file with the same name will be looked for under the subdirectory
     * whose name is the same as the language code. For example, given the file "path/to/view.php"
     * and language code "zh-CN", the localized file will be looked for as
     * "path/to/zh-CN/view.php". If the file is not found, it will try a fallback with just a language code that is
     * "zh" i.e. "path/to/zh/view.php". If it is not found as well the original file will be returned.
     *
     * If the target and the source language codes are the same,
     * the original file will be returned.
     *
     * @param string $file the original file
     * @param string $language the target language that the file should be localized to.
     * If not set, the value of [[\yii\base\Application::language]] will be used.
     * @param string $sourceLanguage the language that the original file is in.
     * If not set, the value of [[\yii\base\Application::sourceLanguage]] will be used.
     * @return string the matching localized file, or the original file if the localized version is not found.
     * If the target and the source language codes are the same, the original file will be returned.
     */
    public static function localize($file, $language = null, $sourceLanguage = null)
    {
        if ($language === null) {
            $language = \Reaction::$app->language;
        }
        if ($sourceLanguage === null) {
            $sourceLanguage = \Reaction::$app->sourceLanguage;
        }
        if ($language === $sourceLanguage) {
            return $file;
        }
        $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
        if (is_file($desiredFile)) {
            return $desiredFile;
        }

        $language = substr($language, 0, 2);
        if ($language === $sourceLanguage) {
            return $file;
        }
        $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);

        return is_file($desiredFile) ? $desiredFile : $file;
    }

    /**
     * Determines the MIME type of the specified file.
     * This method will first try to determine the MIME type based on
     * [finfo_open](http://php.net/manual/en/function.finfo-open.php). If the `fileinfo` extension is not installed,
     * it will fall back to [[getMimeTypeByExtension()]] when `$checkExtension` is true.
     * @param string $file the file name.
     * @param string $magicFile name of the optional magic database file (or alias), usually something like `/path/to/magic.mime`.
     * This will be passed as the second parameter to [finfo_open()](http://php.net/manual/en/function.finfo-open.php)
     * when the `fileinfo` extension is installed. If the MIME type is being determined based via [[getMimeTypeByExtension()]]
     * and this is null, it will use the file specified by [[mimeMagicFile]].
     * @param bool $checkExtension whether to use the file extension to determine the MIME type in case
     * `finfo_open()` cannot determine it.
     * @return string the MIME type (e.g. `text/plain`). Null is returned if the MIME type cannot be determined.
     * @throws InvalidConfigException when the `fileinfo` PHP extension is not installed and `$checkExtension` is `false`.
     */
    public static function getMimeType($file, $magicFile = null, $checkExtension = true)
    {
        if ($magicFile !== null) {
            $magicFile = \Reaction::$app->getAlias($magicFile);
        }
        if (!extension_loaded('fileinfo')) {
            if ($checkExtension) {
                return static::getMimeTypeByExtension($file, $magicFile);
            }

            throw new InvalidConfigException('The fileinfo PHP extension is not installed.');
        }
        $info = finfo_open(FILEINFO_MIME_TYPE, $magicFile);

        if ($info) {
            $result = finfo_file($info, $file);
            finfo_close($info);

            if ($result !== false) {
                return $result;
            }
        }

        return $checkExtension ? static::getMimeTypeByExtension($file, $magicFile) : null;
    }

    /**
     * Determines the MIME type based on the extension name of the specified file.
     * This method will use a local map between extension names and MIME types.
     * @param string $file the file name.
     * @param string $magicFile the path (or alias) of the file that contains all available MIME type information.
     * If this is not set, the file specified by [[mimeMagicFile]] will be used.
     * @return string|null the MIME type. Null is returned if the MIME type cannot be determined.
     */
    public static function getMimeTypeByExtension($file, $magicFile = null)
    {
        $mimeTypes = static::loadMimeTypes($magicFile);

        if (($ext = pathinfo($file, PATHINFO_EXTENSION)) !== '') {
            $ext = strtolower($ext);
            if (isset($mimeTypes[$ext])) {
                return $mimeTypes[$ext];
            }
        }

        return null;
    }

    /**
     * Determines the extensions by given MIME type.
     * This method will use a local map between extension names and MIME types.
     * @param string $mimeType file MIME type.
     * @param string $magicFile the path (or alias) of the file that contains all available MIME type information.
     * If this is not set, the file specified by [[mimeMagicFile]] will be used.
     * @return array the extensions corresponding to the specified MIME type
     */
    public static function getExtensionsByMimeType($mimeType, $magicFile = null)
    {
        $aliases = static::loadMimeAliases(static::$mimeAliasesFile);
        if (isset($aliases[$mimeType])) {
            $mimeType = $aliases[$mimeType];
        }

        $mimeTypes = static::loadMimeTypes($magicFile);
        return array_keys($mimeTypes, mb_strtolower($mimeType, 'UTF-8'), true);
    }

    private static $_mimeTypes = [];

    /**
     * Loads MIME types from the specified file.
     * @param string $magicFile the path (or alias) of the file that contains all available MIME type information.
     * If this is not set, the file specified by [[mimeMagicFile]] will be used.
     * @return array the mapping from file extensions to MIME types
     */
    protected static function loadMimeTypes($magicFile)
    {
        if ($magicFile === null) {
            $magicFile = static::$mimeMagicFile;
        }
        $magicFile = \Reaction::$app->getAlias($magicFile);
        if (!isset(self::$_mimeTypes[$magicFile])) {
            self::$_mimeTypes[$magicFile] = require $magicFile;
        }

        return self::$_mimeTypes[$magicFile];
    }

    private static $_mimeAliases = [];

    /**
     * Loads MIME aliases from the specified file.
     * @param string $aliasesFile the path (or alias) of the file that contains MIME type aliases.
     * If this is not set, the file specified by [[mimeAliasesFile]] will be used.
     * @return array the mapping from file extensions to MIME types
     */
    protected static function loadMimeAliases($aliasesFile)
    {
        if ($aliasesFile === null) {
            $aliasesFile = static::$mimeAliasesFile;
        }
        $aliasesFile = \Reaction::$app->getAlias($aliasesFile);
        if (!isset(self::$_mimeAliases[$aliasesFile])) {
            self::$_mimeAliases[$aliasesFile] = require $aliasesFile;
        }

        return self::$_mimeAliases[$aliasesFile];
    }

    /**
     * Copies a whole directory as another one.
     * The files and sub-directories will also be copied over.
     * @param string $src the source directory
     * @param string $dst the destination directory
     * @param array $options options for directory copy. Valid options are:
     *
     * - dirMode: integer, the permission to be set for newly copied directories. Defaults to 0775.
     * - fileMode:  integer, the permission to be set for newly copied files. Defaults to the current environment setting.
     * - filter: callback, a PHP callback that is called for each directory or file.
     *   The signature of the callback should be: `function ($path)`, where `$path` refers the full path to be filtered.
     *   The callback can return one of the following values:
     *
     *   * true: the directory or file will be copied (the "only" and "except" options will be ignored)
     *   * false: the directory or file will NOT be copied (the "only" and "except" options will be ignored)
     *   * null: the "only" and "except" options will determine whether the directory or file should be copied
     *
     * - only: array, list of patterns that the file paths should match if they want to be copied.
     *   A path matches a pattern if it contains the pattern string at its end.
     *   For example, '.php' matches all file paths ending with '.php'.
     *   Note, the '/' characters in a pattern matches both '/' and '\' in the paths.
     *   If a file path matches a pattern in both "only" and "except", it will NOT be copied.
     * - except: array, list of patterns that the files or directories should match if they want to be excluded from being copied.
     *   A path matches a pattern if it contains the pattern string at its end.
     *   Patterns ending with '/' apply to directory paths only, and patterns not ending with '/'
     *   apply to file paths only. For example, '/a/b' matches all file paths ending with '/a/b';
     *   and '.svn/' matches directory paths ending with '.svn'. Note, the '/' characters in a pattern matches
     *   both '/' and '\' in the paths.
     * - caseSensitive: boolean, whether patterns specified at "only" or "except" should be case sensitive. Defaults to true.
     * - recursive: boolean, whether the files under the subdirectories should also be copied. Defaults to true.
     * - beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file.
     *   If the callback returns false, the copy operation for the sub-directory or file will be cancelled.
     *   The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or
     *   file to be copied from, while `$to` is the copy target.
     * - afterCopy: callback, a PHP callback that is called after each sub-directory or file is successfully copied.
     *   The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or
     *   file copied from, while `$to` is the copy target.
     * - copyEmptyDirectories: boolean, whether to copy empty directories. Set this to false to avoid creating directories
     *   that do not contain files. This affects directories that do not contain files initially as well as directories that
     *   do not contain files at the target destination because files have been filtered via `only` or `except`.
     *   Defaults to true. This option is available since version 2.0.12. Before 2.0.12 empty directories are always copied.
     * @throws InvalidArgumentException if unable to open directory
     */
    public static function copyDirectory($src, $dst, $options = [])
    {
        $src = static::normalizePath($src);
        $dst = static::normalizePath($dst);

        if ($src === $dst || strpos($dst, $src . DIRECTORY_SEPARATOR) === 0) {
            throw new InvalidArgumentException('Trying to copy a directory to itself or a subdirectory.');
        }
        $dstExists = is_dir($dst);
        if (!$dstExists && (!isset($options['copyEmptyDirectories']) || $options['copyEmptyDirectories'])) {
            static::createDirectory($dst, isset($options['dirMode']) ? $options['dirMode'] : 0775, true);
            $dstExists = true;
        }

        $handle = opendir($src);
        if ($handle === false) {
            throw new InvalidArgumentException("Unable to open directory: $src");
        }
        if (!isset($options['basePath'])) {
            // this should be done only once
            $options['basePath'] = realpath($src);
            $options = static::normalizeOptions($options);
        }
        while (($file = readdir($handle)) !== false) {
            if ($file === '.' || $file === '..') {
                continue;
            }
            $from = $src . DIRECTORY_SEPARATOR . $file;
            $to = $dst . DIRECTORY_SEPARATOR . $file;
            if (static::filterPath($from, $options)) {
                if (isset($options['beforeCopy']) && !call_user_func($options['beforeCopy'], $from, $to)) {
                    continue;
                }
                if (is_file($from)) {
                    if (!$dstExists) {
                        // delay creation of destination directory until the first file is copied to avoid creating empty directories
                        static::createDirectory($dst, isset($options['dirMode']) ? $options['dirMode'] : 0775, true);
                        $dstExists = true;
                    }
                    copy($from, $to);
                    if (isset($options['fileMode'])) {
                        @chmod($to, $options['fileMode']);
                    }
                } else {
                    // recursive copy, defaults to true
                    if (!isset($options['recursive']) || $options['recursive']) {
                        static::copyDirectory($from, $to, $options);
                    }
                }
                if (isset($options['afterCopy'])) {
                    call_user_func($options['afterCopy'], $from, $to);
                }
            }
        }
        closedir($handle);
    }

    /**
     * Removes a directory (and all its content) recursively.
     *
     * @param string $dir the directory to be deleted recursively.
     * @param array $options options for directory remove. Valid options are:
     *
     * - traverseSymlinks: boolean, whether symlinks to the directories should be traversed too.
     *   Defaults to `false`, meaning the content of the symlinked directory would not be deleted.
     *   Only symlink would be removed in that default case.
     *
     * @throws ErrorException in case of failure
     */
    public static function removeDirectory($dir, $options = [])
    {
        if (!is_dir($dir)) {
            return;
        }
        if (!empty($options['traverseSymlinks']) || !is_link($dir)) {
            if (!($handle = opendir($dir))) {
                return;
            }
            while (($file = readdir($handle)) !== false) {
                if ($file === '.' || $file === '..') {
                    continue;
                }
                $path = $dir . DIRECTORY_SEPARATOR . $file;
                if (is_dir($path)) {
                    static::removeDirectory($path, $options);
                } else {
                    static::unlink($path);
                }
            }
            closedir($handle);
        }
        if (is_link($dir)) {
            static::unlink($dir);
        } else {
            rmdir($dir);
        }
    }

    /**
     * Removes a file or symlink in a cross-platform way
     *
     * @param string $path
     * @return bool
     */
    public static function unlink($path)
    {
        $isWindows = DIRECTORY_SEPARATOR === '\\';

        if (!$isWindows) {
            return unlink($path);
        }

        if (is_link($path) && is_dir($path)) {
            return rmdir($path);
        }

        try {
            return unlink($path);
        } catch (ErrorException $e) {
            // last resort measure for Windows
            $lines = [];
            exec('DEL /F/Q ' . escapeshellarg($path), $lines, $deleteError);
            return $deleteError !== 0;
        }
    }

    /**
     * Returns the files found under the specified directory and subdirectories.
     * @param string $dir the directory under which the files will be looked for.
     * @param array $options options for file searching. Valid options are:
     *
     * - `filter`: callback, a PHP callback that is called for each directory or file.
     *   The signature of the callback should be: `function ($path)`, where `$path` refers the full path to be filtered.
     *   The callback can return one of the following values:
     *
     *   * `true`: the directory or file will be returned (the `only` and `except` options will be ignored)
     *   * `false`: the directory or file will NOT be returned (the `only` and `except` options will be ignored)
     *   * `null`: the `only` and `except` options will determine whether the directory or file should be returned
     *
     * - `except`: array, list of patterns excluding from the results matching file or directory paths.
     *   Patterns ending with slash ('/') apply to directory paths only, and patterns not ending with '/'
     *   apply to file paths only. For example, '/a/b' matches all file paths ending with '/a/b';
     *   and `.svn/` matches directory paths ending with `.svn`.
     *   If the pattern does not contain a slash (`/`), it is treated as a shell glob pattern
     *   and checked for a match against the pathname relative to `$dir`.
     *   Otherwise, the pattern is treated as a shell glob suitable for consumption by `fnmatch(3)`
     *   with the `FNM_PATHNAME` flag: wildcards in the pattern will not match a `/` in the pathname.
     *   For example, `views/*.php` matches `views/index.php` but not `views/controller/index.php`.
     *   A leading slash matches the beginning of the pathname. For example, `/*.php` matches `index.php` but not `views/start/index.php`.
     *   An optional prefix `!` which negates the pattern; any matching file excluded by a previous pattern will become included again.
     *   If a negated pattern matches, this will override lower precedence patterns sources. Put a backslash (`\`) in front of the first `!`
     *   for patterns that begin with a literal `!`, for example, `\!important!.txt`.
     *   Note, the '/' characters in a pattern matches both '/' and '\' in the paths.
     * - `only`: array, list of patterns that the file paths should match if they are to be returned. Directory paths
     *   are not checked against them. Same pattern matching rules as in the `except` option are used.
     *   If a file path matches a pattern in both `only` and `except`, it will NOT be returned.
     * - `caseSensitive`: boolean, whether patterns specified at `only` or `except` should be case sensitive. Defaults to `true`.
     * - `recursive`: boolean, whether the files under the subdirectories should also be looked for. Defaults to `true`.
     * @return array files found under the directory, in no particular order. Ordering depends on the files system used.
     * @throws InvalidArgumentException if the dir is invalid.
     */
    public static function findFiles($dir, $options = [])
    {
        $dir = self::clearDir($dir);
        $options = self::setBasePath($dir, $options);
        $list = [];
        $handle = self::openDir($dir);
        while (($file = readdir($handle)) !== false) {
            if ($file === '.' || $file === '..') {
                continue;
            }
            $path = $dir . DIRECTORY_SEPARATOR . $file;
            if (static::filterPath($path, $options)) {
                if (is_file($path)) {
                    $list[] = $path;
                } elseif (is_dir($path) && (!isset($options['recursive']) || $options['recursive'])) {
                    $list = array_merge($list, static::findFiles($path, $options));
                }
            }
        }
        closedir($handle);

        return $list;
    }

    /**
     * Returns the directories found under the specified directory and subdirectories.
     * @param string $dir the directory under which the files will be looked for.
     * @param array $options options for directory searching. Valid options are:
     *
     * - `filter`: callback, a PHP callback that is called for each directory or file.
     *   The signature of the callback should be: `function ($path)`, where `$path` refers the full path to be filtered.
     *   The callback can return one of the following values:
     *
     *   * `true`: the directory will be returned
     *   * `false`: the directory will NOT be returned
     *
     * - `recursive`: boolean, whether the files under the subdirectories should also be looked for. Defaults to `true`.
     * @return array directories found under the directory, in no particular order. Ordering depends on the files system used.
     * @throws InvalidArgumentException if the dir is invalid.
     */
    public static function findDirectories($dir, $options = [])
    {
        $dir = self::clearDir($dir);
        $options = self::setBasePath($dir, $options);
        $list = [];
        $handle = self::openDir($dir);
        while (($file = readdir($handle)) !== false) {
            if ($file === '.' || $file === '..') {
                continue;
            }
            $path = $dir . DIRECTORY_SEPARATOR . $file;
            if (is_dir($path) && static::filterPath($path, $options)) {
                $list[] = $path;
                if (!isset($options['recursive']) || $options['recursive']) {
                    $list = array_merge($list, static::findDirectories($path, $options));
                }
            }
        }
        closedir($handle);

        return $list;
    }

    /**
     * Set basePath in options array
     * @param string $dir
     * @param array  $options
     * @return array
     */
    private static function setBasePath($dir, $options)
    {
        if (!isset($options['basePath'])) {
            // this should be done only once
            $options['basePath'] = realpath($dir);
            $options = static::normalizeOptions($options);
        }

        return $options;
    }

    /**
     * @param string $dir
     * @return bool|resource
     */
    private static function openDir($dir)
    {
        $handle = opendir($dir);
        if ($handle === false) {
            throw new InvalidArgumentException("Unable to open directory: $dir");
        }
        return $handle;
    }

    /**
     * @param string $dir
     * @return string
     */
    private static function clearDir($dir)
    {
        if (!is_dir($dir)) {
            throw new InvalidArgumentException("The dir argument must be a directory: $dir");
        }
        return rtrim($dir, DIRECTORY_SEPARATOR);
    }

    /**
     * Checks if the given file path satisfies the filtering options.
     * @param string $path the path of the file or directory to be checked
     * @param array $options the filtering options. See [[findFiles()]] for explanations of
     * the supported options.
     * @return bool whether the file or directory satisfies the filtering options.
     */
    public static function filterPath($path, $options)
    {
        if (isset($options['filter'])) {
            $result = call_user_func($options['filter'], $path);
            if (is_bool($result)) {
                return $result;
            }
        }

        if (empty($options['except']) && empty($options['only'])) {
            return true;
        }

        $path = str_replace('\\', '/', $path);

        if (!empty($options['except'])) {
            if (($except = self::lastExcludeMatchingFromList($options['basePath'], $path, $options['except'])) !== null) {
                return $except['flags'] & self::PATTERN_NEGATIVE;
            }
        }

        if (!empty($options['only']) && !is_dir($path)) {
            if (($except = self::lastExcludeMatchingFromList($options['basePath'], $path, $options['only'])) !== null) {
                // don't check PATTERN_NEGATIVE since those entries are not prefixed with !
                return true;
            }

            return false;
        }

        return true;
    }

    /**
     * Creates a new directory.
     *
     * This method is similar to the PHP `mkdir()` function except that
     * it uses `chmod()` to set the permission of the created directory
     * in order to avoid the impact of the `umask` setting.
     *
     * @param string $path path of the directory to be created.
     * @param int $mode the permission to be set for the created directory.
     * @param bool $recursive whether to create parent directories if they do not exist.
     * @return bool whether the directory is created successfully
     * @throws \Reaction\Exceptions\Exception if the directory could not be created (i.e. php error due to parallel changes)
     */
    public static function createDirectory($path, $mode = 0775, $recursive = true)
    {
        if (is_dir($path)) {
            return true;
        }
        $parentDir = dirname($path);
        // recurse if parent dir does not exist and we are not at the root of the file system.
        if ($recursive && !is_dir($parentDir) && $parentDir !== $path) {
            static::createDirectory($parentDir, $mode, true);
        }
        try {
            if (!mkdir($path, $mode)) {
                return false;
            }
        } catch (\Exception $e) {
            if (!is_dir($path)) {// https://github.com/yiisoft/yii2/issues/9288
                throw new \Reaction\Exceptions\Exception("Failed to create directory \"$path\": " . $e->getMessage(), $e->getCode(), $e);
            }
        }
        try {
            return chmod($path, $mode);
        } catch (\Exception $e) {
            throw new \Reaction\Exceptions\Exception("Failed to change permissions for directory \"$path\": " . $e->getMessage(), $e->getCode(), $e);
        }
    }

    /** @var array Bytes map for permissions conversion */
    protected static $_permissionsByteMap = [
        0x0100 => 'r',
        0x0080 => 'w',
        0x0040 => 'x',
        0x0020 => 'r',
        0x0010 => 'w',
        0x0008 => 'x',
        0x0004 => 'r',
        0x0002 => 'w',
        0x0001 => 'x',
    ];

    /**
     * Convert octal permissions to string
     * @param int $modeOctal Octal mode (0755). Do not omit zero, must be octal, not decimal!
     * @return string String permissions representation (rwxr-xr-x)
     */
    public static function permissionsAsString($modeOctal) {
        $modeStr = '';
        foreach (static::$_permissionsByteMap as $bytes => $flag) {
            $modeStr .= (($modeOctal & $bytes) ? $flag : '-');
        }
        return $modeStr;
    }

    /**
     * Convert string representation of permissions to octal
     * @param string $modeStr String permissions (rwxr-xr-x)
     * @return int Octal permissions representation
     */
    public static function permissionsAsOctal($modeStr) {
        $modeStr = str_pad($modeStr, 9, '-', STR_PAD_RIGHT);
        $modeOctal = 0x0;
        $num = 0;
        foreach (static::$_permissionsByteMap as $bytes => $flag) {
            $modeOctal += (($modeStr[$num] === $flag) ? $bytes : 0x0);
            $num++;
        }
        return $modeOctal;
    }

    /**
     * Performs a simple comparison of file or directory names.
     *
     * Based on match_basename() from dir.c of git 1.8.5.3 sources.
     *
     * @param string $baseName file or directory name to compare with the pattern
     * @param string $pattern the pattern that $baseName will be compared against
     * @param int|bool $firstWildcard location of first wildcard character in the $pattern
     * @param int $flags pattern flags
     * @return bool whether the name matches against pattern
     */
    private static function matchBasename($baseName, $pattern, $firstWildcard, $flags)
    {
        if ($firstWildcard === false) {
            if ($pattern === $baseName) {
                return true;
            }
        } elseif ($flags & self::PATTERN_ENDSWITH) {
            /* "*literal" matching against "fooliteral" */
            $n = StringHelper::byteLength($pattern);
            if (StringHelper::byteSubstr($pattern, 1, $n) === StringHelper::byteSubstr($baseName, -$n, $n)) {
                return true;
            }
        }

        $matchOptions = [];
        if ($flags & self::PATTERN_CASE_INSENSITIVE) {
            $matchOptions['caseSensitive'] = false;
        }

        return StringHelper::matchWildcard($pattern, $baseName, $matchOptions);
    }

    /**
     * Compares a path part against a pattern with optional wildcards.
     *
     * Based on match_pathname() from dir.c of git 1.8.5.3 sources.
     *
     * @param string $path full path to compare
     * @param string $basePath base of path that will not be compared
     * @param string $pattern the pattern that path part will be compared against
     * @param int|bool $firstWildcard location of first wildcard character in the $pattern
     * @param int $flags pattern flags
     * @return bool whether the path part matches against pattern
     */
    private static function matchPathname($path, $basePath, $pattern, $firstWildcard, $flags)
    {
        // match with FNM_PATHNAME; the pattern has base implicitly in front of it.
        if (isset($pattern[0]) && $pattern[0] === '/') {
            $pattern = StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern));
            if ($firstWildcard !== false && $firstWildcard !== 0) {
                $firstWildcard--;
            }
        }

        $namelen = StringHelper::byteLength($path) - (empty($basePath) ? 0 : StringHelper::byteLength($basePath) + 1);
        $name = StringHelper::byteSubstr($path, -$namelen, $namelen);

        if ($firstWildcard !== 0) {
            if ($firstWildcard === false) {
                $firstWildcard = StringHelper::byteLength($pattern);
            }
            // if the non-wildcard part is longer than the remaining pathname, surely it cannot match.
            if ($firstWildcard > $namelen) {
                return false;
            }

            if (strncmp($pattern, $name, $firstWildcard)) {
                return false;
            }
            $pattern = StringHelper::byteSubstr($pattern, $firstWildcard, StringHelper::byteLength($pattern));
            $name = StringHelper::byteSubstr($name, $firstWildcard, $namelen);

            // If the whole pattern did not have a wildcard, then our prefix match is all we need; we do not need to call fnmatch at all.
            if (empty($pattern) && empty($name)) {
                return true;
            }
        }

        $matchOptions = [
            'filePath' => true
        ];
        if ($flags & self::PATTERN_CASE_INSENSITIVE) {
            $matchOptions['caseSensitive'] = false;
        }

        return StringHelper::matchWildcard($pattern, $name, $matchOptions);
    }

    /**
     * Scan the given exclude list in reverse to see whether pathname
     * should be ignored.  The first match (i.e. the last on the list), if
     * any, determines the fate.  Returns the element which
     * matched, or null for undecided.
     *
     * Based on last_exclude_matching_from_list() from dir.c of git 1.8.5.3 sources.
     *
     * @param string $basePath
     * @param string $path
     * @param array $excludes list of patterns to match $path against
     * @return array|null null or one of $excludes item as an array with keys: 'pattern', 'flags'
     * @throws InvalidArgumentException if any of the exclude patterns is not a string or an array with keys: pattern, flags, firstWildcard.
     */
    private static function lastExcludeMatchingFromList($basePath, $path, $excludes)
    {
        foreach (array_reverse($excludes) as $exclude) {
            if (is_string($exclude)) {
                $exclude = self::parseExcludePattern($exclude, false);
            }
            if (!isset($exclude['pattern']) || !isset($exclude['flags']) || !isset($exclude['firstWildcard'])) {
                throw new InvalidArgumentException('If exclude/include pattern is an array it must contain the pattern, flags and firstWildcard keys.');
            }
            if ($exclude['flags'] & self::PATTERN_MUSTBEDIR && !is_dir($path)) {
                continue;
            }

            if ($exclude['flags'] & self::PATTERN_NODIR) {
                if (self::matchBasename(basename($path), $exclude['pattern'], $exclude['firstWildcard'], $exclude['flags'])) {
                    return $exclude;
                }
                continue;
            }

            if (self::matchPathname($path, $basePath, $exclude['pattern'], $exclude['firstWildcard'], $exclude['flags'])) {
                return $exclude;
            }
        }

        return null;
    }

    /**
     * Processes the pattern, stripping special characters like / and ! from the beginning and settings flags instead.
     * @param string $pattern
     * @param bool $caseSensitive
     * @throws InvalidArgumentException
     * @return array with keys: (string) pattern, (int) flags, (int|bool) firstWildcard
     */
    private static function parseExcludePattern($pattern, $caseSensitive)
    {
        if (!is_string($pattern)) {
            throw new InvalidArgumentException('Exclude/include pattern must be a string.');
        }

        $result = [
            'pattern' => $pattern,
            'flags' => 0,
            'firstWildcard' => false,
        ];

        if (!$caseSensitive) {
            $result['flags'] |= self::PATTERN_CASE_INSENSITIVE;
        }

        if (!isset($pattern[0])) {
            return $result;
        }

        if ($pattern[0] === '!') {
            $result['flags'] |= self::PATTERN_NEGATIVE;
            $pattern = StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern));
        }
        if (StringHelper::byteLength($pattern) && StringHelper::byteSubstr($pattern, -1, 1) === '/') {
            $pattern = StringHelper::byteSubstr($pattern, 0, -1);
            $result['flags'] |= self::PATTERN_MUSTBEDIR;
        }
        if (strpos($pattern, '/') === false) {
            $result['flags'] |= self::PATTERN_NODIR;
        }
        $result['firstWildcard'] = self::firstWildcardInPattern($pattern);
        if ($pattern[0] === '*' && self::firstWildcardInPattern(StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern))) === false) {
            $result['flags'] |= self::PATTERN_ENDSWITH;
        }
        $result['pattern'] = $pattern;

        return $result;
    }

    /**
     * Searches for the first wildcard character in the pattern.
     * @param string $pattern the pattern to search in
     * @return int|bool position of first wildcard character or false if not found
     */
    private static function firstWildcardInPattern($pattern)
    {
        $wildcards = ['*', '?', '[', '\\'];
        $wildcardSearch = function ($r, $c) use ($pattern) {
            $p = strpos($pattern, $c);

            return $r === false ? $p : ($p === false ? $r : min($r, $p));
        };

        return array_reduce($wildcards, $wildcardSearch, false);
    }

    /**
     * @param array $options raw options
     * @return array normalized options
     */
    protected static function normalizeOptions(array $options)
    {
        if (!array_key_exists('caseSensitive', $options)) {
            $options['caseSensitive'] = true;
        }
        if (isset($options['except'])) {
            foreach ($options['except'] as $key => $value) {
                if (is_string($value)) {
                    $options['except'][$key] = self::parseExcludePattern($value, $options['caseSensitive']);
                }
            }
        }
        if (isset($options['only'])) {
            foreach ($options['only'] as $key => $value) {
                if (is_string($value)) {
                    $options['only'][$key] = self::parseExcludePattern($value, $options['caseSensitive']);
                }
            }
        }

        return $options;
    }
}


<?php
/**
 * Got_Sniffs_Strings_DoubleQuoteUsageSniff
 *
 * PHP version 5
 *
 * @category PHP
 * @package  CodeSniffer
 * @author   Pierre Rambaud (GoT) <pierre.rambaud86@gmail.com>
 * @license  http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
 * @link     http://pierrerambaud.com
 */

namespace Got\Sniffs\Strings;

use PHP_CodeSniffer_Sniff;
use PHP_CodeSniffer_File;

/**
 * Got_Sniffs_Strings_DoubleQuoteUsageSniff.
 *
 * PHP version 5
 *
 * @category PHP
 * @package  CodeSniffer
 * @author   Pierre Rambaud (GoT) <pierre.rambaud86@gmail.com>
 * @license  http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
 * @link     http://pierrerambaud.com
 */
class DoubleQuoteUsageSniff implements PHP_CodeSniffer_Sniff
{
    /**
     * Returns an array of tokens this test wants to listen for.
     *
     * @return array
     */
    public function register()
    {
        return array(
            T_CONSTANT_ENCAPSED_STRING,
            T_DOUBLE_QUOTED_STRING,
        );

    }

    /**
     * Processes this test, when one of its tokens is encountered.
     *
     * @param PHP_CodeSniffer_File $phpCsFile The file being scanned.
     * @param int                  $stackPtra The position of the current token
     *                                        in the stack passed in $tokens.
     *
     * @return void
     */
    public function process(PHP_CodeSniffer_File $phpCsFile, $stackPtra)
    {
        $tokens = $phpCsFile->getTokens();

        // The use of variables in double quoted strings is not allowed.
        if ($tokens[$stackPtra]['code'] === T_DOUBLE_QUOTED_STRING) {
            $stringTokens = token_get_all('<?php ' . $tokens[$stackPtra]['content']);
            foreach ($stringTokens as $token) {
                if (is_array($token) === true && $token[0] === T_VARIABLE) {
                    return;
                }
            }

            return;
        }

        $workingString = $tokens[$stackPtra]['content'];

        // Check if it's a double quoted string.
        if (strpos($workingString, '"') === false) {
            return;
        }

        // Make sure it's not a part of a string started above.
        // If it is, then we have already checked it.
        if ($workingString[0] !== '"') {
            return;
        }

        // Work through the following tokens, in case this string is stretched
        // over multiple Lines.
        for ($i = ($stackPtra + 1); $i < $phpCsFile->numTokens; $i++) {
            if ($tokens[$i]['type'] !== 'T_CONSTANT_ENCAPSED_STRING') {
                break;
            }

            $workingString .= $tokens[$i]['content'];
        }

        $allowedChars = array(
            '\n',
            '\r',
            '\f',
            '\t',
            '\v',
            '\x',
            '\'',
        );

        foreach ($allowedChars as $testChar) {
            if (strpos($workingString, $testChar) !== false) {
                return;
            }
        }

        $error = 'String ' . $workingString . ' does not require double quotes; use single quotes instead';
        $phpCsFile->addError($error, $stackPtra);
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: Bartosz Gołek
 * Date: 09.11.13
 * Time: 15:30
 *
 * @package    Conpago
 * @subpackage Helpers
 * @author     Bartosz Gołek <bartosz.golek@gmail.com>
 * @copyright  Copyright (c) 2015, Bartosz Gołek
 */

namespace Conpago\Helpers;

use Conpago\File\Contract\IFileSystem;
use Conpago\File\Contract\IPath;
use Conpago\File\Path;
use Conpago\Helpers\Contract\IAppPath;

class AppPath implements IAppPath
{

    protected $cache;

    protected $config;

    protected $root;

    protected $templates;

    protected $source;

    protected $sessions;

    /**
     * @var IFileSystem
     */
    private $fileSystem;

    public function __construct(IFileSystem $fileSystem, $basePath)
    {
        $this->fileSystem = $fileSystem;

        $this->source    = array(
                            $basePath,
                            'src',
                           );
        $this->templates = array(
                            $basePath,
                            'templates',
                           );
        $this->root      = array($basePath);
        $this->config    = array(
                            $basePath,
                            'config',
                           );
        $this->cache     = array(
                            $basePath,
                            'tmp',
                            'cache',
                           );
        $this->sessions  = array(
                            $basePath,
                            'tmp',
                            'sessions',
                           );
    }

    /**
     * @param array $elements
     *
     * @return IPath
     */
    private function getPath(array $elements)
    {
        $path     = implode(DIRECTORY_SEPARATOR, $elements);
        $realPath = $this->fileSystem->realPath($path);
        return new Path($path, $realPath);
    }

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

    /**
     * @return IPath
     */
    public function sessions()
    {
        return $this->getPath($this->sessions);
    }

    /**
     * @return IPath
     */
    public function config()
    {
        return $this->getPath($this->config);
    }

    /**
     * @return IPath
     */
    public function root()
    {
        return $this->getPath($this->root);
    }

    /**
     * @return IPath
     */
    public function templates()
    {
        return $this->getPath($this->templates);
    }

    /**
     * @return IPath
     */
    public function source()
    {
        return $this->getPath($this->source);
    }
}


<?php

namespace Colorium\Orm\SQLite;

use Colorium\Orm;

abstract class SQL extends Orm\SQL
{

    /**
     * Compile CREATE TABLE
     *
     * @param string $table
     * @param array $specs
     * @return bool
     */
    public static function createTable($table, array $specs)
    {
        $sql = 'CREATE TABLE IF NOT EXISTS ' . static::e($table) . ' (';
        foreach($specs as $field => $opts) {
            $sql .= "\n" .  '`' . $field . '` ' . $opts['type'];
            if($opts['primary'] == true) {
                $opts['nullable'] = false;
                $opts['default'] = null;
                $sql .= ' PRIMARY KEY AUTOINCREMENT';
            }
            if(!$opts['nullable']) {
                $sql .= ' NOT NULL';
            }
            if($opts['default']) {
                $sql .= ' DEFAULT ' . $opts['default'];
            }
            $sql .= ',';
        }

        $sql = trim($sql, ',') . "\n" . ');';
        return $sql;
    }

    /**
     * Compile TRUNCATE TABLE
     *
     * @param string $table
     * @return bool
     */
    public static function truncateTable($table)
    {
        return 'DELETE FROM ' . static::e($table);
    }

}


<?php
/**
 * Created by PhpStorm.
 * User: Bartosz Gołek
 * Date: 09.11.13
 * Time: 15:30
 *
 * @package    Conpago
 * @subpackage Core
 * @author     Bartosz Gołek <bartosz.golek@gmail.com>
 * @copyright  Copyright (c) 2015, Bartosz Gołek
 */

namespace Conpago;

use Conpago\Contract\IApp;
use Conpago\DI\IContainer;
use Conpago\DI\IModule;
use Conpago\DI\IContainerBuilder;
use Conpago\File\Contract\IFileSystem;
use Conpago\Helpers\Contract\IAppPath;
use Conpago\Logging\Contract\ILogger;

/**
 * Builds application using container Modules.
 */
class AppBuilder
{

    /**
     * Provider for application base paths.
     *
     * @var IAppPath
     */
    protected $appPath;

    /**
     * Provider for application DI container.
     *
     * @var IContainer
     */
    protected $container;

    /**
     * Name of building context.
     *
     * @var string
     */
    private $contextName;

    /**
     * Provider for file system access.
     *
     * @var IFileSystem
     */
    private $fileSystem;

    /**
     * Container builder provider.
     *
     * @var IContainerBuilder
     */
    private $containerBuilder;

    /**
     * Creates AppBuilder instance.
     *
     * @param IFileSystem       $fileSystem       Provider for file system access.
     * @param IAppPath          $appPath          Provider for application base paths.
     * @param IContainerBuilder $containerBuilder Container builder provider.
     * @param string            $contextName      Name of building context.
     */
    public function __construct(
        IFileSystem $fileSystem,
        IAppPath $appPath,
        IContainerBuilder $containerBuilder,
        $contextName
    ) {
        $this->appPath          = $appPath;
        $this->contextName      = $contextName;
        $this->fileSystem       = $fileSystem;
        $this->containerBuilder = $containerBuilder;
    }

    /**
     * Loads all modules contained in app and builds them.
     *
     * @return void
     */
    protected function loadModules()
    {
        $moduleMask = implode(
            DIRECTORY_SEPARATOR,
            array(
             $this->appPath->root()->get(),
             'src',
             $this->contextName.'Module.php',
            )
        );

        foreach ($this->fileSystem->glob($moduleMask) as $filePath) {
            $class = $this->loadModule($filePath);
            $class->build($this->containerBuilder);
        }
    }

    /**
     * Gets built container.
     *
     * @return IContainer IoC container.
     */
    protected function getContainer()
    {
        if (!$this->container) {
            $this->container = $this->containerBuilder->build();
        }

        return $this->container;
    }

    /**
     * Builds application.
     *
     * @return void
     */
    public function buildApp()
    {
        $this->registerFileSystem();
        $this->registerAppPath();
        $this->loadModules();
    }

    /**
     * Gets logger from application container.
     *
     * @return ILogger The logger implementation.
     */
    public function getLogger()
    {
        return $this->getContainer()->resolve('Conpago\Logging\Contract\ILogger');
    }

    /**
     * Gets application instance.
     *
     * @return IApp The application instance.
     */
    public function getApp()
    {
        return $this->getContainer()->resolve('Conpago\Contract\IApp');
    }

    /**
     * Registers file system access provider. It is required during application build for loading modules.
     *
     * @return void
     */
    private function registerFileSystem()
    {
        $this->containerBuilder->registerInstance($this->fileSystem)->asA('Conpago\File\Contract\IFileSystem');
    }

    /**
     * Registers app paths provider. It is required during application build for loading modules.
     *
     * @return void
     */
    private function registerAppPath()
    {
        $this->containerBuilder->registerInstance($this->appPath)->asA('Conpago\Helpers\Contract\IAppPath');
    }

    /**
     * Loads module class.
     *
     * @param string $filePath Path to module file.
     *
     * @return IModule Loaded module class instance.
     */
    protected function loadModule($filePath)
    {
        return $this->fileSystem->loadClass($filePath);
    }
}


<?php

namespace Flowcode\DashboardBundle\Service;

use Amulen\SettingsBundle\Model\SettingRepository;
use Doctrine\ORM\EntityRepository;
use Flowcode\DashboardBundle\Entity\Setting;
use Flowcode\DashboardBundle\Event\CollectSettingOptionsEvent;
use Symfony\Component\EventDispatcher\EventDispatcher;

/**
 * User: juanma
 * Date: 5/28/16
 * Time: 6:03 PM
 */
class SettingService implements SettingRepository
{

    private $settingRepository;

    /**
     * @var EventDispatcher
     */
    private $dispatcher;

    /**
     * SettingService constructor.
     * @param $settingRepository
     */
    public function __construct(EntityRepository $settingRepository, $dispatcher)
    {
        $this->settingRepository = $settingRepository;
        $this->dispatcher = $dispatcher;
    }

    public function getValue($settingName)
    {
        $setting = $this->settingRepository->findOneBy(array(
            'name' => $settingName,
        ));
        if ($setting) {
            return $setting->getValue();
        }
        return null;
    }

    /**
     * @return array
     */
    public function getAll()
    {
        $settingOptions = array();

        $collectSettingOptionsEvent = new CollectSettingOptionsEvent();
        $collectSettingOptionsEvent->setSettingOptions($settingOptions);

        $this->dispatcher->dispatch(CollectSettingOptionsEvent::NAME, $collectSettingOptionsEvent);

        return $collectSettingOptionsEvent->getSettingOptions();
    }

    /**
     * Get setting value.
     *
     * @param $key
     * @return null|string
     */
    public function getOneByKey($key)
    {
        /**
         * @var Setting $setting
         */
        $setting = $this->settingRepository->findOneBy(array(
            'name' => $key,
        ));

        return $setting;
    }

    /**
     * Get setting value.
     *
     * @param $key
     * @return null|string
     */
    public function get($key)
    {
        /**
         * @var Setting $setting
         */
        $setting = $this->settingRepository->findOneBy(array(
            'name' => $key,
        ));
        if ($setting) {
            return $setting->getValue();
        }
        return null;
    }

    /**
     * Get setting value.
     *
     * @param $key
     * @return null|string
     */
    public function getByKey($key)
    {
        /**
         * @var Setting $setting
         */
        $settings = $this->settingRepository->findBy(array(
            'name' => $key,
        ));
        $return = array();
        if ($settings) {
            foreach ($settings as $setting) {
                $return[] = strtolower($setting->getValue());
            }
        }
        return $return;
    }

    public function currentVersion()
    {
        return "0.4.2";
    }

}


<?php

namespace Philip\Plugin;

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

/**
 * Adds a "swear jar" to the Philip IRC bot.
 *
 * @author Bill Israel <bill.israel@gmail.com>
 */
class SwearJarPlugin extends BasePlugin
{
    /**
     * Listens to channel messages and lets everyone know who owes what to
     * the "swear jar".
     */
    public function init()
    {
        $swears = array('fu+ck', 'sh+i+t', 'cu+nt', 'co+ck');
        $swear_jar = array();

        // Don't say bad words, kids.
        $re = '/' . implode('|', $swears) . '/i';
        $this->bot->onChannel($re, function(Event $event) use (&$swear_jar) {
            $cost = 0.25;
            $who = $event->getRequest()->getSendingUser();
            if (!isset($swear_jar[$who])) {
                $swear_jar[$who] = 0;
            }

            $price = ($swear_jar[$who] += $cost);
            $event->addResponse(
                Response::msg(
                    $event->getRequest()->getSource(),
                    sprintf("Mind your tongue $who! Now you owe \$%.2f to the swear jar.", $price)
            ));
        });
    }

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


<?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\ORM\QueryBuilder;

use Valkyrja\ORM\Enums\OrderBy;
use Valkyrja\ORM\Enums\Statement;
use Valkyrja\ORM\QueryBuilder;

/**
 * Class QueryBuilder.
 */
class NativeQueryBuilder implements QueryBuilder
{
    /**
     * The type of statement to build.
     *
     * @var string
     */
    protected $type;

    /**
     * The columns for use in a select statement.
     *
     * @var array
     */
    protected $columns = [];

    /**
     * The table upon which the statement executes.
     *
     * @var string
     */
    protected $table;

    /**
     * Where conditions for the query statement.
     *
     * @var array
     */
    protected $where = [];

    /**
     * Values to use for update/insert statements.
     *
     * @var array
     */
    protected $values = [];

    /**
     * Order by conditions for the query statement.
     *
     * @var array
     */
    protected $orderBy = [];

    /**
     * Group by conditions for the query statement.
     *
     * @var array
     */
    protected $groupBy = [];

    /**
     * Limit condition for the query statement.
     *
     * @var int
     */
    protected $limit;

    /**
     * Offset condition for the query statement.
     *
     * @var int
     */
    protected $offset;

    /**
     * The built query.
     *
     * @var string
     */
    protected $query;

    /**
     * Create a SELECT query statement.
     *
     *
     *      $queryBuilder->select();
     *      $queryBuilder->select(
     *          [
     *              'column1',
     *              'column2',
     *              ...
     *          ]
     *      );
     *
     *
     * @param array|null $columns
     *
     * @return static
     */
    public function select(array $columns = null): QueryBuilder
    {
        $this->type = Statement::SELECT;

        if (null !== $columns) {
            $this->columns = $columns;
        } else {
            $this->columns[] = '*';
        }

        return $this;
    }

    /**
     * Create an INSERT query statement.
     *
     *
     *      $queryBuilder->insert();
     *
     *
     * @return static
     */
    public function insert(): QueryBuilder
    {
        $this->type = Statement::INSERT;

        return $this;
    }

    /**
     * Create an UPDATE query statement.
     *
     *
     *      $queryBuilder->update();
     *
     *
     * @return static
     */
    public function update(): QueryBuilder
    {
        $this->type = Statement::UPDATE;

        return $this;
    }

    /**
     * Create an DELETE query statement.
     *
     *
     *      $queryBuilder->delete();
     *
     *
     * @return static
     */
    public function delete(): QueryBuilder
    {
        $this->type = Statement::DELETE;

        return $this;
    }

    /**
     * Set the table on which to perform the query statement.
     *
     *
     *      $queryBuilder
     *          ->select()
     *          ->table('table');
     *
     *      $queryBuilder
     *          ->select()
     *          ->table('table', 't');
     *
     *
     * @param string      $table
     * @param string|null $alias
     *
     * @return static
     */
    public function table(string $table, string $alias = null): QueryBuilder
    {
        $this->table = $table . ($alias !== null ? ' ' . $alias : '');

        return $this;
    }

    /**
     * Add a value for a column to set.
     *
     *
     *      $queryBuilder
     *          ->insert()
     *          ->table('table')
     *          ->set('column', ':column');
     *
     *      $queryBuilder
     *          ->update()
     *          ->table('table')
     *          ->set('column', ':column');
     *
     *
     * @param string $column
     * @param string $value
     *
     * @return static
     */
    public function set(string $column, string $value): QueryBuilder
    {
        $this->values[$column] = $value;

        return $this;
    }

    /**
     * Add a where condition to the query statement.
     * - Each additional use will add an `AND` where condition.
     *
     *
     *      $queryBuilder
     *          ->select()
     *          ->table('table')
     *          ->where('column = :column');
     *
     *      $queryBuilder
     *          ->select()
     *          ->table('table')
     *          ->where('column = :column')
     *          ->where('column2 = :column2');
     *
     *
     * @param string $where
     *
     * @return static
     */
    public function where(string $where): QueryBuilder
    {
        if (empty($this->where)) {
            $this->setWhere($where);

            return $this;
        }

        $this->setWhere($where, Statement::WHERE_AND);

        return $this;
    }

    /**
     * Add an additional `AND` where condition to the query statement.
     *
     *
     *      $queryBuilder
     *          ->select()
     *          ->table('table')
     *          ->where('column = :column')
     *          ->andWhere('column2 = :column2');
     *
     *
     * @param string $where
     *
     * @return static
     */
    public function andWhere(string $where): QueryBuilder
    {
        if (empty($this->where)) {
            return $this->where($where);
        }

        $this->setWhere($where, Statement::WHERE_AND);

        return $this;
    }

    /**
     * Add an additional `OR` where condition to the query statement.
     *
     *
     *      $queryBuilder
     *          ->select()
     *          ->table('table')
     *          ->where('column = :column')
     *          ->andWhere('column2 = :column2');
     *
     *
     * @param string $where
     *
     * @return static
     */
    public function orWhere(string $where): QueryBuilder
    {
        if (empty($this->where)) {
            return $this->where($where);
        }

        $this->setWhere($where, Statement::WHERE_OR);

        return $this;
    }

    /**
     * Add an order by without specifying the order to the query statement.
     *
     *
     *      $queryBuilder
     *          ->select()
     *          ->table('table')
     *          ->where('column = :column')
     *          ->orderBy('column');
     *
     *
     * @param string $column
     *
     * @return static
     */
    public function orderBy(string $column): QueryBuilder
    {
        $this->setOrderBy($column);

        return $this;
    }

    /**
     * Add an order by ascending to the query statement.
     *
     *
     *      $queryBuilder
     *          ->select()
     *          ->table('table')
     *          ->where('column = :column')
     *          ->orderByAsc('column');
     *
     *
     * @param string $column
     *
     * @return static
     */
    public function orderByAsc(string $column): QueryBuilder
    {
        $this->setOrderBy($column, OrderBy::ASC);

        return $this;
    }

    /**
     * Add an order by descending to the query statement.
     *
     *
     *      $queryBuilder
     *          ->select()
     *          ->table('table')
     *          ->where('column = :column')
     *          ->orderByDesc('column');
     *
     *
     * @param string $column
     *
     * @return static
     */
    public function orderByDesc(string $column): QueryBuilder
    {
        $this->setOrderBy($column, OrderBy::DESC);

        return $this;
    }

    /**
     * Add limit to the query statement.
     *
     *
     *      $queryBuilder
     *          ->select()
     *          ->table('table')
     *          ->where('column = :column')
     *          ->limit(1);
     *
     *
     * @param int $limit
     *
     * @return static
     */
    public function limit(int $limit): QueryBuilder
    {
        $this->limit = $limit;

        return $this;
    }

    /**
     * Add offset to the query statement.
     *
     *
     *      $queryBuilder
     *          ->select()
     *          ->table('table')
     *          ->where('column = :column')
     *          ->offset(1);
     *
     *
     * @param int $offset
     *
     * @return static
     */
    public function offset(int $offset): QueryBuilder
    {
        $this->offset = $offset;

        return $this;
    }

    /**
     * Get the built query string.
     *
     * @return string
     */
    public function getQuery(): string
    {
        if (null !== $this->query) {
            return $this->query;
        }

        switch ($this->type) {
            case Statement::SELECT:
                $this->query = $this->getSelectQuery();
                break;
            case Statement::UPDATE:
                $this->query = $this->getUpdateQuery();
                break;
            case Statement::INSERT:
                $this->query = $this->getInsertQuery();
                break;
            case Statement::DELETE:
                $this->query = $this->getDeleteQuery();
                break;
        }

        return $this->query;
    }

    /**
     * Set a where condition.
     *
     * @param string      $where
     * @param string|null $type
     *
     * @return void
     */
    protected function setWhere(string $where, string $type = null): void
    {
        if (null !== $type) {
            $where = $type . ' ' . $where;
        }

        $this->where[] = $where;
    }

    /**
     * Set an order by condition.
     *
     * @param string      $column
     * @param string|null $order
     *
     * @return void
     */
    protected function setOrderBy(string $column, string $order = null): void
    {
        $orderBy = $column;

        if (null !== $order) {
            $orderBy .= ' ' . $order;
        }

        $this->orderBy[] = $orderBy;
    }

    /**
     * Get a SELECT query.
     *
     * @return string
     */
    protected function getSelectQuery(): string
    {
        return $this->type
            . ' ' . implode(', ', $this->columns)
            . ' ' . Statement::FROM
            . ' ' . $this->table
            . ' ' . $this->getWhereQuery()
            . ' ' . $this->getOrderByQuery()
            . ' ' . $this->getLimitQuery()
            . ' ' . $this->getOffsetQuery();
    }

    /**
     * Get an INSERT query.
     *
     * @return string
     */
    protected function getInsertQuery(): string
    {
        return $this->type
            . ' ' . Statement::INTO
            . ' ' . $this->table
            . ' (' . implode(', ', array_keys($this->values)) . ')'
            . ' ' . Statement::VALUE
            . ' (' . implode(', ', $this->values) . ')';
    }

    /**
     * Get an UPDATE query.
     *
     * @return string
     */
    protected function getUpdateQuery(): string
    {
        return $this->type
            . ' ' . $this->table
            . ' ' . $this->getSetQuery()
            . ' ' . $this->getWhereQuery()
            . ' ' . $this->getOrderByQuery()
            . ' ' . $this->getLimitQuery();
    }

    /**
     * Get an DELETE query.
     *
     * @return string
     */
    protected function getDeleteQuery(): string
    {
        return $this->type
            . ' ' . Statement::FROM
            . ' ' . $this->table
            . ' ' . $this->getWhereQuery()
            . ' ' . $this->getOrderByQuery()
            . ' ' . $this->getLimitQuery();
    }

    /**
     * Get the SET part of an INSERT query.
     *
     * @return string
     */
    protected function getSetQuery(): string
    {
        $query = '';

        foreach ($this->values as $column => $value) {
            if (! empty($query)) {
                $query .= ', ';
            }

            $query .= $column . ' = ' . $value;
        }

        return Statement::SET . ' ' . $query;
    }

    /**
     * Get the WHERE part of a query statement.
     *
     * @return string
     */
    protected function getWhereQuery(): string
    {
        if (empty($this->where)) {
            return '';
        }

        return Statement::WHERE . ' ' . implode(' ', $this->where);
    }

    /**
     * Get the ORDER BY part of a query statement.
     *
     * @return string
     */
    protected function getOrderByQuery(): string
    {
        if (empty($this->orderBy)) {
            return '';
        }

        return Statement::ORDER_BY . ' ' . implode(', ', $this->orderBy);
    }

    /**
     * Get the LIMIT part of a query statement.
     *
     * @return string
     */
    protected function getLimitQuery(): string
    {
        if (null === $this->limit) {
            return '';
        }

        return Statement::LIMIT . ' ' . $this->limit;
    }

    /**
     * Get the OFFSET part of a query statement.
     *
     * @return string
     */
    protected function getOffsetQuery(): string
    {
        if (null === $this->offset) {
            return '';
        }

        return Statement::OFFSET . ' ' . $this->offset;
    }
}


<?php

declare(strict_types=1);

namespace Psi\Bridge\ObjectAgent\Doctrine\PhpcrOdm;

use Doctrine\ODM\PHPCR\Query\Builder\AbstractNode;
use Doctrine\ODM\PHPCR\Query\Builder\QueryBuilder;
use Psi\Component\ObjectAgent\Query\Comparison;
use Psi\Component\ObjectAgent\Query\Composite;
use Psi\Component\ObjectAgent\Query\Expression;

class ExpressionVisitor
{
    private $queryBuilder;
    private $sourceAlias;

    /**
     * @param QueryBuilder $queryBuilder
     */
    public function __construct(QueryBuilder $queryBuilder, string $sourceAlias)
    {
        $this->queryBuilder = $queryBuilder;
        $this->sourceAlias = $sourceAlias;
    }

    /**
     * Walk the given expression to build up the PHPCR-ODM query builder.
     *
     * @param Expression $expr
     * @param AbstractNode|null $parentNode
     */
    public function dispatch(Expression $expr, AbstractNode $parentNode = null)
    {
        if ($parentNode === null) {
            $parentNode = $this->queryBuilder->where();
        }

        switch (true) {
            case $expr instanceof Comparison:
                return $this->walkComparison($expr, $parentNode);

            case $expr instanceof Composite:
                return $this->walkComposite($expr, $parentNode);
        }

        throw new \RuntimeException('Unknown Expression: ' . get_class($expr));
    }

    /**
     * {@inheritdoc}
     */
    private function walkComparison(Comparison $comparison, AbstractNode $parentNode)
    {
        $field = $comparison->getField();
        $value = $comparison->getValue();

        switch ($comparison->getComparator()) {
            case Comparison::EQUALS:
                return $parentNode->eq()->field($this->getField($field))->literal($value)->end();

            case Comparison::NOT_EQUALS:
                return $parentNode->neq()->field($this->getField($field))->literal($value)->end();

            case Comparison::LESS_THAN:
                return $parentNode->lt()->field($this->getField($field))->literal($value)->end();

            case Comparison::LESS_THAN_EQUAL:
                return $parentNode->lte()->field($this->getField($field))->literal($value)->end();

            case Comparison::GREATER_THAN:
                return $parentNode->gt()->field($this->getField($field))->literal($value)->end();

            case Comparison::GREATER_THAN_EQUAL:
                return $parentNode->gte()->field($this->getField($field))->literal($value)->end();

            case Comparison::IN:
                return $this->getInConstraint($parentNode, $field, $value);

            case Comparison::NOT_IN:
                $node = $parentNode->not();
                $this->getInConstraint($node, $field, $value);

                return $node->end();

            case Comparison::CONTAINS:
                return $parentNode->like()->field($this->getField($field))->literal($value)->end();

            case Comparison::NOT_CONTAINS:
                return $parentNode->not()->like()->field($this->getField($field))->literal($value)->end()->end();

            case Comparison::NULL:
                return $parentNode->not()->fieldIsset($this->getField($field))->end();

            case Comparison::NOT_NULL:
                return $parentNode->fieldIsset($this->getField($field));
        }

        throw new \RuntimeException('Unknown comparator: ' . $comparison->getComparator());
    }

    /**
     * {@inheritdoc}
     */
    private function walkComposite(Composite $expression, AbstractNode $parentNode)
    {
        $node = $expression->getType() === Composite::AND ? $parentNode->andX() : $parentNode->orX();

        $expressions = $expression->getExpressions();

        if (empty($expressions)) {
            return $node;
        }

        $leftExpression = array_shift($expressions);
        $this->dispatch($leftExpression, $node);

        $parentNode = $node;
        foreach ($expressions as $index => $expression) {
            if (count($expressions) === $index + 1) {
                $this->dispatch($expression, $parentNode);
                break;
            }

            $this->dispatch($expression, $parentNode);
        }

        return $node;
    }

    /**
     * @param string $field
     *
     * @return string
     */
    private function getField($field): string
    {
        return $this->sourceAlias . '.' . $field;
    }

    /**
     * @param AbstractNode $parentNode
     * @param string $field
     * @param array $values
     */
    private function getInConstraint(AbstractNode $parentNode, $field, array $values)
    {
        $orNode = $parentNode->orx();

        foreach ($values as $value) {
            $orNode->eq()->field($this->getField($field))->literal($value);
        }

        $orNode->end();
    }
}


<?php namespace Ordercloud\Entities\Products;

use JsonSerializable;

class ProductTag implements JsonSerializable
{
    /** @var integer */
    private $id;
    /** @var string */
    private $name;
    /** @var string */
    private $description;
    /** @var string */
    private $shortDescription;
    /** @var boolean */
    private $enabled;
    /** @var ProductTagType */
    private $type;
    /** @var ProductTagLink */
    private $parentTag;
    /**
     * @var array|ProductTagLink[]
     * @reflectType Ordercloud\Entities\Products\ProductTagLink
     */
    private $childTags;

    public function __construct($id, $name, $description, $shortDescription, $enabled, ProductTagType $tagType = null, ProductTagLink $parentTag = null, array $childTags)
    {
        $this->id = $id;
        $this->name = $name;
        $this->description = $description;
        $this->shortDescription = $shortDescription;
        $this->enabled = $enabled;
        $this->type = $tagType;
        $this->parentTag = $parentTag;
        $this->childTags = $childTags;
    }

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

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

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

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

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

    /**
     * @param string $typeName
     *
     * @return bool
     */
    public function isType($typeName)
    {
        if (is_null($this->getType())) {
            return false;
        }

        return strcasecmp($this->getType()->getName(), $typeName) === 0;
    }

    /**
     * @return ProductTagType
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * @return ProductTagLink
     */
    public function getParentTag()
    {
        return $this->parentTag;
    }

    /**
     * @return array|ProductTagLink[]
     */
    public function getChildTags()
    {
        return $this->childTags;
    }

    /**
     * Specify data which should be serialized to JSON
     */
    public function jsonSerialize()
    {
        return [
            'id' => $this->getId(),
            'name' => $this->getName(),
            'description' => $this->getDescription(),
            'shortDescription' => $this->getShortDescription(),
            'enabled' => $this->isEnabled(),
            'tagType' => $this->getType(),
            'parentTag' => $this->getParentTag(),
            'childTags' => $this->getChildTags(),
        ];
    }
}


<?php

namespace tourze\Http\Request;

use tourze\Base\Object;
use tourze\Http\Http;
use tourze\Http\Request;
use tourze\Http\Request\Exception\RequestException;
use tourze\Http\Response;
use tourze\Http\Request\Exception\ClientRecursionException;

/**
 * 请求的具体实现类，支持两种请求方式，一种是内部请求，一种是外部请求
 *
 * @property array options
 * @property bool  follow
 * @property array followHeaders
 * @property bool  strictRedirect
 * @property array headerCallbacks
 * @property int   maxCallbackDepth
 * @property int   callbackDepth
 * @property mixed callbackParams
 * @property array callbackParams
 * @package tourze\Http\Request
 */
abstract class RequestClient extends Object
{

    /**
     * @var array 用作透传的选项变量
     */
    protected $_options = [];

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

    /**
     * @param array $options
     */
    public function setOptions($options)
    {
        $this->_options = $options;
    }

    /**
     * @var bool 如果返回header有跳转，是否继续跟随跳转
     */
    protected $_follow = false;

    /**
     * @param bool $follow
     */
    public function setFollow($follow)
    {
        $this->_follow = $follow;
    }

    /**
     * @return bool
     */
    public function isFollow()
    {
        return $this->_follow;
    }

    /**
     * @var array 跳转之后，依然要保留的header信息
     */
    protected $_followHeaders = ['Authorization'];

    /**
     * @param array $followHeaders
     */
    public function setFollowHeaders($followHeaders)
    {
        $this->_followHeaders = $followHeaders;
    }

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

    /**
     * @var bool 302重定向后依然使用之前的http方法？
     */
    protected $_strictRedirect = true;

    /**
     * @param bool $strictRedirect
     */
    public function setStrictRedirect($strictRedirect)
    {
        $this->_strictRedirect = $strictRedirect;
    }

    /**
     * @return bool
     */
    public function isStrictRedirect()
    {
        return $this->_strictRedirect;
    }

    /**
     * @var array 当请求带有指定的header信息时，自动执行回调函数
     */
    protected $_headerCallbacks = [
        'Location' => 'tourze\Http\Request\RequestClient::onHeaderLocation',
    ];

    /**
     * @param array $headerCallbacks
     */
    public function setHeaderCallbacks($headerCallbacks)
    {
        $this->_headerCallbacks = $headerCallbacks;
    }

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

    /**
     * @var int header回调函数执行的最大次数
     */
    protected $_maxCallbackDepth = 5;

    /**
     * @param int $maxCallbackDepth
     */
    public function setMaxCallbackDepth($maxCallbackDepth)
    {
        $this->_maxCallbackDepth = $maxCallbackDepth;
    }

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

    /**
     * @var int 当前主请求的级别
     */
    protected $_callbackDepth = 1;

    /**
     * @param int $callbackDepth
     */
    public function setCallbackDepth($callbackDepth)
    {
        $this->_callbackDepth = $callbackDepth;
    }

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

    /**
     * @var array 回调参数
     */
    protected $_callbackParams = [];

    /**
     * @param array $callbackParams
     */
    public function setCallbackParams($callbackParams)
    {
        $this->_callbackParams = $callbackParams;
    }

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

    /**
     * 处理请求，根据路由中的信息，执行对应的控制器和动作
     *
     * @param  Request $request
     * @return Response
     * @throws ClientRecursionException
     * @throws RequestException
     */
    public function execute(Request $request)
    {
        // 防止一直循环
        if ($this->callbackDepth > $this->maxCallbackDepth)
        {
            throw new ClientRecursionException('Could not execute request to :uri - too many recursions after :depth requests', [
                ':uri'   => $request->uri,
                ':depth' => $this->callbackDepth - 1,
            ]);
        }

        $origResponse = $response = new Response([
            'protocol' => $request->protocol,
        ]);

        $response = $this->executeRequest($request, $response);

        foreach ($this->headerCallbacks as $header => $callback)
        {
            if ($response->headers($header))
            {
                $callbackResult = call_user_func($callback, $request, $response, $this);

                if ($callbackResult instanceof Request)
                {
                    $this->assignClientProperties($callbackResult->client);
                    $callbackResult
                        ->client
                        ->callbackDepth = $this->callbackDepth + 1;

                    $response = $callbackResult->execute();
                }
                elseif ($callbackResult instanceof Response)
                {
                    $response = $callbackResult;
                }

                if ($response !== $origResponse)
                {
                    break;
                }
            }
        }

        return $response;
    }

    /**
     * 执行请求，并返回接口
     *
     * @param  Request  $request 要处理的request实例
     * @param  Response $response
     * @return Response
     */
    abstract public function executeRequest(Request $request, Response $response);

    /**
     * 复制client的信息
     *
     * @param RequestClient $client
     */
    public function assignClientProperties(RequestClient $client)
    {
        $client->options = $this->options;
        $client->follow = $this->follow;
        $client->followHeaders = $this->followHeaders;
        $client->headerCallbacks = $this->headerCallbacks;
        $client->maxCallbackDepth = $this->maxCallbackDepth;
        $client->callbackParams = $this->callbackParams;
    }

    /**
     * 跳转状态码的处理
     *
     * @param Request       $request
     * @param Response      $response
     * @param RequestClient $client
     * @return null|Request
     */
    public static function onHeaderLocation(Request $request, Response $response, RequestClient $client)
    {
        if ($client->follow
            && in_array($response->status, [
                Http::CREATED,
                Http::MOVED_PERMANENTLY,
                Http::FOUND,
                Http::SEE_OTHER,
                Http::TEMPORARY_REDIRECT,
            ])
        )
        {
            switch ($response->status)
            {
                default:
                case Http::MOVED_PERMANENTLY:
                case Http::TEMPORARY_REDIRECT:
                    $followMethod = $request->method;
                    break;
                case Http::CREATED:
                case Http::SEE_OTHER:
                    $followMethod = Http::GET;
                    break;
                case Http::FOUND:
                    if ($client->strictRedirect)
                    {
                        $followMethod = $request->method;
                    }
                    else
                    {
                        $followMethod = Http::GET;
                    }
                    break;
            }

            $origHeaders = $request->headers();
            $followHeaders = array_intersect_assoc($origHeaders, array_fill_keys($client->followHeaders, true));

            $followRequest = Request::factory($response->headers('Location'));
            $followRequest->method = $followMethod;
            $followRequest->headers($followHeaders);

            if ($followMethod !== Http::GET)
            {
                $followRequest->body = $request->body;
            }

            return $followRequest;
        }

        return null;
    }
}


<?php declare(strict_types=1);
/**
 * Uthando CMS (http://www.shaunfreeman.co.uk/)
 *
 * @package   UthandoUser\Service
 * @author    Shaun Freeman <shaun@shaunfreeman.co.uk>
 * @link      https://github.com/uthando-cms for the canonical source repository
 * @copyright Copyright (c) 2014 Shaun Freeman. (http://www.shaunfreeman.co.uk)
 * @license   see LICENSE
 */

namespace UthandoUser\Service;

use UthandoUser\Form\ForgotPasswordForm;
use UthandoUser\Form\PasswordForm;
use UthandoUser\Form\RegisterForm;
use UthandoUser\Form\UserEditForm;
use UthandoUser\Form\UserForm;
use UthandoUser\Hydrator\UserHydrator;
use UthandoUser\InputFilter\UserInputFilter;
use UthandoUser\Mapper\UserMapper;
use UthandoUser\Model\UserModel;
use UthandoCommon\Service\AbstractMapperService;
use UthandoUser\Options\AuthOptions;
use UthandoUser\UthandoUserException;
use Zend\Authentication\AuthenticationService;
use Zend\Crypt\Password\PasswordInterface;
use Zend\EventManager\Event;
use Zend\Form\Form;
use Zend\View\Model\ViewModel;

/**
 * Class User
 *
 * @package UthandoUser\Service
 * @method UserModel getModel($model = null)
 */
class UserService extends AbstractMapperService
{
    protected $form         = UserForm::class;
    protected $hydrator     = UserHydrator::class;
    protected $inputFilter  = UserInputFilter::class;
    protected $mapper       = UserMapper::class;
    protected $model        = UserModel::class;

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

    public function attachEvents(): void
    {
        $this->getEventManager()->attach('post.add', [$this, 'sendEmail']);
        $this->getEventManager()->attach('pre.add', [$this, 'preAdd']);
        $this->getEventManager()->attach('pre.edit', [$this, 'preEdit']);
        $this->getEventManager()->attach('post.edit', [$this, 'postEdit']);
        $this->getEventManager()->attach('pre.save', [$this, 'preSave']);
    }

    public function sendEmail(Event $e): void
    {
        $userId = $e->getParam('saved', null);
        $user = $this->getById($userId);

        if ($user instanceof UserModel) {

            $emailView = new ViewModel([
                'user' => $user,
            ]);

            $emailView->setTemplate('uthando-user/email/register');

            $this->getEventManager()->trigger('mail.send', $this, [
                'recipient' => [
                    'name' => $user->getFullName(),
                    'address' => $user->getEmail(),
                ],
                'layout' => 'uthando-user/email/layout',
                'body' => $emailView,
                'subject' => 'Account Registration',
                'transport' => 'default',
            ]);
        }
    }

    /**
     * Registers a new user
     *
     * @param array $post
     * @return int|Form
     * @throws \UthandoCommon\Service\ServiceException
     */
    public function register(array $post)
    {
        /* @var $form RegisterForm */
        $form = $this->getForm(RegisterForm::class);

        $model = $this->getModel();
        $model->setRole('registered');

        $form->setHydrator($this->getHydrator());
        $form->bind($model);

        /* @var $inputFilter \UthandoUser\InputFilter\UserInputFilter */
        $inputFilter = $this->getInputFilter();
        $form->setInputFilter($inputFilter);

        return $this->add($post, $form);
    }

    /**
     * Allows not admin user to edit thier profile
     *
     * @param UserModel $model
     * @param array $post
     * @return int|UserEditForm
     * @throws UthandoUserException
     * @throws \UthandoCommon\Service\ServiceException
     */
    public function editUser(UserModel $model, array $post)
    {
        if (!$model instanceof UserModel) {
            throw new UthandoUserException('$model must be an instance of UthandoUser\Model\User, ' . get_class($model) . ' given.');
        }

        $model->setDateModified();

        /* @var $form UserEditForm */
        $form = $this->getForm(UserEditForm::class);

        $form->setHydrator($this->getHydrator());
        $form->bind($model);

        /* @var $inputFilter \UthandoUser\InputFilter\UserInputFilter */
        $inputFilter = $this->getInputFilter();

        // we need to find if this email has changed,
        // if not then exclude it from validation,
        // if changed then reevaluate it.
        $email = ($model->getEmail() === $post['email']) ? $model->getEmail() : null;

        $inputFilter->addEmailNoRecordExists($email);

        $form->setInputFilter($inputFilter);

        $form->setData($post);
        $form->setValidationGroup([
            'firstname', 'lastname', 'email', 'userId', 'security'
        ]);

        if (!$form->isValid()) {
            return $form;
        }

        $saved = $this->save($form->getData());

        $this->updateSession($saved, $model);

        return $saved;

    }

    public function changePassword(array $post, UserModel $user)
    {
        /* @var $form PasswordForm */
        $form = $this->getForm(PasswordForm::class);

        /* @var $inputFilter \UthandoUser\InputFilter\UserInputFilter */
        $inputFilter = $this->getInputFilter();

        $inputFilter->addPasswordLength('register');

        $form->setHydrator($this->getHydrator());
        $form->setInputFilter($inputFilter);

        $form->setData($post);
        $form->bind($user);
        $form->setValidationGroup(['passwd', 'passwd-confirm', 'security']);

        if (!$form->isValid()) {
            return $form;
        }

        $user->setDateModified();

        $saved = $this->save($form->getData());

        return $saved;
    }

    private function updateSession(int $saved, UserModel $model): void
    {
        /* @var $auth AuthenticationService */
        $auth = $this->getService(AuthenticationService::class);
        $identity = $auth->getIdentity();

        // if user has updated this details write the update model to session
        if ($saved && $model instanceof UserModel && $model->getUserId() === $identity->getUserId()) {
            $auth->getStorage()->write($model);
        }
    }

    public function preAdd(Event $e): void
    {
        $form = $e->getParam('form');
        /* @var $inputFilter \UthandoUser\InputFilter\UserInputFilter */
        $inputFilter = $form->getInputFilter();
        $inputFilter->addEmailNoRecordExists(null);
        $inputFilter->addPasswordLength('register');
        $form->setValidationGroup([
            'firstname', 'lastname', 'email', 'passwd', 'passwd-confirm', 'role', 'security',
        ]);
    }

    public function preEdit(Event $e): void
    {
        $model = $e->getParam('model');
        $form = $e->getParam('form');
        $post = $e->getParam('post');

        $model->setDateModified();

        // we need to find if this email has changed,
        // if not then exclude it from validation,
        // if changed then reevaluate it.
        $email = ($model->getEmail() === $post['email']) ? $model->getEmail() : null;

        /* @var $inputFilter \UthandoUser\InputFilter\UserInputFilter */
        $inputFilter = $form->getInputFilter();
        $inputFilter->addEmailNoRecordExists($email);

        $form->setValidationGroup([
            'firstname', 'lastname', 'email', 'userId', 'active', 'role', 'security'
        ]);
    }

    public function postEdit(Event $e): void
    {
        $this->updateSession($e->getParam('saved', false), $e->getParam('model'));
    }

    public function preSave(Event $e): void
    {
        $data = $e->getParam('data');

        if ($data instanceof UserModel) {
            $data = $this->getMapper()->extract($data);
        }

        if (array_key_exists('passwd', $data) && '' != $data['passwd']) {
            $data['passwd'] = $this->createPassword($data['passwd']);
        } else {
            unset($data['passwd']);
        }

        $e->setParam('data', $data);
    }

    public function createPassword(string $password): string
    {
        /* @var $authOptions AuthOptions */
        $authOptions = $this->getService(AuthOptions::class);

        if (!class_exists($authOptions->getCredentialTreatment())) {
            throw new UthandoUserException('Credential treatment must be an class name');
        } else {
            $cryptClass = $authOptions->getCredentialTreatment();
            $crypt      = new $cryptClass;
        }

        if (!$crypt instanceof PasswordInterface) {
            throw new UthandoUserException('Credential treatment must be an instance of Zend\Crypt\Password\PasswordInterface');
        }

        $password = $crypt->create($password);

        return $password;
    }

    public function forgotPassword(array $post)
    {
        $email          = (isset($post['email'])) ? $post['email'] : '';
        $user           = $this->getUserByEmail(
            $email,
            null,
            true,
            false
        );
        /* @var $inputFilter \UthandoUser\InputFilter\UserInputFilter */
        $inputFilter    = $this->getInputFilter();
        /* @var $form \UthandoUser\Form\ForgotPasswordForm */
        $form           = $this->getService('FormElementManager')
            ->get(ForgotPasswordForm::class);

        //$inputFilter->addEmailNoRecordExists();
        $form->setValidationGroup(['email', 'captcha', 'security']);
        $form->setInputFilter($inputFilter);
        $form->setData($post);

        if (!$form->isValid()) {
            return $form;
        }

        return $this->resetPassword($user);
    }

    public function getAdminUserByEmail(string $email, ?string $ignore, bool $emptyPassword, bool $activeOnly): ?UserModel
    {
        /* @var $mapper \UthandoUser\Mapper\UserMapper */
        $mapper = $this->getMapper();
        return $mapper->getAdminUserByEmail($email, $ignore, $emptyPassword, $activeOnly);
    }

    public function getUserByEmail(string $email, ?string $ignore, bool $emptyPassword, bool $activeOnly): ?UserModel
    {
        /* @var $mapper \UthandoUser\Mapper\UserMapper */
        $mapper = $this->getMapper();
        return $mapper->getUserByEmail($email, $ignore, $emptyPassword, $activeOnly);
    }

    public function resetPassword(UserModel $user): int
    {
        $user->generatePassword();

        $result = $this->save($user);

        if ($result) {

            $emailView = new ViewModel([
                'user' => $user,
            ]);

            $emailView->setTemplate('uthando-user/email/reset-password');

            $this->getEventManager()->trigger('mail.send', $this, [
                'recipient' => [
                    'name' => $user->getFullName(),
                    'address' => $user->getEmail(),
                ],
                'layout' => 'uthando-user/email/layout',
                'body' => $emailView,
                'subject' => 'Reset Password',
                'transport' => 'default',
            ]);
        }

        return $result;

    }

    public function delete($id): int
    {
        $id = (int)$id;

        /* @var $auth AuthenticationService */
        $auth = $this->getService(AuthenticationService::class);
        $identity = $auth->getIdentity();

        // sanity check to see if we are deleting ourselves!
        if ($id == $identity->getUserId()) {
            throw new UthandoUserException('You cannot delete yourself!');
        }

        return parent::delete($id);
    }
}