<?php

namespace Reaction\Helpers;

use React\Stream\ReadableStreamInterface;
use React\Stream\WritableStreamInterface;
use Reaction\Base\Model;
use Reaction\Console\Exception;
use Reaction\Console\Markdown as ConsoleMarkdown;
use Reaction\Promise\ExtendedPromiseInterface;
use Reaction\Promise\Promise;
use function Reaction\Promise\reject;

/**
 * Console helper provides useful methods for command line related tasks such as getting input or formatting and coloring
 * output.
 */
class Console
{
    // foreground color control codes
    const FG_BLACK = 30;
    const FG_RED = 31;
    const FG_GREEN = 32;
    const FG_YELLOW = 33;
    const FG_BLUE = 34;
    const FG_PURPLE = 35;
    const FG_CYAN = 36;
    const FG_GREY = 37;
    // background color control codes
    const BG_BLACK = 40;
    const BG_RED = 41;
    const BG_GREEN = 42;
    const BG_YELLOW = 43;
    const BG_BLUE = 44;
    const BG_PURPLE = 45;
    const BG_CYAN = 46;
    const BG_GREY = 47;
    // fonts style control codes
    const RESET = 0;
    const NORMAL = 0;
    const BOLD = 1;
    const ITALIC = 3;
    const UNDERLINE = 4;
    const BLINK = 5;
    const NEGATIVE = 7;
    const CONCEALED = 8;
    const CROSSED_OUT = 9;
    const FRAMED = 51;
    const ENCIRCLED = 52;
    const OVERLINED = 53;

    /**
     * Moves the terminal cursor up by sending ANSI control code CUU to the terminal.
     * If the cursor is already at the edge of the screen, this has no effect.
     * @param int $rows number of rows the cursor should be moved up
     */
    public static function moveCursorUp($rows = 1)
    {
        static::stdout("\033[" . (int) $rows . 'A');
    }

    /**
     * Moves the terminal cursor down by sending ANSI control code CUD to the terminal.
     * If the cursor is already at the edge of the screen, this has no effect.
     * @param int $rows number of rows the cursor should be moved down
     */
    public static function moveCursorDown($rows = 1)
    {
        static::stdout("\033[" . (int) $rows . 'B');
    }

    /**
     * Moves the terminal cursor forward by sending ANSI control code CUF to the terminal.
     * If the cursor is already at the edge of the screen, this has no effect.
     * @param int $steps number of steps the cursor should be moved forward
     */
    public static function moveCursorForward($steps = 1)
    {
        static::stdout("\033[" . (int) $steps . 'C');
    }

    /**
     * Moves the terminal cursor backward by sending ANSI control code CUB to the terminal.
     * If the cursor is already at the edge of the screen, this has no effect.
     * @param int $steps number of steps the cursor should be moved backward
     */
    public static function moveCursorBackward($steps = 1)
    {
        static::stdout("\033[" . (int) $steps . 'D');
    }

    /**
     * Moves the terminal cursor to the beginning of the next line by sending ANSI control code CNL to the terminal.
     * @param int $lines number of lines the cursor should be moved down
     */
    public static function moveCursorNextLine($lines = 1)
    {
        static::stdout("\033[" . (int) $lines . 'E');
    }

    /**
     * Moves the terminal cursor to the beginning of the previous line by sending ANSI control code CPL to the terminal.
     * @param int $lines number of lines the cursor should be moved up
     */
    public static function moveCursorPrevLine($lines = 1)
    {
        static::stdout("\033[" . (int) $lines . 'F');
    }

    /**
     * Moves the cursor to an absolute position given as column and row by sending ANSI control code CUP or CHA to the terminal.
     * @param int $column 1-based column number, 1 is the left edge of the screen.
     * @param int|null $row 1-based row number, 1 is the top edge of the screen. if not set, will move cursor only in current line.
     */
    public static function moveCursorTo($column, $row = null)
    {
        if ($row === null) {
            static::stdout("\033[" . (int) $column . 'G');
        } else {
            static::stdout("\033[" . (int) $row . ';' . (int) $column . 'H');
        }
    }

    /**
     * Scrolls whole page up by sending ANSI control code SU to the terminal.
     * New lines are added at the bottom. This is not supported by ANSI.SYS used in windows.
     * @param int $lines number of lines to scroll up
     */
    public static function scrollUp($lines = 1)
    {
        static::stdout("\033[" . (int) $lines . 'S');
    }

    /**
     * Scrolls whole page down by sending ANSI control code SD to the terminal.
     * New lines are added at the top. This is not supported by ANSI.SYS used in windows.
     * @param int $lines number of lines to scroll down
     */
    public static function scrollDown($lines = 1)
    {
        static::stdout("\033[" . (int) $lines . 'T');
    }

    /**
     * Saves the current cursor position by sending ANSI control code SCP to the terminal.
     * Position can then be restored with [[restoreCursorPosition()]].
     */
    public static function saveCursorPosition()
    {
        static::stdout("\033[s");
    }

    /**
     * Restores the cursor position saved with [[saveCursorPosition()]] by sending ANSI control code RCP to the terminal.
     */
    public static function restoreCursorPosition()
    {
        static::stdout("\033[u");
    }

    /**
     * Hides the cursor by sending ANSI DECTCEM code ?25l to the terminal.
     * Use [[showCursor()]] to bring it back.
     * Do not forget to show cursor when your application exits. Cursor might stay hidden in terminal after exit.
     */
    public static function hideCursor()
    {
        static::stdout("\033[?25l");
    }

    /**
     * Will show a cursor again when it has been hidden by [[hideCursor()]]  by sending ANSI DECTCEM code ?25h to the terminal.
     */
    public static function showCursor()
    {
        static::stdout("\033[?25h");
    }

    /**
     * Clears entire screen content by sending ANSI control code ED with argument 2 to the terminal.
     * Cursor position will not be changed.
     * **Note:** ANSI.SYS implementation used in windows will reset cursor position to upper left corner of the screen.
     */
    public static function clearScreen()
    {
        static::stdout("\033[2J");
    }

    /**
     * Clears text from cursor to the beginning of the screen by sending ANSI control code ED with argument 1 to the terminal.
     * Cursor position will not be changed.
     */
    public static function clearScreenBeforeCursor()
    {
        static::stdout("\033[1J");
    }

    /**
     * Clears text from cursor to the end of the screen by sending ANSI control code ED with argument 0 to the terminal.
     * Cursor position will not be changed.
     */
    public static function clearScreenAfterCursor()
    {
        static::stdout("\033[0J");
    }

    /**
     * Clears the line, the cursor is currently on by sending ANSI control code EL with argument 2 to the terminal.
     * Cursor position will not be changed.
     */
    public static function clearLine()
    {
        static::stdout("\033[2K");
        static::moveCursorTo(0);
    }

    /**
     * Clears text from cursor position to the beginning of the line by sending ANSI control code EL with argument 1 to the terminal.
     * Cursor position will not be changed.
     */
    public static function clearLineBeforeCursor()
    {
        static::stdout("\033[1K");
    }

    /**
     * Clears text from cursor position to the end of the line by sending ANSI control code EL with argument 0 to the terminal.
     * Cursor position will not be changed.
     */
    public static function clearLineAfterCursor()
    {
        static::stdout("\033[0K");
    }

    /**
     * Returns the ANSI format code.
     *
     * @param array $format An array containing formatting values.
     * You can pass any of the `FG_*`, `BG_*` and `TEXT_*` constants
     * and also [[xtermFgColor]] and [[xtermBgColor]] to specify a format.
     * @return string The ANSI format code according to the given formatting constants.
     */
    public static function ansiFormatCode($format)
    {
        return "\033[" . implode(';', $format) . 'm';
    }

    /**
     * Echoes an ANSI format code that affects the formatting of any text that is printed afterwards.
     *
     * @param array $format An array containing formatting values.
     * You can pass any of the `FG_*`, `BG_*` and `TEXT_*` constants
     * and also [[xtermFgColor]] and [[xtermBgColor]] to specify a format.
     * @see ansiFormatCode()
     * @see endAnsiFormat()
     */
    public static function beginAnsiFormat($format)
    {
        static::stdout("\033[" . implode(';', $format) . 'm');
    }

    /**
     * Resets any ANSI format set by previous method [[beginAnsiFormat()]]
     * Any output after this will have default text format.
     * This is equal to calling.
     *
     * ```php
     * echo Console::ansiFormatCode([Console::RESET])
     * ```
     */
    public static function endAnsiFormat()
    {
        static::stdout("\033[0m");
    }

    /**
     * Will return a string formatted with the given ANSI style.
     *
     * @param string $string the string to be formatted
     * @param array $format An array containing formatting values.
     * You can pass any of the `FG_*`, `BG_*` and `TEXT_*` constants
     * and also [[xtermFgColor]] and [[xtermBgColor]] to specify a format.
     * @return string
     */
    public static function ansiFormat($string, $format = [])
    {
        $code = implode(';', $format);

        return "\033[0m" . ($code !== '' ? "\033[" . $code . 'm' : '') . $string . "\033[0m";
    }

    /**
     * Returns the ansi format code for xterm foreground color.
     *
     * You can pass the return value of this to one of the formatting methods:
     * [[ansiFormat]], [[ansiFormatCode]], [[beginAnsiFormat]].
     *
     * @param int $colorCode xterm color code
     * @return string
     * @see http://en.wikipedia.org/wiki/Talk:ANSI_escape_code#xterm-256colors
     */
    public static function xtermFgColor($colorCode)
    {
        return '38;5;' . $colorCode;
    }

    /**
     * Returns the ansi format code for xterm background color.
     *
     * You can pass the return value of this to one of the formatting methods:
     * [[ansiFormat]], [[ansiFormatCode]], [[beginAnsiFormat]].
     *
     * @param int $colorCode xterm color code
     * @return string
     * @see http://en.wikipedia.org/wiki/Talk:ANSI_escape_code#xterm-256colors
     */
    public static function xtermBgColor($colorCode)
    {
        return '48;5;' . $colorCode;
    }

    /**
     * Strips ANSI control codes from a string.
     *
     * @param string $string String to strip
     * @return string
     */
    public static function stripAnsiFormat($string)
    {
        return preg_replace('/\033\[[\d;?]*\w/', '', $string);
    }

    /**
     * Returns the length of the string without ANSI color codes.
     * @param string $string the string to measure
     * @return int the length of the string not counting ANSI format characters
     */
    public static function ansiStrlen($string)
    {
        return mb_strlen(static::stripAnsiFormat($string));
    }

    /**
     * Converts an ANSI formatted string to HTML.
     *
     * Note: xTerm 256 bit colors are currently not supported.
     *
     * @param string $string the string to convert.
     * @param array $styleMap an optional mapping of ANSI control codes such as
     * FG\_*COLOR* or [[BOLD]] to a set of css style definitions.
     * The CSS style definitions are represented as an array where the array keys correspond
     * to the css style attribute names and the values are the css values.
     * values may be arrays that will be merged and imploded with `' '` when rendered.
     * @return string HTML representation of the ANSI formatted string
     */
    public static function ansiToHtml($string, $styleMap = [])
    {
        $styleMap = [
            // http://www.w3.org/TR/CSS2/syndata.html#value-def-color
            self::FG_BLACK => ['color' => 'black'],
            self::FG_BLUE => ['color' => 'blue'],
            self::FG_CYAN => ['color' => 'aqua'],
            self::FG_GREEN => ['color' => 'lime'],
            self::FG_GREY => ['color' => 'silver'],
            // http://meyerweb.com/eric/thoughts/2014/06/19/rebeccapurple/
            // http://dev.w3.org/csswg/css-color/#valuedef-rebeccapurple
            self::FG_PURPLE => ['color' => 'rebeccapurple'],
            self::FG_RED => ['color' => 'red'],
            self::FG_YELLOW => ['color' => 'yellow'],
            self::BG_BLACK => ['background-color' => 'black'],
            self::BG_BLUE => ['background-color' => 'blue'],
            self::BG_CYAN => ['background-color' => 'aqua'],
            self::BG_GREEN => ['background-color' => 'lime'],
            self::BG_GREY => ['background-color' => 'silver'],
            self::BG_PURPLE => ['background-color' => 'rebeccapurple'],
            self::BG_RED => ['background-color' => 'red'],
            self::BG_YELLOW => ['background-color' => 'yellow'],
            self::BOLD => ['font-weight' => 'bold'],
            self::ITALIC => ['font-style' => 'italic'],
            self::UNDERLINE => ['text-decoration' => ['underline']],
            self::OVERLINED => ['text-decoration' => ['overline']],
            self::CROSSED_OUT => ['text-decoration' => ['line-through']],
            self::BLINK => ['text-decoration' => ['blink']],
            self::CONCEALED => ['visibility' => 'hidden'],
        ] + $styleMap;

        $tags = 0;
        $result = preg_replace_callback(
            '/\033\[([\d;]+)m/',
            function ($ansi) use (&$tags, $styleMap) {
                $style = [];
                $reset = false;
                $negative = false;
                foreach (explode(';', $ansi[1]) as $controlCode) {
                    if ($controlCode == 0) {
                        $style = [];
                        $reset = true;
                    } elseif ($controlCode == self::NEGATIVE) {
                        $negative = true;
                    } elseif (isset($styleMap[$controlCode])) {
                        $style[] = $styleMap[$controlCode];
                    }
                }

                $return = '';
                while ($reset && $tags > 0) {
                    $return .= '';
                    $tags--;
                }
                if (empty($style)) {
                    return $return;
                }

                $currentStyle = [];
                foreach ($style as $content) {
                    $currentStyle = ArrayHelper::merge($currentStyle, $content);
                }

                // if negative is set, invert background and foreground
                if ($negative) {
                    if (isset($currentStyle['color'])) {
                        $fgColor = $currentStyle['color'];
                        unset($currentStyle['color']);
                    }
                    if (isset($currentStyle['background-color'])) {
                        $bgColor = $currentStyle['background-color'];
                        unset($currentStyle['background-color']);
                    }
                    if (isset($fgColor)) {
                        $currentStyle['background-color'] = $fgColor;
                    }
                    if (isset($bgColor)) {
                        $currentStyle['color'] = $bgColor;
                    }
                }

                $styleString = '';
                foreach ($currentStyle as $name => $value) {
                    if (is_array($value)) {
                        $value = implode(' ', $value);
                    }
                    $styleString .= "$name: $value;";
                }
                $tags++;
                return "$return";
            },
            $string
        );
        while ($tags > 0) {
            $result .= '';
            $tags--;
        }

        return $result;
    }

    /**
     * Converts Markdown to be better readable in console environments by applying some ANSI format.
     * @param string $markdown the markdown string.
     * @return string the parsed result as ANSI formatted string.
     */
    public static function markdownToAnsi($markdown)
    {
        $parser = new ConsoleMarkdown();
        return $parser->parse($markdown);
    }

    /**
     * Converts a string to ansi formatted by replacing patterns like %y (for yellow) with ansi control codes.
     *
     * Uses almost the same syntax as https://github.com/pear/Console_Color2/blob/master/Console/Color2.php
     * The conversion table is: ('bold' meaning 'light' on some
     * terminals). It's almost the same conversion table irssi uses.
     *

     *                  text      text            background
     *      ------------------------------------------------
     *      %k %K %0    black     dark grey       black
     *      %r %R %1    red       bold red        red
     *      %g %G %2    green     bold green      green
     *      %y %Y %3    yellow    bold yellow     yellow
     *      %b %B %4    blue      bold blue       blue
     *      %m %M %5    magenta   bold magenta    magenta
     *      %p %P       magenta (think: purple)
     *      %c %C %6    cyan      bold cyan       cyan
     *      %w %W %7    white     bold white      white
     *
     *      %F     Blinking, Flashing
     *      %U     Underline
     *      %8     Reverse
     *      %_,%9  Bold
     *
     *      %n     Resets the color
     *      %%     A single %
     *

     * First param is the string to convert, second is an optional flag if
     * colors should be used. It defaults to true, if set to false, the
     * color codes will just be removed (And %% will be transformed into %)
     *
     * @param string $string String to convert
     * @param bool $colored Should the string be colored?
     * @return string
     */
    public static function renderColoredString($string, $colored = true)
    {
        // TODO rework/refactor according to https://github.com/yiisoft/yii2/issues/746
        static $conversions = [
            '%y' => [self::FG_YELLOW],
            '%g' => [self::FG_GREEN],
            '%b' => [self::FG_BLUE],
            '%r' => [self::FG_RED],
            '%p' => [self::FG_PURPLE],
            '%m' => [self::FG_PURPLE],
            '%c' => [self::FG_CYAN],
            '%w' => [self::FG_GREY],
            '%k' => [self::FG_BLACK],
            '%n' => [0], // reset
            '%Y' => [self::FG_YELLOW, self::BOLD],
            '%G' => [self::FG_GREEN, self::BOLD],
            '%B' => [self::FG_BLUE, self::BOLD],
            '%R' => [self::FG_RED, self::BOLD],
            '%P' => [self::FG_PURPLE, self::BOLD],
            '%M' => [self::FG_PURPLE, self::BOLD],
            '%C' => [self::FG_CYAN, self::BOLD],
            '%W' => [self::FG_GREY, self::BOLD],
            '%K' => [self::FG_BLACK, self::BOLD],
            '%N' => [0, self::BOLD],
            '%3' => [self::BG_YELLOW],
            '%2' => [self::BG_GREEN],
            '%4' => [self::BG_BLUE],
            '%1' => [self::BG_RED],
            '%5' => [self::BG_PURPLE],
            '%6' => [self::BG_CYAN],
            '%7' => [self::BG_GREY],
            '%0' => [self::BG_BLACK],
            '%F' => [self::BLINK],
            '%U' => [self::UNDERLINE],
            '%8' => [self::NEGATIVE],
            '%9' => [self::BOLD],
            '%_' => [self::BOLD],
        ];

        if ($colored) {
            $string = str_replace('%%', '% ', $string);
            foreach ($conversions as $key => $value) {
                $string = str_replace(
                    $key,
                    static::ansiFormatCode($value),
                    $string
                );
            }
            $string = str_replace('% ', '%', $string);
        } else {
            $string = preg_replace('/%((%)|.)/', '$2', $string);
        }

        return $string;
    }

    /**
     * Escapes % so they don't get interpreted as color codes when
     * the string is parsed by [[renderColoredString]].
     *
     * @param string $string String to escape
     *
     * @return string
     */
    public static function escape($string)
    {
        // TODO rework/refactor according to https://github.com/yiisoft/yii2/issues/746
        return str_replace('%', '%%', $string);
    }

    /**
     * Returns true if the stream supports colorization. ANSI colors are disabled if not supported by the stream.
     *
     * - windows without ansicon
     * - not tty consoles
     *
     * @param mixed $stream
     * @return bool true if the stream supports ANSI colors, otherwise false.
     */
    public static function streamSupportsAnsiColors($stream)
    {
        return DIRECTORY_SEPARATOR === '\\'
            ? getenv('ANSICON') !== false || getenv('ConEmuANSI') === 'ON'
            : function_exists('posix_isatty') && @posix_isatty($stream);
    }

    /**
     * Returns true if the console is running on windows.
     * @return bool
     */
    public static function isRunningOnWindows()
    {
        return DIRECTORY_SEPARATOR === '\\';
    }

    /**
     * Returns terminal screen size.
     *
     * Usage:
     *
     * ```php
     * list($width, $height) = ConsoleHelper::getScreenSize();
     * ```
     *
     * @param bool $refresh whether to force checking and not re-use cached size value.
     * This is useful to detect changing window size while the application is running but may
     * not get up to date values on every terminal.
     * @return array|bool An array of ($width, $height) or false when it was not able to determine size.
     */
    public static function getScreenSize($refresh = false)
    {
        static $size;
        if ($size !== null && !$refresh) {
            return $size;
        }

        if (static::isRunningOnWindows()) {
            $output = [];
            exec('mode con', $output);
            if (isset($output[1]) && strpos($output[1], 'CON') !== false) {
                return $size = [(int) preg_replace('~\D~', '', $output[4]), (int) preg_replace('~\D~', '', $output[3])];
            }
        } else {
            // try stty if available
            $stty = [];
            if (exec('stty -a 2>&1', $stty)) {
                $stty = implode(' ', $stty);

                // Linux stty output
                if (preg_match('/rows\s+(\d+);\s*columns\s+(\d+);/mi', $stty, $matches)) {
                    $size = [(int) $matches[2], (int) $matches[1]];
                    if ($size !== [0, 0]) {
                        return $size;
                    }
                }

                // MacOS stty output
                if (preg_match('/(\d+)\s+rows;\s*(\d+)\s+columns;/mi', $stty, $matches)) {
                    $size = [(int) $matches[2], (int) $matches[1]];
                    if ($size !== [0, 0]) {
                        return $size;
                    }
                }
            }

            // fallback to tput, which may not be updated on terminal resize
            if (($width = (int) exec('tput cols 2>&1')) > 0 && ($height = (int) exec('tput lines 2>&1')) > 0) {
                return $size = [$width, $height];
            }

            // fallback to ENV variables, which may not be updated on terminal resize
            if (($width = (int) getenv('COLUMNS')) > 0 && ($height = (int) getenv('LINES')) > 0) {
                return $size = [$width, $height];
            }
        }

        return $size = false;
    }

    /**
     * Word wrap text with indentation to fit the screen size.
     *
     * If screen size could not be detected, or the indentation is greater than the screen size, the text will not be wrapped.
     *
     * The first line will **not** be indented, so `Console::wrapText("Lorem ipsum dolor sit amet.", 4)` will result in the
     * following output, given the screen width is 16 characters:
     *
     * ```
     * Lorem ipsum
     *     dolor sit
     *     amet.
     * ```
     *
     * @param string $text the text to be wrapped
     * @param int $indent number of spaces to use for indentation.
     * @param bool $refresh whether to force refresh of screen size.
     * This will be passed to [[getScreenSize()]].
     * @return string the wrapped text.
     */
    public static function wrapText($text, $indent = 0, $refresh = false)
    {
        $size = static::getScreenSize($refresh);
        if ($size === false || $size[0] <= $indent) {
            return $text;
        }
        $pad = str_repeat(' ', $indent);
        $lines = explode("\n", wordwrap($text, $size[0] - $indent, "\n", true));
        $first = true;
        foreach ($lines as $i => $line) {
            if ($first) {
                $first = false;
                continue;
            }
            $lines[$i] = $pad . $line;
        }

        return implode("\n", $lines);
    }

    /**
     * Gets input from STDIN and returns a string right-trimmed for EOLs.
     *
     * @param bool $raw If set to true, returns the raw string without trimming
     * @return ExtendedPromiseInterface with string the string read from stdin
     */
    public static function stdin($raw = false)
    {
        $promise = new Promise(function($r, $c) use ($raw) {
            static::getStdInStream()->once('data', function($chunk) use ($r, $raw) {
                if (!$raw) {
                    $chunk = rtrim($chunk, PHP_EOL);
                }
                $r($chunk);
            });
        });
        return $promise;
    }

    /**
     * Prints a string to STDOUT.
     *
     * @param string $string the string to print
     * @return bool Number of bytes printed or false on error
     */
    public static function stdout($string)
    {
        return static::getStdOutStream()->write($string);
    }

    /**
     * Prints a string to STDERR.
     *
     * @param string $string the string to print
     * @return bool Number of bytes printed or false on error
     */
    public static function stderr($string)
    {
        return static::getStdOutStream()->write($string);
    }

    /**
     * Asks the user for input. Ends when the user types a carriage return (PHP_EOL). Optionally, It also provides a
     * prompt.
     *
     * @param string $prompt the prompt to display before waiting for input (optional)
     * @return ExtendedPromiseInterface with string the user's input
     */
    public static function input($prompt = null)
    {
        if (isset($prompt)) {
            static::stdout($prompt);
        }

        return static::stdin();
    }

    /**
     * Prints text to STDOUT appended with a carriage return (PHP_EOL).
     *
     * @param string $string the text to print
     * @return bool number of bytes printed or false on error.
     */
    public static function output($string = null)
    {
        return static::stdout($string . PHP_EOL);
    }

    /**
     * Prints text to STDERR appended with a carriage return (PHP_EOL).
     *
     * @param string $string the text to print
     * @return bool number of bytes printed or false on error.
     */
    public static function error($string = null)
    {
        return static::stderr($string . PHP_EOL);
    }

    /**
     * Prompts the user for input and validates it.
     *
     * @param string $text prompt string
     * @param array $options the options to validate the input:
     *
     * - `required`: whether it is required or not
     * - `default`: default value if no input is inserted by the user
     * - `pattern`: regular expression pattern to validate user input
     * - `validator`: a callable function to validate input. The function must accept two parameters:
     * - `input`: the user input to validate
     * - `error`: the error value passed by reference if validation failed.
     *
     * @return ExtendedPromiseInterface with string the user input
     */
    public static function prompt($text, $options = [])
    {
        $options = ArrayHelper::merge(
            [
                'required' => false,
                'default' => null,
                'pattern' => null,
                'validator' => null,
                'error' => 'Invalid input.',
            ],
            $options
        );
        $error = null;

        $basePromptFunc =
            function() use ($text, $options) {
            return $options['default']
                ? static::input("$text [" . $options['default'] . '] ')
                : static::input("$text ");
        };

        return $basePromptFunc()->then(static::promptValidationCallback($options, $basePromptFunc, $error));
    }

    /**
     * @param array       $options
     * @param \Closure    $basePromptFunc
     * @param string|null $error
     * @return \Closure
     * @internal
     */
    protected static function promptValidationCallback($options, $basePromptFunc, &$error) {
        $thenPromptFunction = function($input) use ($options, $basePromptFunc, &$error) {
            if ($input === '') {
                if (isset($options['default'])) {
                    $input = $options['default'];
                } elseif ($options['required']) {
                    static::output($options['error']);
                    return $basePromptFunc()
                        ->then(static::promptValidationCallback($options, $basePromptFunc, $error));
                }
            } elseif ($options['pattern'] && !preg_match($options['pattern'], $input)) {
                static::output($options['error']);
                return $basePromptFunc()
                    ->then(static::promptValidationCallback($options, $basePromptFunc, $error));
            } elseif ($options['validator'] &&
                !call_user_func_array($options['validator'], [$input, &$error])
            ) {
                static::output(isset($error) ? $error : $options['error']);
                return $basePromptFunc()
                    ->then(static::promptValidationCallback($options, $basePromptFunc, $error));
            }
            return $input;
        };
        return $thenPromptFunction;
    }

    /**
     * Asks user to confirm by typing y or n.
     *
     * A typical usage looks like the following:
     *
     * ```php
     * if (Console::confirm("Are you sure?")) {
     *     echo "user typed yes\n";
     * } else {
     *     echo "user typed no\n";
     * }
     * ```
     *
     * @param string $message to print out before waiting for user input
     * @param bool   $default this value is returned if no selection is made.
     * @param bool   $rejectIfNo
     * @return ExtendedPromiseInterface with bool whether user confirmed
     */
    public static function confirm($message, $default = false, $rejectIfNo = true)
    {
        $promptMessage = $message . ' (yes|no) :';
        $promptOptions = [
            'default' => $default ? 'yes' : 'no',
            'validator' => function($input, &$error) {
                $input = trim($input);
                $variants = ['yes', 'no', 'y', 'n'];
                foreach ($variants as $variant) {
                    if (!strcasecmp($input, $variant)) {
                        return true;
                    }
                }
                $error = "You must type 'yes' or 'no' (y|n)";
                return false;
            },
        ];
        return static::prompt($promptMessage, $promptOptions)->then(function($input) use ($default, $rejectIfNo) {
            $input = trim($input);

            if (!strcasecmp($input, 'y') || !strcasecmp($input, 'yes')) {
                return true;
            }

            if (!strcasecmp($input, 'n') || !strcasecmp($input, 'no')) {
                return $rejectIfNo ? reject(new Exception("User canceled")) : false;
            }

            return $default ? $default : ($rejectIfNo ? reject(new Exception("User canceled")) : false);
        });
    }

    /**
     * Gives the user an option to choose from. Giving '?' as an input will show
     * a list of options to choose from and their explanations.
     *
     * @param string $prompt the prompt message
     * @param array $options Key-value array of options to choose from. Key is what is inputed and used, value is
     * what's displayed to end user by help command.
     *
     * @return ExtendedPromiseInterface with string An option character the user chose
     */
    public static function select($prompt, $options = [])
    {
        $helpText = '';
        foreach ($options as $key => $value) {
            $helpText .= " $key - $value\n";
        }
        $helpText .= ' ? - Show help';
        $promptText = "$prompt [" . implode(',', array_keys($options)) . ',?]: ';
        $promptOptions = [
            'required' => true,
            'validator' => function($input, &$error) use($options, $helpText) {
                $input = trim($input);
                if ($input === '?') {
                    $error = $helpText;
                    return false;
                }
                if (array_key_exists($input, $options)) {
                    return true;
                }

                $error = "Invalid input, please enter '?' for help";
                return false;
            }
        ];
        return static::prompt($promptText, $promptOptions);
    }

    private static $_progressStart;
    private static $_progressWidth;
    private static $_progressPrefix;
    private static $_progressEta;
    private static $_progressEtaLastDone = 0;
    private static $_progressEtaLastUpdate;

    /**
     * Starts display of a progress bar on screen.
     *
     * This bar will be updated by [[updateProgress()]] and my be ended by [[endProgress()]].
     *
     * The following example shows a simple usage of a progress bar:
     *
     * ```php
     * Console::startProgress(0, 1000);
     * for ($n = 1; $n <= 1000; $n++) {
     *     usleep(1000);
     *     Console::updateProgress($n, 1000);
     * }
     * Console::endProgress();
     * ```
     *
     * Git clone like progress (showing only status information):
     * ```php
     * Console::startProgress(0, 1000, 'Counting objects: ', false);
     * for ($n = 1; $n <= 1000; $n++) {
     *     usleep(1000);
     *     Console::updateProgress($n, 1000);
     * }
     * Console::endProgress("done." . PHP_EOL);
     * ```
     *
     * @param int $done the number of items that are completed.
     * @param int $total the total value of items that are to be done.
     * @param string $prefix an optional string to display before the progress bar.
     * Default to empty string which results in no prefix to be displayed.
     * @param int|bool $width optional width of the progressbar. This can be an integer representing
     * the number of characters to display for the progress bar or a float between 0 and 1 representing the
     * percentage of screen with the progress bar may take. It can also be set to false to disable the
     * bar and only show progress information like percent, number of items and ETA.
     * If not set, the bar will be as wide as the screen. Screen size will be detected using [[getScreenSize()]].
     * @see startProgress
     * @see updateProgress
     * @see endProgress
     */
    public static function startProgress($done, $total, $prefix = '', $width = null)
    {
        self::$_progressStart = time();
        self::$_progressWidth = $width;
        self::$_progressPrefix = $prefix;
        self::$_progressEta = null;
        self::$_progressEtaLastDone = 0;
        self::$_progressEtaLastUpdate = time();

        static::updateProgress($done, $total);
    }

    /**
     * Updates a progress bar that has been started by [[startProgress()]].
     *
     * @param int $done the number of items that are completed.
     * @param int $total the total value of items that are to be done.
     * @param string $prefix an optional string to display before the progress bar.
     * Defaults to null meaning the prefix specified by [[startProgress()]] will be used.
     * If prefix is specified it will update the prefix that will be used by later calls.
     * @see startProgress
     * @see endProgress
     */
    public static function updateProgress($done, $total, $prefix = null)
    {
        if ($prefix === null) {
            $prefix = self::$_progressPrefix;
        } else {
            self::$_progressPrefix = $prefix;
        }
        $width = static::getProgressbarWidth($prefix);
        $percent = ($total == 0) ? 1 : $done / $total;
        $info = sprintf('%d%% (%d/%d)', $percent * 100, $done, $total);
        self::setETA($done, $total);
        $info .= self::$_progressEta === null ? ' ETA: n/a' : sprintf(' ETA: %d sec.', self::$_progressEta);

        // Number extra characters outputted. These are opening [, closing ], and space before info
        // Since Windows uses \r\n\ for line endings, there's one more in the case
        $extraChars = static::isRunningOnWindows() ? 4 : 3;
        $width -= $extraChars + static::ansiStrlen($info);
        // skipping progress bar on very small display or if forced to skip
        if ($width < 5) {
            static::stdout("\r$prefix$info   ");
        } else {
            if ($percent < 0) {
                $percent = 0;
            } elseif ($percent > 1) {
                $percent = 1;
            }
            $bar = floor($percent * $width);
            $status = str_repeat('=', $bar);
            if ($bar < $width) {
                $status .= '>';
                $status .= str_repeat(' ', $width - $bar - 1);
            }
            static::stdout("\r$prefix" . "[$status] $info");
        }
        flush();
    }

    /**
     * Return width of the progressbar
     * @param string $prefix an optional string to display before the progress bar.
     * @see updateProgress
     * @return int screen width
     */
    private static function getProgressbarWidth($prefix)
    {
        $width = self::$_progressWidth;

        if ($width === false) {
            return 0;
        }

        $screenSize = static::getScreenSize(true);
        if ($screenSize === false && $width < 1) {
            return 0;
        }

        if ($width === null) {
            $width = $screenSize[0];
        } elseif ($width > 0 && $width < 1) {
            $width = floor($screenSize[0] * $width);
        }

        $width -= static::ansiStrlen($prefix);

        return $width;
    }

    /**
     * Calculate $_progressEta, $_progressEtaLastUpdate and $_progressEtaLastDone
     * @param int $done the number of items that are completed.
     * @param int $total the total value of items that are to be done.
     * @see updateProgress
     */
    private static function setETA($done, $total)
    {
        if ($done > $total || $done == 0) {
            self::$_progressEta = null;
            self::$_progressEtaLastUpdate = time();
            return;
        }

        if ($done < $total && (time() - self::$_progressEtaLastUpdate > 1 && $done > self::$_progressEtaLastDone)) {
            $rate = (time() - (self::$_progressEtaLastUpdate ?: self::$_progressStart)) / ($done - self::$_progressEtaLastDone);
            self::$_progressEta = $rate * ($total - $done);
            self::$_progressEtaLastUpdate = time();
            self::$_progressEtaLastDone = $done;
        }
    }

    /**
     * Ends a progress bar that has been started by [[startProgress()]].
     *
     * @param string|bool $remove This can be `false` to leave the progress bar on screen and just print a newline.
     * If set to `true`, the line of the progress bar will be cleared. This may also be a string to be displayed instead
     * of the progress bar.
     * @param bool $keepPrefix whether to keep the prefix that has been specified for the progressbar when progressbar
     * gets removed. Defaults to true.
     * @see startProgress
     * @see updateProgress
     */
    public static function endProgress($remove = false, $keepPrefix = true)
    {
        if ($remove === false) {
            static::stdout(PHP_EOL);
        } else {
            if (static::streamSupportsAnsiColors(STDOUT)) {
                static::clearLine();
            }
            static::stdout("\r" . ($keepPrefix ? self::$_progressPrefix : '') . (is_string($remove) ? $remove : ''));
        }
        flush();

        self::$_progressStart = null;
        self::$_progressWidth = null;
        self::$_progressPrefix = '';
        self::$_progressEta = null;
        self::$_progressEtaLastDone = 0;
        self::$_progressEtaLastUpdate = null;
    }

    /**
     * Generates a summary of the validation errors.
     * @param Model|Model[] $models the model(s) whose validation errors are to be displayed.
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
     *
     * - showAllErrors: boolean, if set to true every error message for each attribute will be shown otherwise
     *   only the first error message for each attribute will be shown. Defaults to `false`.
     *
     * @return string the generated error summary
     */
    public static function errorSummary($models, $options = [])
    {
        $showAllErrors = ArrayHelper::remove($options, 'showAllErrors', false);
        $lines = self::collectErrors($models, $showAllErrors);

        return implode(PHP_EOL, $lines);
    }

    /**
     * Return array of the validation errors
     * @param Model|Model[] $models the model(s) whose validation errors are to be displayed.
     * @param $showAllErrors boolean, if set to true every error message for each attribute will be shown otherwise
     * only the first error message for each attribute will be shown.
     * @return array of the validation errors
     */
    private static function collectErrors($models, $showAllErrors)
    {
        $lines = [];
        if (!is_array($models)) {
            $models = [$models];
        }

        foreach ($models as $model) {
            $lines = array_unique(array_merge($lines, $model->getErrorSummary($showAllErrors)));
        }

        return $lines;
    }

    /**
     * @return ReadableStreamInterface
     */
    protected static function getStdInStream()
    {
        return \Reaction::create('stdinReadStream');
    }

    /**
     * @return WritableStreamInterface
     */
    protected static function getStdOutStream()
    {
        return \Reaction::create('stdoutWriteStream');
    }
}


<?php

declare(strict_types=1);

namespace Psi\Component\Description\Schema\Extension;

use Psi\Component\Description\Schema\ExtensionInterface;
use Psi\Component\Description\Schema\Builder;
use Psi\Component\Description\Descriptor\UriDescriptor;
use Psi\Component\Description\Descriptor\StringDescriptor;
use Psi\Component\Description\Descriptor\DateTimeDescriptor;
use Psi\Component\Description\Descriptor\ClassDescriptor;

/**
 * Standard descriptors.
 *
 * Provide a list of general, commonly required, descriptors.
 */
class StandardExtension implements ExtensionInterface
{
    /**
     * {@inheritdoc}
     */
    public function buildSchema(Builder $builder)
    {
        $builder->add(
            'class',
            ClassDescriptor::class,
            'Resolved reflection class. Note that this should be the reflection of the *real* class '.
            '(as opposed to that of a proxy if applicable)'
        );
        $builder->add(
            'identifier',
            StringDescriptor::class,
            'Identifier for object (e.g. primary key / UUID)'
        );
        $builder->add('class.alias', StringDescriptor::class, 'Alias for the class');

        $builder->add('title', StringDescriptor::class, 'Title to use for the object instance');
        $builder->add('description', StringDescriptor::class, 'Description of the object');
        $builder->add('image', UriDescriptor::class, 'URL to image');
        $builder->add('created_at', DateTimeDescriptor::class, 'Date this object was created');
        $builder->add('updated_at', DateTimeDescriptor::class, 'Date this object was updated');

        $builder->add('uri.create', UriDescriptor::class, 'Uri to where the object can be created');
        $builder->add('uri.show', UriDescriptor::class, 'Uri to where the object can be shown');
        $builder->add('uri.update', UriDescriptor::class, 'Uri to where the object can be updated');
        $builder->add('uri.delete', UriDescriptor::class, 'Uri to where the object can be deleted');
        $builder->add('uri.list', UriDescriptor::class, 'Uri to where objects of the described objects class are listed');
    }

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


<?php

namespace Versatile\Html;

use Illuminate\Support\ServiceProvider;

use Versatile\Html\Bootstrap\Bootstrap;

class BootstrapServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = true;

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(__DIR__.'/config/config.php', 'html');

        $this->app->singleton('bootstrap', function($app) {
            return new Bootstrap($app['html'], $app['form'], $app['config']);
        });
    }

    /**
     * Boot the service provider.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__.'/config/config.php' => config_path('html.php')
        ], 'config');
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return ['bootstrap'];
    }
}


<?php

namespace Zax\Application\UI;

use Nette;

abstract class Control extends Nette\Application\UI\Control implements IAjaxAware, IHasControlLifeCycle {

	use TControlLifeCycle;
	use TControlMergeLinkParams;
	use TControlAjax;

	/**
	 * @param string $view
	 * @param string $render
	 * @return string
	 */
	static protected function formatTemplatePath($view, $render = '') {
		return 'templates' . DIRECTORY_SEPARATOR . $view . (strlen($render) > 0 ? '.' . $render : '') . '.latte';
	}

	/**
	 * @param string $view
	 * @param string $render
	 * @return string
	 * @throws Nette\InvalidStateException
	 */
	protected function getTemplatePath($view, $render = '') {
		$class = $this->reflection;

		do { // Template inheritance.. kinda..
			$path = dirname($class->fileName) . DIRECTORY_SEPARATOR . self::formatTemplatePath($view, $render);
			if(is_file($path)) {
				return $path;
			}
			$class = $class->getParentClass();
		} while ($class->getName() !== 'Zax\Application\UI\Control');

		$currentClass = get_class($this);
		throw new Nette\InvalidStateException("Template for view '$view' in control '$currentClass' was not found.");
	}

	/**
	 * Life cycle
	 *
	 * @param string $render
	 * @param array $renderParams
	 * @throws Nette\Application\UI\BadSignalException
	 */
	final public function run($render = '', $renderParams = []) {
		$template = $this->getTemplate();
		$template->setFile($this->getTemplatePath($this->view, $render));
		$template->render();
	}

}


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

/**
 * Provides password validation.
 */
class OwpPasswordValidator
{
    /**
     * @var string $tooShortMessage TooShortMessage
     */
    static public $tooShortMessage = 'Your password must be at least {{minlength}} characters long.';

    /**
     * @var string $tooLongMessage TooLongMessage
     */
    static public $tooLongMessage = 'Your password must not exceed {{maxlength}} characters.';

    /**
     * @var string $missingLettersMessage MissingLettersMessage
     */
    static public $missingLettersMessage = 'Your password must include at least one letter.';

    /**
     * @var string $requireCaseDiffMessage RequireCaseDiffMessage
     */
    static public $requireCaseDiffMessage = 'Your password must include both upper and lower case letters.';

    /**
     * @var string $missingNumbersMessage MissingNumbersMessage
     */
    static public $missingNumbersMessage = 'Your password must include at least one digit.';

    /**
     * @var string $missingNonAlphanumericMessage MissingNonAlphanumericMessage
     */
    static public $missingNonAlphanumericMessage = 'Your password must include at least one non-alphanumeric character.';

    /**
     * @var string $minLength MinLength
     */
    static public $minLength = 5;

    /**
     * @var string $maxLength MaxLength
     */
    static public $maxLength = 0;

    /**
     * @var string $requireLetters RequireLetters
     */
    static public $requireLetters = true;

    /**
     * @var string $requireCaseDiff RequireCaseDiff
     */
    static public $requireCaseDiff = false;

    /**
     * @var string $requireNumbers RequireNumbers
     */
    static public $requireNumbers = false;

    /**
     * @var string $requireNonAlphanumeric RequireNonAlphanumeric
     */
    static public $requireNonAlphanumeric = false;

    /**
     * @var string $charset Allowed Characterset
     */
    static public $charset = 'UTF-8';

    /**
     * @var string $violations Violation array
     */
    static public $violations = array();

    /**
     * @var object $constraint Validation constraints
     */
    static public $constraint;

    /**
     * validate
     *
     * @method validate($value, $constraint)
     * @access public
     * @param  string $value      Password value
     * @param  object $constraint Constraints
     * @return mixed Violation array or false if no violations
     *
     * @author  Brian Tafoya
     * @version 1.0
     */
    static public function validate($value, $constraint)
    {
        self::$constraint = $constraint;

        $stringValue = (string) $value;
        if (function_exists('grapheme_strlen') && 'UTF-8' === self::$constraint->charset) {
            $length = grapheme_strlen($stringValue);
        } else if (function_exists('mb_strlen')) {
            $length = mb_strlen($stringValue,  self::$constraint->charset);
        } else {
            $length = strlen($stringValue);
        }

        if(self::$constraint->minLength > 0 && ($length < self::$constraint->minLength))
            self::addViolation(self::$tooShortMessage);
        if($constraint->maxLength > 0 && ($length > self::$constraint->maxLength))
            self::addViolation(self::$tooLongMessage);
        if($constraint->requireLetters && !preg_match('/\pL/', $stringValue))
            self::addViolation(self::$missingLettersMessage);
        if($constraint->requireCaseDiff && !preg_match('/(\p{Ll}+.*\p{Lu})|(\p{Lu}+.*\p{Ll})/', $stringValue))
            self::addViolation(self::$requireCaseDiffMessage);
        if($constraint->requireNumbers && !preg_match('/\pN/', $stringValue))
            self::addViolation(self::$missingNumbersMessage);
        if($constraint->requireNonAlphanumeric && ctype_alnum($stringValue))
            self::addViolation(self::$missingNonAlphanumericMessage);

        return (self::$violations ? self::$violations : false);

    }//end validate()

    /**
     * addViolation
     *
     * @method addViolation($violation)
     * @access private
     * @param  string $violation Violation to record
     *
     * @author  Brian Tafoya
     * @version 1.0
     */
    static private function addViolation($violation)
    {
        self::$violations[] = str_replace(array("{{minlength}}", "{{maxlength}}"), array(self::$constraint->minLength, self::$constraint->maxLength), $violation);

    }//end addViolation()

}//end class


<?php
namespace PlasmaConduit\option;
use PlasmaConduit\either\Left;
use PlasmaConduit\either\Right;
use PlasmaConduit\option\Option;
use Exception;

/**
 * Class None
 *
 * @package PlasmaConduit\option
 */
class None implements Option {

    /**
     * This constructor does absolutely nothing
     */
    public function __construct() { /**/ }

    /**
     * This function is used to signify if the Option type is empty. This is
     * the `None` class and the class type carries this information so this
     * method will always return true.
     *
     * @return bool - Always true
     */
    public function isEmpty() {
        return true;
    }

    /**
     * This function is used to signify if the Option type is not empty. This
     * is the `None` class and the class type carries this information so this
     * method will always return false.
     *
     * @return bool - Always false
     */
    public function nonEmpty() {
        return false;
    }

    /**
     * This method should never be called because you can't get a value from
     * nothing. So this throws unconditionally.
     *
     * @throws Exception
     */
    public function get() {
        throw new Exception("None#get() should never be called");
    }

    /**
     * This function will return the wrapped value if the `Option` type is
     * `Some` and if it's `None` it will return `$default` instead. Seeing how
     * this is the `None` class, this will always return the `$default`
     *
     * @param mixed $default - The default value if no value is present
     * @return mixed         - The `$default` value
     */
    public function getOrElse($default) {
        if (is_callable($default)) {
            return $default();
        } else {
            return $default;
        }
    }

    /**
     * This function takes an alternative `Option` type or a callable and if
     * this `Option` type is `None` it returns the evaluated alternative type.
     * However, this is the `None` class so it will always return
     * the evaluated `$alternative`.
     *
     * @param Callable|Option $alternative - The alternative Option
     * @return Option                      - Always returns `$alternative`
     * @throws Exception
     */
    public function orElse($alternative) {
        if (!is_callable($alternative) && !($alternative instanceof Option)) {
            throw new Exception(
                "Can't call Some#orElse() with non option or callable"
            );
        }

        if ($alternative instanceof Option) {
            return $alternative;
        } else {
            $evaluated = $alternative();
            if (!($evaluated instanceof Option)) {
                throw new Exception(
                    "Result of alternative must return an `Option` type"
                );
            }
            return $evaluated;
        }
    }

    /**
     * For those moments when you just need either a value or null. This
     * function returns the wrapped value when called on the `Some` class and
     * returns null when called on the `None` class. This is the `None` class
     * so it will always return null
     *
     * @return null - Always null
     */
    public function orNull() {
        return null;
    }

    /**
     * This returns the evaluated value of `$right` as a `Right` projection.
     *
     * @param callable|mixed $right - The alternative `Right` value
     * @return Either               - The alternative `Right` value
     */
    public function toLeft($right) {
        if (is_callable($right)) {
            return new Right($right());
        } else {
            return new Right($right);
        }
    }

    /**
     * This returns the evaluated value of `$left` as a `Left` projection.
     *
     * @param Callable|mixed $left - The alternative `Left` value
     * @return Either               - The alternative `Left` value
     */
    public function toRight($left) {
        if (is_callable($left)) {
            return new Left($left());
        } else {
            return new Left($left);
        }
    }

    /**
     * This method takes a callable type (closure, function, etc) and if it's
     * called on a `Some` instance it will call the function `$mapper` with the
     * wrapped value and the value returend by `$mapper` will be wrapped in a
     * new `Some` container and that new `Some` container will be returned. If
     * this is called on a `None` container, the function `$mapper` will never
     * be called and instead we return `None` immediately. This is the `None`
     * class, so it will never call the `$mapper` and will return `None`
     * immediately.
     *
     * @param Callable $mapper - Function to disregard
     * @return Option          - Always `None`
     * @throws Exception
     */
    public function map($mapper) {
        if (!is_callable($mapper)) {
            throw new Exception("Can't call Some#map with a non callable.");
        }
        return $this;
    }

    /**
     * This takes a callable and completely disregards it, returning `None`
     * immediately.
     *
     * @param Callable $flatMapper
     * @return $this|Option
     * @throws \Exception
     */
    public function flatMap($flatMapper) {
        if (!is_callable($flatMapper)) {
            throw new Exception("Can't call Some#flatMap with a non callable.");
        }
        return $this;
    }

    /**
     * This function takes a callable as a predicate, disregards it and returns
     * `None` immediately
     *
     * @param Callable $predicate
     * @return $this|Option
     * @throws \Exception
     */
    public function filter($predicate) {
        if (!is_callable($predicate)) {
            throw new Exception("Can't call Some#filter with a non callable.");
        }
        return $this;
    }

}


<?php
namespace Nubs\Which\PathBuilder;

/**
 * Appends filenames to an array of paths.
 */
trait FileAppenderTrait
{
    /**
     * Append the filename to the array of paths.
     *
     * @param array $paths The paths to append to.
     * @param string $file The filename.
     * @return array The paths with the file name appended.
     */
    protected function _appendFileToPaths(array $paths, $file)
    {
        if (!$this->_isAtom($file)) {
            return [$file];
        }

        $appendFile = function($path) use($file) {
            return $this->_joinPaths($path, $file);
        };

        return array_map($appendFile, $paths);
    }

    /**
     * Joins two path segments together.
     *
     * @param string $start The starting segment.
     * @param string $end The ending segment.
     * @return string The joined segments.
     */
    abstract protected function _joinPaths($start, $end);

    /**
     * Checks to see if a path is just a single atom (no directory).
     *
     * @param string $path The path to check.
     * @return boolean True if it's an atom, false otherwise.
     */
    abstract protected function _isAtom($path);
}


<?php

namespace Reaction\Db\Pgsql;

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

/**
 * Class Database
 * @package Reaction\Db\Pgsql
 * @property pgClient $pgClient
 */
class Database extends \Reaction\Db\Database
{
    /**
     * @var array Schema, QueryBuilder, ColumnSchema and Command classes config
     */
    public $componentsConfig = [
        'Reaction\Db\SchemaInterface' => 'Reaction\Db\Pgsql\Schema',
        'Reaction\Db\QueryBuilderInterface' => 'Reaction\Db\Pgsql\QueryBuilder',
        'Reaction\Db\ColumnSchemaInterface' => 'Reaction\Db\Pgsql\ColumnSchema',
        'Reaction\Db\ConnectionInterface' => 'Reaction\Db\Pgsql\Connection',
    ];

    /**
     * @var bool Enable savepoint support
     */
    public $enableSavepoint = true;

    /** @var \PgAsync\Client */
    protected $_pgClient;

    /**
     * Get DB driver name
     * @return string
     */
    public function getDriverName() {
        return 'pgsql';
    }

    /**
     * Get PgClient instance
     * @return PgClient
     */
    protected function getPgClient() {
        if (!isset($this->_pgClient)) {
            $config = [
                'dbCredentials' => [
                    'host' => $this->host,
                    'port' => $this->port,
                    'user' => $this->username,
                    'password' => $this->password,
                    'database' => $this->database,
                ],
                //'autoDisconnect' => true,
                //'maxConnections' => 5,
                'loop' => Reaction::$app->loop
            ];
            $this->_pgClient = new PgClient($config);
        }
        return $this->_pgClient;
    }

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

    /**
     * Get dedicated connection (Not used in shared pool)
     * @return ConnectionInterface
     */
    public function getDedicatedConnection() {
        $config = [
            'pgConnection' => $this->getPgClient()->getDedicatedConnection(false),
        ];
        return $this->createComponent(ConnectionInterface::class, $config);
    }

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


<?php

/*
 * 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\HttpMessage;

use InvalidArgumentException;
use RuntimeException;

/**
 * Value object representing a file uploaded through an HTTP request.
 *
 * Instances of this interface are considered immutable; all methods that
 * might change state MUST be implemented such that they retain the internal
 * state of the current instance and return an instance that contains the
 * changed state.
 *
 * @author Melech Mizrachi
 */
class NativeUploadedFile implements UploadedFile
{
    /**
     * The uploaded file.
     *
     * @var string
     */
    protected $file;

    /**
     * The uploaded file as a stream.
     *
     * @var \Valkyrja\HttpMessage\Stream
     */
    protected $stream;

    /**
     * THe uploaded file size.
     *
     * @var int
     */
    protected $size;

    /**
     * The error status. One of UPLOAD_ERR_* constant.
     *
     * @var int
     */
    protected $errorStatus;

    /**
     * The uploaded file's name.
     *
     * @var string
     */
    protected $fileName;

    /**
     * The uploaded file's media type.
     *
     * @var string
     */
    protected $mediaType;

    /**
     * Whether the file has been moved yet.
     *
     * @var bool
     */
    protected $moved = false;

    /**
     * NativeUploadedFile constructor.
     *
     * @param int    $size        The file size
     * @param int    $errorStatus The error status
     * @param string $file        [optional] The file
     * @param Stream $stream      [optional] The stream
     * @param string $fileName    [optional] The file name
     * @param string $mediaType   [optional] The file media type
     *
     * @throws \InvalidArgumentException
     */
    public function __construct(
        int $size,
        int $errorStatus,
        string $file = null,
        Stream $stream = null,
        string $fileName = null,
        string $mediaType = null
    ) {
        // If the error is less than the lowest valued UPLOAD_ERR_* constant
        // Or the error is greater than the highest valued UPLOAD_ERR_* constant
        if (
            UPLOAD_ERR_OK > $errorStatus
            || $errorStatus > UPLOAD_ERR_EXTENSION
        ) {
            // Throw an invalid argument exception for the error status
            throw new InvalidArgumentException(
                'Invalid error status for UploadedFile;'
                . ' must be an UPLOAD_ERR_* constant value.'
            );
        }

        // If the file is not set
        // and the stream is not set
        if (null === $file && null === $stream) {
            // Throw an invalid argument exception as on or the other
            // is required
            throw new InvalidArgumentException(
                'Either one of file or stream are required.'
                . ' Neither passed as arguments.'
            );
        }

        $this->file        = $file;
        $this->size        = $size;
        $this->errorStatus = $errorStatus;
        $this->stream      = $stream;
        $this->fileName    = $fileName;
        $this->mediaType   = $mediaType;
    }

    /**
     * Retrieve a stream representing the uploaded file.
     *
     * This method MUST return a StreamInterface instance, representing the
     * uploaded file. The purpose of this method is to allow utilizing native
     * PHP stream functionality to manipulate the file upload, such as
     * stream_copy_to_stream() (though the result will need to be decorated in
     * a native PHP stream wrapper to work with such functions).
     *
     * If the moveTo() method has been called previously, this method MUST
     * raise an exception.
     *
     * @throws \RuntimeException in cases when no stream is available or can
     *          be created.
     * @throws \Valkyrja\HttpMessage\Exceptions\InvalidStream
     *
     * @return \Valkyrja\HttpMessage\Stream Stream representation of the
     *          uploaded file.
     */
    public function getStream(): Stream
    {
        // If the error status is not OK
        if (UPLOAD_ERR_OK !== $this->errorStatus) {
            // Throw a runtime exception as there's been an uploaded file error
            throw new RuntimeException(
                'Cannot retrieve stream due to upload error'
            );
        }

        // If the file has already been moved
        if ($this->moved) {
            // Throw a runtime exception as subsequent moves are not allowed
            // in PSR-7
            throw new RuntimeException(
                'Cannot retrieve stream after it has already been moved'
            );
        }

        // If the stream has been set
        if (null !== $this->stream) {
            // Return the stream
            return $this->stream;
        }

        // Set the stream as a new native stream
        $this->stream = new NativeStream($this->file);

        return $this->stream;
    }

    /**
     * Move the uploaded file to a new location.
     *
     * Use this method as an alternative to move_uploaded_file(). This method
     * is
     * guaranteed to work in both SAPI and non-SAPI environments.
     * Implementations must determine which environment they are in, and use
     * the appropriate method (move_uploaded_file(), rename(), or a stream
     * operation) to perform the operation.
     *
     * $targetPath may be an absolute path, or a relative path. If it is a
     * relative path, resolution should be the same as used by PHP's rename()
     * function.
     *
     * The original file or stream MUST be removed on completion.
     *
     * If this method is called more than once, any subsequent calls MUST raise
     * an exception.
     *
     * When used in an SAPI environment where $_FILES is populated, when
     * writing files via moveTo(), is_uploaded_file() and
     * move_uploaded_file() SHOULD be used to ensure permissions and upload
     * status are verified correctly.
     *
     * If you wish to move to a stream, use getStream(), as SAPI operations
     * cannot guarantee writing to stream destinations.
     *
     * @see http://php.net/is_uploaded_file
     * @see http://php.net/move_uploaded_file
     *
     * @param string $targetPath Path to which to move the uploaded file.
     *
     * @throws \InvalidArgumentException if the $targetPath specified is
     *          invalid.
     * @throws \RuntimeException on any error during the move operation, or
     *          on the second or subsequent call to the method.
     * @throws \Valkyrja\HttpMessage\Exceptions\InvalidStream
     *
     * @return void
     */
    public function moveTo(string $targetPath): void
    {
        // If the error status is not OK
        if (UPLOAD_ERR_OK !== $this->errorStatus) {
            // Throw a runtime exception as there's been an uploaded file error
            throw new RuntimeException(
                'Cannot retrieve stream due to upload error'
            );
        }

        // If the file has already been moved
        if ($this->moved) {
            // Throw a runtime exception as subsequent moves are not allowed
            // in PSR-7
            throw new RuntimeException(
                'Cannot move file after it has already been moved'
            );
        }

        $targetDirectory = \dirname($targetPath);

        // If the target directory is not a directory
        // or the target directory is not writable
        if (! is_dir($targetDirectory) || ! is_writable($targetDirectory)) {
            // Throw a runtime exception
            throw new RuntimeException(
                sprintf(
                    'The target directory `%s` does not exists '
                    . 'or is not writable',
                    $targetDirectory
                )
            );
        }

        $sapi = PHP_SAPI;

        // If the PHP_SAPI value is empty
        // or there is no file
        // or the PHP_SAPI value is set to a CLI environment
        if (
            empty($sapi)
            || ! $this->file
            || 0 === strpos($sapi, 'cli')
        ) {
            // Non-SAPI environment, or no filename present
            $this->writeStream($targetPath);
        }
        // Otherwise try to use the move_uploaded_file function
        // and if the move_uploaded_file function call failed
        elseif (false === move_uploaded_file($this->file, $targetPath)) {
            // Throw a runtime exception
            throw new RuntimeException(
                'Error occurred while moving uploaded file'
            );
        }

        $this->moved = true;
    }

    /**
     * Retrieve the file size.
     *
     * Implementations SHOULD return the value stored in the "size" key of
     * the file in the $_FILES array if available, as PHP calculates this based
     * on the actual size transmitted.
     *
     * @return int|null The file size in bytes or null if unknown.
     */
    public function getSize(): ? int
    {
        return $this->size;
    }

    /**
     * Retrieve the error associated with the uploaded file.
     *
     * The return value MUST be one of PHP's UPLOAD_ERR_XXX constants.
     *
     * If the file was uploaded successfully, this method MUST return
     * UPLOAD_ERR_OK.
     *
     * Implementations SHOULD return the value stored in the "error" key of
     * the file in the $_FILES array.
     *
     * @see http://php.net/manual/en/features.file-upload.errors.php
     *
     * @return int One of PHP's UPLOAD_ERR_XXX constants.
     */
    public function getError(): int
    {
        return $this->errorStatus;
    }

    /**
     * Retrieve the filename sent by the client.
     *
     * Do not trust the value returned by this method. A client could send
     * a malicious filename with the intention to corrupt or hack your
     * application.
     *
     * Implementations SHOULD return the value stored in the "name" key of
     * the file in the $_FILES array.
     *
     * @return string|null The filename sent by the client or null if none was
     *          provided.
     */
    public function getClientFilename(): ? string
    {
        return $this->fileName;
    }

    /**
     * Retrieve the media type sent by the client.
     *
     * Do not trust the value returned by this method. A client could send
     * a malicious media type with the intention to corrupt or hack your
     * application.
     *
     * Implementations SHOULD return the value stored in the "type" key of
     * the file in the $_FILES array.
     *
     * @return string|null The media type sent by the client or null if none
     *          was provided.
     */
    public function getClientMediaType(): ? string
    {
        return $this->mediaType;
    }

    /**
     * Write the stream to a path.
     *
     * @param string $path The path to write the stream to
     *
     * @throws \RuntimeException
     * @throws \Valkyrja\HttpMessage\Exceptions\InvalidStream
     *
     * @return void
     */
    protected function writeStream(string $path): void
    {
        // Attempt to open the path specified
        $handle = fopen($path, 'wb+');

        // If the handler failed to open
        if (false === $handle) {
            // Throw a runtime exception
            throw new RuntimeException(
                'Unable to write to designated path'
            );
        }

        // Get the stream
        $stream = $this->getStream();
        // Rewind the stream
        $stream->rewind();

        // While the end of file hasn't been reached
        while (! $stream->eof()) {
            // Write the stream's contents to the handler
            fwrite($handle, $stream->read(4096));
        }

        // Close the file path
        fclose($handle);
    }
}


<?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\HttpMessage;

use InvalidArgumentException;
use stdClass;
use UnexpectedValueException;
use Valkyrja\Http\RequestMethod;

/**
 * Class ServerRequestFactory.
 *
 * @author Melech Mizrachi
 */
abstract class ServerRequestFactory
{
    /**
     * Function to use to get apache request headers; present only to simplify mocking.
     *
     * @var callable
     */
    private static $apacheRequestHeaders = 'apache_request_headers';

    /**
     * Create a request from the supplied superglobal values.
     *
     * If any argument is not supplied, the corresponding superglobal value will
     * be used.
     *
     * The ServerRequest created is then passed to the fromServer() method in
     * order to marshal the request URI and headers.
     *
     * @see fromServer()
     *
     * @param array $server  $_SERVER superglobal
     * @param array $query   $_GET superglobal
     * @param array $body    $_POST superglobal
     * @param array $cookies $_COOKIE superglobal
     * @param array $files   $_FILES superglobal
     *
     * @throws \InvalidArgumentException
     * @throws \UnexpectedValueException
     * @throws \Valkyrja\HttpMessage\Exceptions\InvalidUploadedFile
     * @throws \Valkyrja\HttpMessage\Exceptions\InvalidStream
     * @throws \Valkyrja\HttpMessage\Exceptions\InvalidScheme
     * @throws \Valkyrja\HttpMessage\Exceptions\InvalidQuery
     * @throws \Valkyrja\HttpMessage\Exceptions\InvalidProtocolVersion
     * @throws \Valkyrja\HttpMessage\Exceptions\InvalidPort
     * @throws \Valkyrja\HttpMessage\Exceptions\InvalidPath
     * @throws \Valkyrja\HttpMessage\Exceptions\InvalidMethod
     *
     * @return ServerRequest
     */
    public static function fromGlobals(
        array $server = null,
        array $query = null,
        array $body = null,
        array $cookies = null,
        array $files = null
    ): ServerRequest {
        $server  = static::normalizeServer($server ?: $_SERVER);
        $files   = static::normalizeFiles($files ?: $_FILES);
        $headers = static::marshalHeaders($server);

        if (null === $cookies && array_key_exists('cookie', $headers)) {
            $cookies = self::parseCookieHeader($headers['cookie']);
        }

        return new NativeServerRequest(
            static::marshalUriFromServer($server, $headers),
            static::get('REQUEST_METHOD', $server, RequestMethod::GET),
            new NativeStream('php://input'),
            $headers,
            $server,
            $cookies ?? $_COOKIE,
            $query ?? $_GET,
            $body ?? $_POST,
            $files,
            static::marshalProtocolVersion($server)
        );
    }

    /**
     * Access a value in an array, returning a default value if not found.
     *
     * Will also do a case-insensitive search if a case sensitive search fails.
     *
     * @param string $key
     * @param array  $values
     * @param mixed  $default
     *
     * @return mixed
     */
    public static function get($key, array $values, $default = null)
    {
        if (array_key_exists($key, $values)) {
            return $values[$key];
        }

        return $default;
    }

    /**
     * Search for a header value.
     *
     * Does a case-insensitive search for a matching header.
     *
     * If found, it is returned as a string, using comma concatenation.
     *
     * If not, the $default is returned.
     *
     * @param string $header
     * @param array  $headers
     * @param mixed  $default
     *
     * @return string
     */
    public static function getHeader(string $header, array $headers, $default = null): string
    {
        $header  = strtolower($header);
        $headers = array_change_key_case($headers, CASE_LOWER);
        if (array_key_exists($header, $headers)) {
            $value = \is_array($headers[$header]) ? implode(', ', $headers[$header]) : $headers[$header];

            return $value;
        }

        return $default;
    }

    /**
     * Marshal the $_SERVER array.
     *
     * Pre-processes and returns the $_SERVER superglobal.
     *
     * @param array $server
     *
     * @return array
     */
    public static function normalizeServer(array $server): array
    {
        // This seems to be the only way to get the Authorization header on Apache
        $apacheRequestHeaders = self::$apacheRequestHeaders;

        if (isset($server['HTTP_AUTHORIZATION'])
            || ! \is_callable($apacheRequestHeaders)
        ) {
            return $server;
        }

        $apacheRequestHeaders = $apacheRequestHeaders();

        if (isset($apacheRequestHeaders['Authorization'])) {
            $server['HTTP_AUTHORIZATION'] = $apacheRequestHeaders['Authorization'];

            return $server;
        }

        if (isset($apacheRequestHeaders['authorization'])) {
            $server['HTTP_AUTHORIZATION'] = $apacheRequestHeaders['authorization'];

            return $server;
        }

        return $server;
    }

    /**
     * Normalize uploaded files.
     *
     * Transforms each value into an UploadedFileInterface instance, and ensures
     * that nested arrays are normalized.
     *
     * @param array $files
     *
     * @throws InvalidArgumentException for unrecognized values
     *
     * @return array
     */
    public static function normalizeFiles(array $files): array
    {
        $normalized = [];
        foreach ($files as $key => $value) {
            if ($value instanceof UploadedFile) {
                $normalized[$key] = $value;
                continue;
            }

            if (\is_array($value) && isset($value['tmp_name'])) {
                $normalized[$key] = self::createUploadedFileFromSpec($value);
                continue;
            }

            if (\is_array($value)) {
                $normalized[$key] = self::normalizeFiles($value);
                continue;
            }

            throw new InvalidArgumentException('Invalid value in files specification');
        }

        return $normalized;
    }

    /**
     * Marshal headers from $_SERVER.
     *
     * @param array $server
     *
     * @return array
     */
    public static function marshalHeaders(array $server): array
    {
        $headers = [];
        foreach ($server as $key => $value) {
            // Apache prefixes environment variables with REDIRECT_
            // if they are added by rewrite rules
            if (strpos($key, 'REDIRECT_') === 0) {
                $key = substr($key, 9);

                // We will not overwrite existing variables with the
                // prefixed versions, though
                if (array_key_exists($key, $server)) {
                    continue;
                }
            }

            if ($value && strpos($key, 'HTTP_') === 0) {
                $name           = str_replace('_', '-', strtolower(substr($key, 5)));
                $headers[$name] = $value;
                continue;
            }

            if ($value && strpos($key, 'CONTENT_') === 0) {
                $name           = 'content-' . strtolower(substr($key, 8));
                $headers[$name] = $value;
            }
        }

        return $headers;
    }

    /**
     * Marshal the URI from the $_SERVER array and headers.
     *
     * @param array $server
     * @param array $headers
     *
     * @throws \Valkyrja\HttpMessage\Exceptions\InvalidScheme
     * @throws \Valkyrja\HttpMessage\Exceptions\InvalidQuery
     * @throws \Valkyrja\HttpMessage\Exceptions\InvalidPort
     * @throws \Valkyrja\HttpMessage\Exceptions\InvalidPath
     *
     * @return Uri
     */
    public static function marshalUriFromServer(array $server, array $headers): Uri
    {
        $uri = new NativeUri();

        // URI scheme
        $scheme = 'http';
        $https  = self::get('HTTPS', $server);

        if (($https && 'off' !== $https)
            || self::getHeader('x-forwarded-proto', $headers, false) === 'https'
        ) {
            $scheme = 'https';
        }

        if (! empty($scheme)) {
            $uri = $uri->withScheme($scheme);
        }

        // Set the host
        $accumulator = (object) ['host' => '', 'port' => null];

        self::marshalHostAndPortFromHeaders($accumulator, $server, $headers);

        $host = $accumulator->host;
        $port = $accumulator->port;

        if (! empty($host)) {
            $uri = $uri->withHost($host);

            if (! empty($port)) {
                $uri = $uri->withPort($port);
            }
        }

        // URI path
        $path = self::marshalRequestUri($server);
        $path = self::stripQueryString($path);

        // URI query
        $query = '';

        if (isset($server['QUERY_STRING'])) {
            $query = ltrim($server['QUERY_STRING'], '?');
        }

        // URI fragment
        $fragment = '';

        if (strpos($path, '#') !== false) {
            [$path, $fragment] = explode('#', $path, 2);
        }

        return $uri
            ->withPath($path)
            ->withFragment($fragment)
            ->withQuery($query);
    }

    /**
     * Marshal the host and port from HTTP headers and/or the PHP environment.
     *
     * @param stdClass $accumulator
     * @param array    $server
     * @param array    $headers
     *
     * @return void
     */
    public static function marshalHostAndPortFromHeaders(stdClass $accumulator, array $server, array $headers): void
    {
        if (self::getHeader('host', $headers, false)) {
            self::marshalHostAndPortFromHeader($accumulator, self::getHeader('host', $headers));

            return;
        }

        if (! isset($server['SERVER_NAME'])) {
            return;
        }

        $accumulator->host = $server['SERVER_NAME'];

        if (isset($server['SERVER_PORT'])) {
            $accumulator->port = (int) $server['SERVER_PORT'];
        }

        if (! isset($server['SERVER_ADDR']) || ! preg_match('/^\[[0-9a-fA-F\:]+\]$/', $accumulator->host)) {
            return;
        }

        // Misinterpreted IPv6-Address
        // Reported for Safari on Windows
        self::marshalIpv6HostAndPort($accumulator, $server);
    }

    /**
     * Detect the base URI for the request.
     *
     * Looks at a variety of criteria in order to attempt to autodetect a base
     * URI, including rewrite URIs, proxy URIs, etc.
     *
     * From ZF2's Zend\Http\PhpEnvironment\Request class
     *
     * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
     * @license   http://framework.zend.com/license/new-bsd New BSD License
     *
     * @param array $server
     *
     * @return string
     */
    public static function marshalRequestUri(array $server): string
    {
        // IIS7 with URL Rewrite: make sure we get the unencoded url
        // (double slash problem).
        $iisUrlRewritten = self::get('IIS_WasUrlRewritten', $server);
        $unencodedUrl    = self::get('UNENCODED_URL', $server, '');

        if ('1' === $iisUrlRewritten && ! empty($unencodedUrl)) {
            return $unencodedUrl;
        }

        $requestUri = self::get('REQUEST_URI', $server);

        // Check this first so IIS will catch.
        $httpXRewriteUrl = self::get('HTTP_X_REWRITE_URL', $server);

        if ($httpXRewriteUrl !== null) {
            $requestUri = $httpXRewriteUrl;
        }

        // Check for IIS 7.0 or later with ISAPI_Rewrite
        $httpXOriginalUrl = self::get('HTTP_X_ORIGINAL_URL', $server);

        if ($httpXOriginalUrl !== null) {
            $requestUri = $httpXOriginalUrl;
        }

        if ($requestUri !== null) {
            return preg_replace('#^[^/:]+://[^/]+#', '', $requestUri);
        }

        $origPathInfo = self::get('ORIG_PATH_INFO', $server);

        if (empty($origPathInfo)) {
            return '/';
        }

        return $origPathInfo;
    }

    /**
     * Strip the query string from a path.
     *
     * @param string $path
     *
     * @return string
     */
    public static function stripQueryString(string $path): string
    {
        if (($queryPos = strpos($path, '?')) !== false) {
            return substr($path, 0, $queryPos);
        }

        return $path;
    }

    /**
     * Marshal the host and port from the request header.
     *
     * @param stdClass     $accumulator
     * @param string|array $host
     *
     * @return void
     */
    private static function marshalHostAndPortFromHeader(stdClass $accumulator, $host): void
    {
        if (\is_array($host)) {
            $host = implode(', ', $host);
        }

        $accumulator->host = $host;
        $accumulator->port = null;

        // Works for regname, IPv4 & IPv6
        if (preg_match('|\:(\d+)$|', $accumulator->host, $matches)) {
            $accumulator->host = substr($accumulator->host, 0, -1 * (\strlen($matches[1]) + 1));
            $accumulator->port = (int) $matches[1];
        }
    }

    /**
     * Marshal host/port from misinterpreted IPv6 address.
     *
     * @param stdClass $accumulator
     * @param array    $server
     *
     * @return void
     */
    private static function marshalIpv6HostAndPort(stdClass $accumulator, array $server): void
    {
        $accumulator->host = '[' . $server['SERVER_ADDR'] . ']';
        $accumulator->port = $accumulator->port ?: 80;

        if ($accumulator->port . ']' === substr($accumulator->host, strrpos($accumulator->host, ':') + 1)) {
            // The last digit of the IPv6-Address has been taken as port
            // Unset the port so the default port can be used
            $accumulator->port = null;
        }
    }

    /**
     * Create and return an UploadedFile instance from a $_FILES specification.
     *
     * If the specification represents an array of values, this method will
     * delegate to normalizeNestedFileSpec() and return that return value.
     *
     * @param array $value $_FILES struct
     *
     * @throws \InvalidArgumentException
     *
     * @return array|UploadedFile
     */
    private static function createUploadedFileFromSpec(array $value)
    {
        if (\is_array($value['tmp_name'])) {
            return self::normalizeNestedFileSpec($value);
        }

        return new NativeUploadedFile(
            $value['size'],
            $value['error'],
            $value['tmp_name'],
            null,
            $value['name'],
            $value['type']
        );
    }

    /**
     * Normalize an array of file specifications.
     *
     * Loops through all nested files and returns a normalized array of
     * UploadedFileInterface instances.
     *
     * @param array $files
     *
     * @throws \InvalidArgumentException
     *
     * @return UploadedFile[]
     */
    private static function normalizeNestedFileSpec(array $files = []): array
    {
        $normalizedFiles = [];

        foreach (array_keys($files['tmp_name']) as $key) {
            $spec                  = [
                'tmp_name' => $files['tmp_name'][$key],
                'size'     => $files['size'][$key],
                'error'    => $files['error'][$key],
                'name'     => $files['name'][$key],
                'type'     => $files['type'][$key],
            ];
            $normalizedFiles[$key] = self::createUploadedFileFromSpec($spec);
        }

        return $normalizedFiles;
    }

    /**
     * Return HTTP protocol version (X.Y).
     *
     * @param array $server
     *
     * @throws \UnexpectedValueException
     *
     * @return string
     */
    private static function marshalProtocolVersion(array $server): string
    {
        if (! isset($server['SERVER_PROTOCOL'])) {
            return '1.1';
        }

        if (! preg_match('#^(HTTP/)?(?P<version>[1-9]\d*(?:\.\d)?)$#', $server['SERVER_PROTOCOL'], $matches)) {
            throw new UnexpectedValueException(
                sprintf(
                    'Unrecognized protocol version (%s)',
                    $server['SERVER_PROTOCOL']
                )
            );
        }

        return $matches['version'];
    }

    /**
     * Parse a cookie header according to RFC 6265.
     *
     * PHP will replace special characters in cookie names, which results in other cookies not being available due to
     * overwriting. Thus, the server request should take the cookies from the request header instead.
     *
     * @param string $cookieHeader
     *
     * @return array
     */
    private static function parseCookieHeader(string $cookieHeader): array
    {
        preg_match_all(
            '(
            (?:^\\n?[ \t]*|;[ ])
            (?P<name>[!#$%&\'*+-.0-9A-Z^_`a-z|~]+)
            =
            (?P<DQUOTE>"?)
                (?P<value>[\x21\x23-\x2b\x2d-\x3a\x3c-\x5b\x5d-\x7e]*)
            (?P=DQUOTE)
            (?=\\n?[ \t]*$|;[ ])
        )x',
            $cookieHeader,
            $matches,
            PREG_SET_ORDER
        );

        $cookies = [];

        /** @var array $matches */
        foreach ($matches as $match) {
            $cookies[$match['name']] = urldecode($match['value']);
        }

        return $cookies;
    }
}