<?php

namespace PhpOffice\PhpSpreadsheet\Shared;

use PhpOffice\PhpSpreadsheet\Calculation\Calculation;

class StringHelper
{
    /**    Constants                */
    /**    Regular Expressions        */
    //    Fraction
    const STRING_REGEXP_FRACTION = '(-?)(\d+)\s+(\d+\/\d+)';

    /**
     * Control characters array.
     *
     * @var string[]
     */
    private static $controlCharacters = [];

    /**
     * SYLK Characters array.
     *
     * @var array
     */
    private static $SYLKCharacters = [];

    /**
     * Decimal separator.
     *
     * @var string
     */
    private static $decimalSeparator;

    /**
     * Thousands separator.
     *
     * @var string
     */
    private static $thousandsSeparator;

    /**
     * Currency code.
     *
     * @var string
     */
    private static $currencyCode;

    /**
     * Is iconv extension avalable?
     *
     * @var bool
     */
    private static $isIconvEnabled;

    /**
     * Build control characters array.
     */
    private static function buildControlCharacters()
    {
        for ($i = 0; $i <= 31; ++$i) {
            if ($i != 9 && $i != 10 && $i != 13) {
                $find = '_x' . sprintf('%04s', strtoupper(dechex($i))) . '_';
                $replace = chr($i);
                self::$controlCharacters[$find] = $replace;
            }
        }
    }

    /**
     * Build SYLK characters array.
     */
    private static function buildSYLKCharacters()
    {
        self::$SYLKCharacters = [
            "\x1B 0" => chr(0),
            "\x1B 1" => chr(1),
            "\x1B 2" => chr(2),
            "\x1B 3" => chr(3),
            "\x1B 4" => chr(4),
            "\x1B 5" => chr(5),
            "\x1B 6" => chr(6),
            "\x1B 7" => chr(7),
            "\x1B 8" => chr(8),
            "\x1B 9" => chr(9),
            "\x1B :" => chr(10),
            "\x1B ;" => chr(11),
            "\x1B <" => chr(12),
            "\x1B =" => chr(13),
            "\x1B >" => chr(14),
            "\x1B ?" => chr(15),
            "\x1B!0" => chr(16),
            "\x1B!1" => chr(17),
            "\x1B!2" => chr(18),
            "\x1B!3" => chr(19),
            "\x1B!4" => chr(20),
            "\x1B!5" => chr(21),
            "\x1B!6" => chr(22),
            "\x1B!7" => chr(23),
            "\x1B!8" => chr(24),
            "\x1B!9" => chr(25),
            "\x1B!:" => chr(26),
            "\x1B!;" => chr(27),
            "\x1B!<" => chr(28),
            "\x1B!=" => chr(29),
            "\x1B!>" => chr(30),
            "\x1B!?" => chr(31),
            "\x1B'?" => chr(127),
            "\x1B(0" => '€', // 128 in CP1252
            "\x1B(2" => '‚', // 130 in CP1252
            "\x1B(3" => 'ƒ', // 131 in CP1252
            "\x1B(4" => '„', // 132 in CP1252
            "\x1B(5" => '…', // 133 in CP1252
            "\x1B(6" => '†', // 134 in CP1252
            "\x1B(7" => '‡', // 135 in CP1252
            "\x1B(8" => 'ˆ', // 136 in CP1252
            "\x1B(9" => '‰', // 137 in CP1252
            "\x1B(:" => 'Š', // 138 in CP1252
            "\x1B(;" => '‹', // 139 in CP1252
            "\x1BNj" => 'Œ', // 140 in CP1252
            "\x1B(>" => 'Ž', // 142 in CP1252
            "\x1B)1" => '‘', // 145 in CP1252
            "\x1B)2" => '’', // 146 in CP1252
            "\x1B)3" => '“', // 147 in CP1252
            "\x1B)4" => '”', // 148 in CP1252
            "\x1B)5" => '•', // 149 in CP1252
            "\x1B)6" => '–', // 150 in CP1252
            "\x1B)7" => '—', // 151 in CP1252
            "\x1B)8" => '˜', // 152 in CP1252
            "\x1B)9" => '™', // 153 in CP1252
            "\x1B):" => 'š', // 154 in CP1252
            "\x1B);" => '›', // 155 in CP1252
            "\x1BNz" => 'œ', // 156 in CP1252
            "\x1B)>" => 'ž', // 158 in CP1252
            "\x1B)?" => 'Ÿ', // 159 in CP1252
            "\x1B*0" => ' ', // 160 in CP1252
            "\x1BN!" => '¡', // 161 in CP1252
            "\x1BN\"" => '¢', // 162 in CP1252
            "\x1BN#" => '£', // 163 in CP1252
            "\x1BN(" => '¤', // 164 in CP1252
            "\x1BN%" => '¥', // 165 in CP1252
            "\x1B*6" => '¦', // 166 in CP1252
            "\x1BN'" => '§', // 167 in CP1252
            "\x1BNH " => '¨', // 168 in CP1252
            "\x1BNS" => '©', // 169 in CP1252
            "\x1BNc" => 'ª', // 170 in CP1252
            "\x1BN+" => '«', // 171 in CP1252
            "\x1B*<" => '¬', // 172 in CP1252
            "\x1B*=" => '', // 173 in CP1252
            "\x1BNR" => '®', // 174 in CP1252
            "\x1B*?" => '¯', // 175 in CP1252
            "\x1BN0" => '°', // 176 in CP1252
            "\x1BN1" => '±', // 177 in CP1252
            "\x1BN2" => '²', // 178 in CP1252
            "\x1BN3" => '³', // 179 in CP1252
            "\x1BNB " => '´', // 180 in CP1252
            "\x1BN5" => 'µ', // 181 in CP1252
            "\x1BN6" => '¶', // 182 in CP1252
            "\x1BN7" => '·', // 183 in CP1252
            "\x1B+8" => '¸', // 184 in CP1252
            "\x1BNQ" => '¹', // 185 in CP1252
            "\x1BNk" => 'º', // 186 in CP1252
            "\x1BN;" => '»', // 187 in CP1252
            "\x1BN<" => '¼', // 188 in CP1252
            "\x1BN=" => '½', // 189 in CP1252
            "\x1BN>" => '¾', // 190 in CP1252
            "\x1BN?" => '¿', // 191 in CP1252
            "\x1BNAA" => 'À', // 192 in CP1252
            "\x1BNBA" => 'Á', // 193 in CP1252
            "\x1BNCA" => 'Â', // 194 in CP1252
            "\x1BNDA" => 'Ã', // 195 in CP1252
            "\x1BNHA" => 'Ä', // 196 in CP1252
            "\x1BNJA" => 'Å', // 197 in CP1252
            "\x1BNa" => 'Æ', // 198 in CP1252
            "\x1BNKC" => 'Ç', // 199 in CP1252
            "\x1BNAE" => 'È', // 200 in CP1252
            "\x1BNBE" => 'É', // 201 in CP1252
            "\x1BNCE" => 'Ê', // 202 in CP1252
            "\x1BNHE" => 'Ë', // 203 in CP1252
            "\x1BNAI" => 'Ì', // 204 in CP1252
            "\x1BNBI" => 'Í', // 205 in CP1252
            "\x1BNCI" => 'Î', // 206 in CP1252
            "\x1BNHI" => 'Ï', // 207 in CP1252
            "\x1BNb" => 'Ð', // 208 in CP1252
            "\x1BNDN" => 'Ñ', // 209 in CP1252
            "\x1BNAO" => 'Ò', // 210 in CP1252
            "\x1BNBO" => 'Ó', // 211 in CP1252
            "\x1BNCO" => 'Ô', // 212 in CP1252
            "\x1BNDO" => 'Õ', // 213 in CP1252
            "\x1BNHO" => 'Ö', // 214 in CP1252
            "\x1B-7" => '×', // 215 in CP1252
            "\x1BNi" => 'Ø', // 216 in CP1252
            "\x1BNAU" => 'Ù', // 217 in CP1252
            "\x1BNBU" => 'Ú', // 218 in CP1252
            "\x1BNCU" => 'Û', // 219 in CP1252
            "\x1BNHU" => 'Ü', // 220 in CP1252
            "\x1B-=" => 'Ý', // 221 in CP1252
            "\x1BNl" => 'Þ', // 222 in CP1252
            "\x1BN{" => 'ß', // 223 in CP1252
            "\x1BNAa" => 'à', // 224 in CP1252
            "\x1BNBa" => 'á', // 225 in CP1252
            "\x1BNCa" => 'â', // 226 in CP1252
            "\x1BNDa" => 'ã', // 227 in CP1252
            "\x1BNHa" => 'ä', // 228 in CP1252
            "\x1BNJa" => 'å', // 229 in CP1252
            "\x1BNq" => 'æ', // 230 in CP1252
            "\x1BNKc" => 'ç', // 231 in CP1252
            "\x1BNAe" => 'è', // 232 in CP1252
            "\x1BNBe" => 'é', // 233 in CP1252
            "\x1BNCe" => 'ê', // 234 in CP1252
            "\x1BNHe" => 'ë', // 235 in CP1252
            "\x1BNAi" => 'ì', // 236 in CP1252
            "\x1BNBi" => 'í', // 237 in CP1252
            "\x1BNCi" => 'î', // 238 in CP1252
            "\x1BNHi" => 'ï', // 239 in CP1252
            "\x1BNs" => 'ð', // 240 in CP1252
            "\x1BNDn" => 'ñ', // 241 in CP1252
            "\x1BNAo" => 'ò', // 242 in CP1252
            "\x1BNBo" => 'ó', // 243 in CP1252
            "\x1BNCo" => 'ô', // 244 in CP1252
            "\x1BNDo" => 'õ', // 245 in CP1252
            "\x1BNHo" => 'ö', // 246 in CP1252
            "\x1B/7" => '÷', // 247 in CP1252
            "\x1BNy" => 'ø', // 248 in CP1252
            "\x1BNAu" => 'ù', // 249 in CP1252
            "\x1BNBu" => 'ú', // 250 in CP1252
            "\x1BNCu" => 'û', // 251 in CP1252
            "\x1BNHu" => 'ü', // 252 in CP1252
            "\x1B/=" => 'ý', // 253 in CP1252
            "\x1BN|" => 'þ', // 254 in CP1252
            "\x1BNHy" => 'ÿ', // 255 in CP1252
        ];
    }

    /**
     * Get whether iconv extension is available.
     *
     * @return bool
     */
    public static function getIsIconvEnabled()
    {
        if (isset(self::$isIconvEnabled)) {
            return self::$isIconvEnabled;
        }

        // Fail if iconv doesn't exist
        if (!function_exists('iconv')) {
            self::$isIconvEnabled = false;

            return false;
        }

        // Sometimes iconv is not working, and e.g. iconv('UTF-8', 'UTF-16LE', 'x') just returns false,
        if (!@iconv('UTF-8', 'UTF-16LE', 'x')) {
            self::$isIconvEnabled = false;

            return false;
        }

        // Sometimes iconv_substr('A', 0, 1, 'UTF-8') just returns false in PHP 5.2.0
        // we cannot use iconv in that case either (http://bugs.php.net/bug.php?id=37773)
        if (!@iconv_substr('A', 0, 1, 'UTF-8')) {
            self::$isIconvEnabled = false;

            return false;
        }

        // CUSTOM: IBM AIX iconv() does not work
        if (defined('PHP_OS') && @stristr(PHP_OS, 'AIX') && defined('ICONV_IMPL') && (@strcasecmp(ICONV_IMPL, 'unknown') == 0) && defined('ICONV_VERSION') && (@strcasecmp(ICONV_VERSION, 'unknown') == 0)) {
            self::$isIconvEnabled = false;

            return false;
        }

        // If we reach here no problems were detected with iconv
        self::$isIconvEnabled = true;

        return true;
    }

    private static function buildCharacterSets()
    {
        if (empty(self::$controlCharacters)) {
            self::buildControlCharacters();
        }

        if (empty(self::$SYLKCharacters)) {
            self::buildSYLKCharacters();
        }
    }

    /**
     * Convert from OpenXML escaped control character to PHP control character.
     *
     * Excel 2007 team:
     * ----------------
     * That's correct, control characters are stored directly in the shared-strings table.
     * We do encode characters that cannot be represented in XML using the following escape sequence:
     * _xHHHH_ where H represents a hexadecimal character in the character's value...
     * So you could end up with something like _x0008_ in a string (either in a cell value (<v>)
     * element or in the shared string <t> element.
     *
     * @param string $value Value to unescape
     *
     * @return string
     */
    public static function controlCharacterOOXML2PHP($value)
    {
        self::buildCharacterSets();

        return str_replace(array_keys(self::$controlCharacters), array_values(self::$controlCharacters), $value);
    }

    /**
     * Convert from PHP control character to OpenXML escaped control character.
     *
     * Excel 2007 team:
     * ----------------
     * That's correct, control characters are stored directly in the shared-strings table.
     * We do encode characters that cannot be represented in XML using the following escape sequence:
     * _xHHHH_ where H represents a hexadecimal character in the character's value...
     * So you could end up with something like _x0008_ in a string (either in a cell value (<v>)
     * element or in the shared string <t> element.
     *
     * @param string $value Value to escape
     *
     * @return string
     */
    public static function controlCharacterPHP2OOXML($value)
    {
        self::buildCharacterSets();

        return str_replace(array_values(self::$controlCharacters), array_keys(self::$controlCharacters), $value);
    }

    /**
     * Try to sanitize UTF8, stripping invalid byte sequences. Not perfect. Does not surrogate characters.
     *
     * @param string $value
     *
     * @return string
     */
    public static function sanitizeUTF8($value)
    {
        if (self::getIsIconvEnabled()) {
            $value = @iconv('UTF-8', 'UTF-8', $value);

            return $value;
        }

        $value = mb_convert_encoding($value, 'UTF-8', 'UTF-8');

        return $value;
    }

    /**
     * Check if a string contains UTF8 data.
     *
     * @param string $value
     *
     * @return bool
     */
    public static function isUTF8($value)
    {
        return $value === '' || preg_match('/^./su', $value) === 1;
    }

    /**
     * Formats a numeric value as a string for output in various output writers forcing
     * point as decimal separator in case locale is other than English.
     *
     * @param mixed $value
     *
     * @return string
     */
    public static function formatNumber($value)
    {
        if (is_float($value)) {
            return str_replace(',', '.', $value);
        }

        return (string) $value;
    }

    /**
     * Converts a UTF-8 string into BIFF8 Unicode string data (8-bit string length)
     * Writes the string using uncompressed notation, no rich text, no Asian phonetics
     * If mbstring extension is not available, ASCII is assumed, and compressed notation is used
     * although this will give wrong results for non-ASCII strings
     * see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3.
     *
     * @param string $value UTF-8 encoded string
     * @param mixed[] $arrcRuns Details of rich text runs in $value
     *
     * @return string
     */
    public static function UTF8toBIFF8UnicodeShort($value, $arrcRuns = [])
    {
        // character count
        $ln = self::countCharacters($value, 'UTF-8');
        // option flags
        if (empty($arrcRuns)) {
            $data = pack('CC', $ln, 0x0001);
            // characters
            $data .= self::convertEncoding($value, 'UTF-16LE', 'UTF-8');
        } else {
            $data = pack('vC', $ln, 0x09);
            $data .= pack('v', count($arrcRuns));
            // characters
            $data .= self::convertEncoding($value, 'UTF-16LE', 'UTF-8');
            foreach ($arrcRuns as $cRun) {
                $data .= pack('v', $cRun['strlen']);
                $data .= pack('v', $cRun['fontidx']);
            }
        }

        return $data;
    }

    /**
     * Converts a UTF-8 string into BIFF8 Unicode string data (16-bit string length)
     * Writes the string using uncompressed notation, no rich text, no Asian phonetics
     * If mbstring extension is not available, ASCII is assumed, and compressed notation is used
     * although this will give wrong results for non-ASCII strings
     * see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3.
     *
     * @param string $value UTF-8 encoded string
     *
     * @return string
     */
    public static function UTF8toBIFF8UnicodeLong($value)
    {
        // character count
        $ln = self::countCharacters($value, 'UTF-8');

        // characters
        $chars = self::convertEncoding($value, 'UTF-16LE', 'UTF-8');

        $data = pack('vC', $ln, 0x0001) . $chars;

        return $data;
    }

    /**
     * Convert string from one encoding to another.
     *
     * @param string $value
     * @param string $to Encoding to convert to, e.g. 'UTF-8'
     * @param string $from Encoding to convert from, e.g. 'UTF-16LE'
     *
     * @return string
     */
    public static function convertEncoding($value, $to, $from)
    {
        if (self::getIsIconvEnabled()) {
            $result = iconv($from, $to . '//IGNORE//TRANSLIT', $value);
            if (false !== $result) {
                return $result;
            }
        }

        return mb_convert_encoding($value, $to, $from);
    }

    /**
     * Get character count.
     *
     * @param string $value
     * @param string $enc Encoding
     *
     * @return int Character count
     */
    public static function countCharacters($value, $enc = 'UTF-8')
    {
        return mb_strlen($value, $enc);
    }

    /**
     * Get a substring of a UTF-8 encoded string.
     *
     * @param string $pValue UTF-8 encoded string
     * @param int $pStart Start offset
     * @param int $pLength Maximum number of characters in substring
     *
     * @return string
     */
    public static function substring($pValue, $pStart, $pLength = 0)
    {
        return mb_substr($pValue, $pStart, $pLength, 'UTF-8');
    }

    /**
     * Convert a UTF-8 encoded string to upper case.
     *
     * @param string $pValue UTF-8 encoded string
     *
     * @return string
     */
    public static function strToUpper($pValue)
    {
        return mb_convert_case($pValue, MB_CASE_UPPER, 'UTF-8');
    }

    /**
     * Convert a UTF-8 encoded string to lower case.
     *
     * @param string $pValue UTF-8 encoded string
     *
     * @return string
     */
    public static function strToLower($pValue)
    {
        return mb_convert_case($pValue, MB_CASE_LOWER, 'UTF-8');
    }

    /**
     * Convert a UTF-8 encoded string to title/proper case
     * (uppercase every first character in each word, lower case all other characters).
     *
     * @param string $pValue UTF-8 encoded string
     *
     * @return string
     */
    public static function strToTitle($pValue)
    {
        return mb_convert_case($pValue, MB_CASE_TITLE, 'UTF-8');
    }

    public static function mbIsUpper($char)
    {
        return mb_strtolower($char, 'UTF-8') != $char;
    }

    public static function mbStrSplit($string)
    {
        // Split at all position not after the start: ^
        // and not before the end: $
        return preg_split('/(?<!^)(?!$)/u', $string);
    }

    /**
     * Reverse the case of a string, so that all uppercase characters become lowercase
     * and all lowercase characters become uppercase.
     *
     * @param string $pValue UTF-8 encoded string
     *
     * @return string
     */
    public static function strCaseReverse($pValue)
    {
        $characters = self::mbStrSplit($pValue);
        foreach ($characters as &$character) {
            if (self::mbIsUpper($character)) {
                $character = mb_strtolower($character, 'UTF-8');
            } else {
                $character = mb_strtoupper($character, 'UTF-8');
            }
        }

        return implode('', $characters);
    }

    /**
     * Identify whether a string contains a fractional numeric value,
     * and convert it to a numeric if it is.
     *
     * @param string &$operand string value to test
     *
     * @return bool
     */
    public static function convertToNumberIfFraction(&$operand)
    {
        if (preg_match('/^' . self::STRING_REGEXP_FRACTION . '$/i', $operand, $match)) {
            $sign = ($match[1] == '-') ? '-' : '+';
            $fractionFormula = '=' . $sign . $match[2] . $sign . $match[3];
            $operand = Calculation::getInstance()->_calculateFormulaValue($fractionFormula);

            return true;
        }

        return false;
    }

    //    function convertToNumberIfFraction()

    /**
     * Get the decimal separator. If it has not yet been set explicitly, try to obtain number
     * formatting information from locale.
     *
     * @return string
     */
    public static function getDecimalSeparator()
    {
        if (!isset(self::$decimalSeparator)) {
            $localeconv = localeconv();
            self::$decimalSeparator = ($localeconv['decimal_point'] != '')
                ? $localeconv['decimal_point'] : $localeconv['mon_decimal_point'];

            if (self::$decimalSeparator == '') {
                // Default to .
                self::$decimalSeparator = '.';
            }
        }

        return self::$decimalSeparator;
    }

    /**
     * Set the decimal separator. Only used by NumberFormat::toFormattedString()
     * to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf.
     *
     * @param string $pValue Character for decimal separator
     */
    public static function setDecimalSeparator($pValue)
    {
        self::$decimalSeparator = $pValue;
    }

    /**
     * Get the thousands separator. If it has not yet been set explicitly, try to obtain number
     * formatting information from locale.
     *
     * @return string
     */
    public static function getThousandsSeparator()
    {
        if (!isset(self::$thousandsSeparator)) {
            $localeconv = localeconv();
            self::$thousandsSeparator = ($localeconv['thousands_sep'] != '')
                ? $localeconv['thousands_sep'] : $localeconv['mon_thousands_sep'];

            if (self::$thousandsSeparator == '') {
                // Default to .
                self::$thousandsSeparator = ',';
            }
        }

        return self::$thousandsSeparator;
    }

    /**
     * Set the thousands separator. Only used by NumberFormat::toFormattedString()
     * to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf.
     *
     * @param string $pValue Character for thousands separator
     */
    public static function setThousandsSeparator($pValue)
    {
        self::$thousandsSeparator = $pValue;
    }

    /**
     *    Get the currency code. If it has not yet been set explicitly, try to obtain the
     *        symbol information from locale.
     *
     * @return string
     */
    public static function getCurrencyCode()
    {
        if (!empty(self::$currencyCode)) {
            return self::$currencyCode;
        }
        self::$currencyCode = '$';
        $localeconv = localeconv();
        if (!empty($localeconv['currency_symbol'])) {
            self::$currencyCode = $localeconv['currency_symbol'];

            return self::$currencyCode;
        }
        if (!empty($localeconv['int_curr_symbol'])) {
            self::$currencyCode = $localeconv['int_curr_symbol'];

            return self::$currencyCode;
        }

        return self::$currencyCode;
    }

    /**
     * Set the currency code. Only used by NumberFormat::toFormattedString()
     *        to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf.
     *
     * @param string $pValue Character for currency code
     */
    public static function setCurrencyCode($pValue)
    {
        self::$currencyCode = $pValue;
    }

    /**
     * Convert SYLK encoded string to UTF-8.
     *
     * @param string $pValue
     *
     * @return string UTF-8 encoded string
     */
    public static function SYLKtoUTF8($pValue)
    {
        self::buildCharacterSets();

        // If there is no escape character in the string there is nothing to do
        if (strpos($pValue, '') === false) {
            return $pValue;
        }

        foreach (self::$SYLKCharacters as $k => $v) {
            $pValue = str_replace($k, $v, $pValue);
        }

        return $pValue;
    }

    /**
     * Retrieve any leading numeric part of a string, or return the full string if no leading numeric
     * (handles basic integer or float, but not exponent or non decimal).
     *
     * @param string $value
     *
     * @return mixed string or only the leading numeric part of the string
     */
    public static function testStringAsNumeric($value)
    {
        if (is_numeric($value)) {
            return $value;
        }
        $v = (float) $value;

        return (is_numeric(substr($value, 0, strlen($v)))) ? $v : $value;
    }
}


<?php

namespace App\Http\Controllers\IntoTheSource\Users;

use App\Role;
use App\Http\Requests\RolesRequest;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

/**
 * Roles Controller
 * @package users
 * @author Gertjan Roke <groke@intothesource.com>
 */
class RolesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $roles = Role::all();
        return view('intothesource.usersmanager.roles.index', compact('roles'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('intothesource.usersmanager.roles.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  RolesRequest $request
     * @return \Illuminate\Http\Response
     */
    public function store(RolesRequest $request)
    {
        $role = new Role;
        $role->create($request->only($role->getFillable()));
        return redirect()->route('role.manager.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $role = Role::findOrFail($id);
        return view('intothesource.usersmanager.roles.edit', compact('role'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     * @param  RolesRequest $request
     * @return \Illuminate\Http\Response
     */
    public function update(RolesRequest $request, $id)
    {
        $role = Role::findOrFail($id);
        $role->update($request->only($role->getFillable()));
        return redirect()->route('role.manager.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $role = Role::findOrFail($id);
        $role->delete();
        return redirect()->route('role.manager.index');
    }
}


<?php
/*   _            _          _ ____   ___  _____
 *  | |          | |        | |___ \ / _ \| ____|
 *  | |      __ _| |__   ___| | __) | | | | |__
 *  | |     / _` | '_ \ / _ \ ||__ <|  -  |___ \
 *  | |____| (_| | |_) |  __/ |___) |     |___) |
 *  |______|\__,_|_.__/ \___|_|____/ \___/|____/
 *
 *  Copyright Label305 B.V. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Label305\AujaLaravel;

use Illuminate\Support\ServiceProvider;
use Label305\AujaLaravel\Config\AujaConfigurator;
use Label305\AujaLaravel\Database\MySQLDatabaseHelper;
use Label305\AujaLaravel\Exceptions\NoDatabaseHelperException;
use Label305\AujaLaravel\Routing\AujaRouter;

/**
 * The Laravel service provider
 * Include this class in your laravel app/config/app.php file to load it at bootstrap.
 *
 * @author  Thijs Scheepers - <thijs@label305.com>
 *
 * @package Label305\AujaLaravel
 * @license http://www.apache.org/licenses/LICENSE-2.0
 */
class AujaServiceProvider extends ServiceProvider {

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register() {

        $this->registerConfigurator();

        $this->registerManager();

        $this->registerRouter();
    }

    /**
     * Register the manager.
     */
    protected function registerManager()
    {
        $this->app->singleton('auja', function ($app) {
            $config = $app['config']['auja-laravel'] ?: $app['config']['auja-laravel::config'];
            return new Auja($app, $app['auja.configurator'], $config['models']);
        });

        $this->app->bind('Label305\AujaLaravel\Auja', 'auja');
    }

    /**
     * Register the auja configurator
     */
    protected function registerConfigurator()
    {
        $this->app->singleton('auja.database', function($app) {

            $config = $app['config']['auja-laravel'] ?: $app['config']['auja-laravel::config'];

            switch ($config['database']) {
                case 'mysql':
                    return new MySQLDatabaseHelper();
                    break;
                default:
                    throw new NoDatabaseHelperException('No Auja database helper for ' . $config['database']);
                    break;
            }
        });

        $this->app->bind('Label305\AujaLaravel\Database\DatabaseHelper', 'auja.database');

        $this->app->singleton('auja.configurator', function($app) {
            return new AujaConfigurator($app, $app['auja.database']);
        });

        $this->app->bind('Label305\AujaLaravel\Config\AujaConfigurator', 'auja.configurator');
    }

    /**
     * Register the router
     */
    protected function registerRouter()
    {
        $this->app->singleton('auja.router', function($app) {

            $config = $app['config']['auja-laravel'] ?: $app['config']['auja-laravel::config'];

            return new AujaRouter($app['auja'], $app['router'], $config['route']);
        });

        $this->app->bind('Label305\AujaLaravel\Routing\AujaRouter', 'auja.router');
    }

    /**
     * @return array
     */
    public function provides()
    {
        return ['auja', 'auja.router', 'auja.database', 'auja.configurator'];
    }

    /**
     * Boot the package
     */
    public function boot() {

        $this->package('label305/auja-laravel');

        $app = $this->app;

        // Include the routes file located in src/routes.php of this package
        include __DIR__.'/../../routes.php';
    }

}


<?php

namespace PhpOffice\PhpSpreadsheet\Calculation;

use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;

class DateTime
{
    /**
     * Identify if a year is a leap year or not.
     *
     * @param int $year The year to test
     *
     * @return bool TRUE if the year is a leap year, otherwise FALSE
     */
    public static function isLeapYear($year)
    {
        return (($year % 4) == 0) && (($year % 100) != 0) || (($year % 400) == 0);
    }

    /**
     * Return the number of days between two dates based on a 360 day calendar.
     *
     * @param int $startDay Day of month of the start date
     * @param int $startMonth Month of the start date
     * @param int $startYear Year of the start date
     * @param int $endDay Day of month of the start date
     * @param int $endMonth Month of the start date
     * @param int $endYear Year of the start date
     * @param bool $methodUS Whether to use the US method or the European method of calculation
     *
     * @return int Number of days between the start date and the end date
     */
    private static function dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, $methodUS)
    {
        if ($startDay == 31) {
            --$startDay;
        } elseif ($methodUS && ($startMonth == 2 && ($startDay == 29 || ($startDay == 28 && !self::isLeapYear($startYear))))) {
            $startDay = 30;
        }
        if ($endDay == 31) {
            if ($methodUS && $startDay != 30) {
                $endDay = 1;
                if ($endMonth == 12) {
                    ++$endYear;
                    $endMonth = 1;
                } else {
                    ++$endMonth;
                }
            } else {
                $endDay = 30;
            }
        }

        return $endDay + $endMonth * 30 + $endYear * 360 - $startDay - $startMonth * 30 - $startYear * 360;
    }

    /**
     * getDateValue.
     *
     * @param string $dateValue
     *
     * @return mixed Excel date/time serial value, or string if error
     */
    public static function getDateValue($dateValue)
    {
        if (!is_numeric($dateValue)) {
            if ((is_string($dateValue)) &&
                (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC)) {
                return Functions::VALUE();
            }
            if ((is_object($dateValue)) && ($dateValue instanceof \DateTime)) {
                $dateValue = Date::PHPToExcel($dateValue);
            } else {
                $saveReturnDateType = Functions::getReturnDateType();
                Functions::setReturnDateType(Functions::RETURNDATE_EXCEL);
                $dateValue = self::DATEVALUE($dateValue);
                Functions::setReturnDateType($saveReturnDateType);
            }
        }

        return $dateValue;
    }

    /**
     * getTimeValue.
     *
     * @param string $timeValue
     *
     * @return mixed Excel date/time serial value, or string if error
     */
    private static function getTimeValue($timeValue)
    {
        $saveReturnDateType = Functions::getReturnDateType();
        Functions::setReturnDateType(Functions::RETURNDATE_EXCEL);
        $timeValue = self::TIMEVALUE($timeValue);
        Functions::setReturnDateType($saveReturnDateType);

        return $timeValue;
    }

    private static function adjustDateByMonths($dateValue = 0, $adjustmentMonths = 0)
    {
        // Execute function
        $PHPDateObject = Date::excelToDateTimeObject($dateValue);
        $oMonth = (int) $PHPDateObject->format('m');
        $oYear = (int) $PHPDateObject->format('Y');

        $adjustmentMonthsString = (string) $adjustmentMonths;
        if ($adjustmentMonths > 0) {
            $adjustmentMonthsString = '+' . $adjustmentMonths;
        }
        if ($adjustmentMonths != 0) {
            $PHPDateObject->modify($adjustmentMonthsString . ' months');
        }
        $nMonth = (int) $PHPDateObject->format('m');
        $nYear = (int) $PHPDateObject->format('Y');

        $monthDiff = ($nMonth - $oMonth) + (($nYear - $oYear) * 12);
        if ($monthDiff != $adjustmentMonths) {
            $adjustDays = (int) $PHPDateObject->format('d');
            $adjustDaysString = '-' . $adjustDays . ' days';
            $PHPDateObject->modify($adjustDaysString);
        }

        return $PHPDateObject;
    }

    /**
     * DATETIMENOW.
     *
     * Returns the current date and time.
     * The NOW function is useful when you need to display the current date and time on a worksheet or
     * calculate a value based on the current date and time, and have that value updated each time you
     * open the worksheet.
     *
     * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
     * and time format of your regional settings. PhpSpreadsheet does not change cell formatting in this way.
     *
     * Excel Function:
     *        NOW()
     *
     * @category Date/Time Functions
     *
     * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
     *                        depending on the value of the ReturnDateType flag
     */
    public static function DATETIMENOW()
    {
        $saveTimeZone = date_default_timezone_get();
        date_default_timezone_set('UTC');
        $retValue = false;
        switch (Functions::getReturnDateType()) {
            case Functions::RETURNDATE_EXCEL:
                $retValue = (float) Date::PHPToExcel(time());

                break;
            case Functions::RETURNDATE_PHP_NUMERIC:
                $retValue = (int) time();

                break;
            case Functions::RETURNDATE_PHP_OBJECT:
                $retValue = new \DateTime();

                break;
        }
        date_default_timezone_set($saveTimeZone);

        return $retValue;
    }

    /**
     * DATENOW.
     *
     * Returns the current date.
     * The NOW function is useful when you need to display the current date and time on a worksheet or
     * calculate a value based on the current date and time, and have that value updated each time you
     * open the worksheet.
     *
     * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
     * and time format of your regional settings. PhpSpreadsheet does not change cell formatting in this way.
     *
     * Excel Function:
     *        TODAY()
     *
     * @category Date/Time Functions
     *
     * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
     *                        depending on the value of the ReturnDateType flag
     */
    public static function DATENOW()
    {
        $saveTimeZone = date_default_timezone_get();
        date_default_timezone_set('UTC');
        $retValue = false;
        $excelDateTime = floor(Date::PHPToExcel(time()));
        switch (Functions::getReturnDateType()) {
            case Functions::RETURNDATE_EXCEL:
                $retValue = (float) $excelDateTime;

                break;
            case Functions::RETURNDATE_PHP_NUMERIC:
                $retValue = (int) Date::excelToTimestamp($excelDateTime);

                break;
            case Functions::RETURNDATE_PHP_OBJECT:
                $retValue = Date::excelToDateTimeObject($excelDateTime);

                break;
        }
        date_default_timezone_set($saveTimeZone);

        return $retValue;
    }

    /**
     * DATE.
     *
     * The DATE function returns a value that represents a particular date.
     *
     * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
     * format of your regional settings. PhpSpreadsheet does not change cell formatting in this way.
     *
     * Excel Function:
     *        DATE(year,month,day)
     *
     * PhpSpreadsheet is a lot more forgiving than MS Excel when passing non numeric values to this function.
     * A Month name or abbreviation (English only at this point) such as 'January' or 'Jan' will still be accepted,
     *     as will a day value with a suffix (e.g. '21st' rather than simply 21); again only English language.
     *
     * @category Date/Time Functions
     *
     * @param int $year The value of the year argument can include one to four digits.
     *                                Excel interprets the year argument according to the configured
     *                                date system: 1900 or 1904.
     *                                If year is between 0 (zero) and 1899 (inclusive), Excel adds that
     *                                value to 1900 to calculate the year. For example, DATE(108,1,2)
     *                                returns January 2, 2008 (1900+108).
     *                                If year is between 1900 and 9999 (inclusive), Excel uses that
     *                                value as the year. For example, DATE(2008,1,2) returns January 2,
     *                                2008.
     *                                If year is less than 0 or is 10000 or greater, Excel returns the
     *                                #NUM! error value.
     * @param int $month A positive or negative integer representing the month of the year
     *                                from 1 to 12 (January to December).
     *                                If month is greater than 12, month adds that number of months to
     *                                the first month in the year specified. For example, DATE(2008,14,2)
     *                                returns the serial number representing February 2, 2009.
     *                                If month is less than 1, month subtracts the magnitude of that
     *                                number of months, plus 1, from the first month in the year
     *                                specified. For example, DATE(2008,-3,2) returns the serial number
     *                                representing September 2, 2007.
     * @param int $day A positive or negative integer representing the day of the month
     *                                from 1 to 31.
     *                                If day is greater than the number of days in the month specified,
     *                                day adds that number of days to the first day in the month. For
     *                                example, DATE(2008,1,35) returns the serial number representing
     *                                February 4, 2008.
     *                                If day is less than 1, day subtracts the magnitude that number of
     *                                days, plus one, from the first day of the month specified. For
     *                                example, DATE(2008,1,-15) returns the serial number representing
     *                                December 16, 2007.
     *
     * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
     *                        depending on the value of the ReturnDateType flag
     */
    public static function DATE($year = 0, $month = 1, $day = 1)
    {
        $year = Functions::flattenSingleValue($year);
        $month = Functions::flattenSingleValue($month);
        $day = Functions::flattenSingleValue($day);

        if (($month !== null) && (!is_numeric($month))) {
            $month = Date::monthStringToNumber($month);
        }

        if (($day !== null) && (!is_numeric($day))) {
            $day = Date::dayStringToNumber($day);
        }

        $year = ($year !== null) ? StringHelper::testStringAsNumeric($year) : 0;
        $month = ($month !== null) ? StringHelper::testStringAsNumeric($month) : 0;
        $day = ($day !== null) ? StringHelper::testStringAsNumeric($day) : 0;
        if ((!is_numeric($year)) ||
            (!is_numeric($month)) ||
            (!is_numeric($day))) {
            return Functions::VALUE();
        }
        $year = (int) $year;
        $month = (int) $month;
        $day = (int) $day;

        $baseYear = Date::getExcelCalendar();
        // Validate parameters
        if ($year < ($baseYear - 1900)) {
            return Functions::NAN();
        }
        if ((($baseYear - 1900) != 0) && ($year < $baseYear) && ($year >= 1900)) {
            return Functions::NAN();
        }

        if (($year < $baseYear) && ($year >= ($baseYear - 1900))) {
            $year += 1900;
        }

        if ($month < 1) {
            //    Handle year/month adjustment if month < 1
            --$month;
            $year += ceil($month / 12) - 1;
            $month = 13 - abs($month % 12);
        } elseif ($month > 12) {
            //    Handle year/month adjustment if month > 12
            $year += floor($month / 12);
            $month = ($month % 12);
        }

        // Re-validate the year parameter after adjustments
        if (($year < $baseYear) || ($year >= 10000)) {
            return Functions::NAN();
        }

        // Execute function
        $excelDateValue = Date::formattedPHPToExcel($year, $month, $day);
        switch (Functions::getReturnDateType()) {
            case Functions::RETURNDATE_EXCEL:
                return (float) $excelDateValue;
            case Functions::RETURNDATE_PHP_NUMERIC:
                return (int) Date::excelToTimestamp($excelDateValue);
            case Functions::RETURNDATE_PHP_OBJECT:
                return Date::excelToDateTimeObject($excelDateValue);
        }
    }

    /**
     * TIME.
     *
     * The TIME function returns a value that represents a particular time.
     *
     * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the time
     * format of your regional settings. PhpSpreadsheet does not change cell formatting in this way.
     *
     * Excel Function:
     *        TIME(hour,minute,second)
     *
     * @category Date/Time Functions
     *
     * @param int $hour A number from 0 (zero) to 32767 representing the hour.
     *                                    Any value greater than 23 will be divided by 24 and the remainder
     *                                    will be treated as the hour value. For example, TIME(27,0,0) =
     *                                    TIME(3,0,0) = .125 or 3:00 AM.
     * @param int $minute A number from 0 to 32767 representing the minute.
     *                                    Any value greater than 59 will be converted to hours and minutes.
     *                                    For example, TIME(0,750,0) = TIME(12,30,0) = .520833 or 12:30 PM.
     * @param int $second A number from 0 to 32767 representing the second.
     *                                    Any value greater than 59 will be converted to hours, minutes,
     *                                    and seconds. For example, TIME(0,0,2000) = TIME(0,33,22) = .023148
     *                                    or 12:33:20 AM
     *
     * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
     *                        depending on the value of the ReturnDateType flag
     */
    public static function TIME($hour = 0, $minute = 0, $second = 0)
    {
        $hour = Functions::flattenSingleValue($hour);
        $minute = Functions::flattenSingleValue($minute);
        $second = Functions::flattenSingleValue($second);

        if ($hour == '') {
            $hour = 0;
        }
        if ($minute == '') {
            $minute = 0;
        }
        if ($second == '') {
            $second = 0;
        }

        if ((!is_numeric($hour)) || (!is_numeric($minute)) || (!is_numeric($second))) {
            return Functions::VALUE();
        }
        $hour = (int) $hour;
        $minute = (int) $minute;
        $second = (int) $second;

        if ($second < 0) {
            $minute += floor($second / 60);
            $second = 60 - abs($second % 60);
            if ($second == 60) {
                $second = 0;
            }
        } elseif ($second >= 60) {
            $minute += floor($second / 60);
            $second = $second % 60;
        }
        if ($minute < 0) {
            $hour += floor($minute / 60);
            $minute = 60 - abs($minute % 60);
            if ($minute == 60) {
                $minute = 0;
            }
        } elseif ($minute >= 60) {
            $hour += floor($minute / 60);
            $minute = $minute % 60;
        }

        if ($hour > 23) {
            $hour = $hour % 24;
        } elseif ($hour < 0) {
            return Functions::NAN();
        }

        // Execute function
        switch (Functions::getReturnDateType()) {
            case Functions::RETURNDATE_EXCEL:
                $date = 0;
                $calendar = Date::getExcelCalendar();
                if ($calendar != Date::CALENDAR_WINDOWS_1900) {
                    $date = 1;
                }

                return (float) Date::formattedPHPToExcel($calendar, 1, $date, $hour, $minute, $second);
            case Functions::RETURNDATE_PHP_NUMERIC:
                return (int) Date::excelToTimestamp(Date::formattedPHPToExcel(1970, 1, 1, $hour, $minute, $second)); // -2147468400; //    -2147472000 + 3600
            case Functions::RETURNDATE_PHP_OBJECT:
                $dayAdjust = 0;
                if ($hour < 0) {
                    $dayAdjust = floor($hour / 24);
                    $hour = 24 - abs($hour % 24);
                    if ($hour == 24) {
                        $hour = 0;
                    }
                } elseif ($hour >= 24) {
                    $dayAdjust = floor($hour / 24);
                    $hour = $hour % 24;
                }
                $phpDateObject = new \DateTime('1900-01-01 ' . $hour . ':' . $minute . ':' . $second);
                if ($dayAdjust != 0) {
                    $phpDateObject->modify($dayAdjust . ' days');
                }

                return $phpDateObject;
        }
    }

    /**
     * DATEVALUE.
     *
     * Returns a value that represents a particular date.
     * Use DATEVALUE to convert a date represented by a text string to an Excel or PHP date/time stamp
     * value.
     *
     * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
     * format of your regional settings. PhpSpreadsheet does not change cell formatting in this way.
     *
     * Excel Function:
     *        DATEVALUE(dateValue)
     *
     * @category Date/Time Functions
     *
     * @param string $dateValue Text that represents a date in a Microsoft Excel date format.
     *                                    For example, "1/30/2008" or "30-Jan-2008" are text strings within
     *                                    quotation marks that represent dates. Using the default date
     *                                    system in Excel for Windows, date_text must represent a date from
     *                                    January 1, 1900, to December 31, 9999. Using the default date
     *                                    system in Excel for the Macintosh, date_text must represent a date
     *                                    from January 1, 1904, to December 31, 9999. DATEVALUE returns the
     *                                    #VALUE! error value if date_text is out of this range.
     *
     * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
     *                        depending on the value of the ReturnDateType flag
     */
    public static function DATEVALUE($dateValue = 1)
    {
        $dateValueOrig = $dateValue;
        $dateValue = trim(Functions::flattenSingleValue($dateValue), '"');
        //    Strip any ordinals because they're allowed in Excel (English only)
        $dateValue = preg_replace('/(\d)(st|nd|rd|th)([ -\/])/Ui', '$1$3', $dateValue);
        //    Convert separators (/ . or space) to hyphens (should also handle dot used for ordinals in some countries, e.g. Denmark, Germany)
        $dateValue = str_replace(['/', '.', '-', '  '], ' ', $dateValue);

        $yearFound = false;
        $t1 = explode(' ', $dateValue);
        foreach ($t1 as &$t) {
            if ((is_numeric($t)) && ($t > 31)) {
                if ($yearFound) {
                    return Functions::VALUE();
                }
                if ($t < 100) {
                    $t += 1900;
                }
                $yearFound = true;
            }
        }
        if ((count($t1) == 1) && (strpos($t, ':') != false)) {
            //    We've been fed a time value without any date
            return 0.0;
        } elseif (count($t1) == 2) {
            //    We only have two parts of the date: either day/month or month/year
            if ($yearFound) {
                array_unshift($t1, 1);
            } else {
                if ($t1[1] > 29) {
                    $t1[1] += 1900;
                    array_unshift($t1, 1);
                } else {
                    $t1[] = date('Y');
                }
            }
        }
        unset($t);
        $dateValue = implode(' ', $t1);

        $PHPDateArray = date_parse($dateValue);
        if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) {
            $testVal1 = strtok($dateValue, '- ');
            if ($testVal1 !== false) {
                $testVal2 = strtok('- ');
                if ($testVal2 !== false) {
                    $testVal3 = strtok('- ');
                    if ($testVal3 === false) {
                        $testVal3 = strftime('%Y');
                    }
                } else {
                    return Functions::VALUE();
                }
            } else {
                return Functions::VALUE();
            }
            if ($testVal1 < 31 && $testVal2 < 12 && $testVal3 < 12 && strlen($testVal3) == 2) {
                $testVal3 += 2000;
            }
            $PHPDateArray = date_parse($testVal1 . '-' . $testVal2 . '-' . $testVal3);
            if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) {
                $PHPDateArray = date_parse($testVal2 . '-' . $testVal1 . '-' . $testVal3);
                if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) {
                    return Functions::VALUE();
                }
            }
        }

        if (($PHPDateArray !== false) && ($PHPDateArray['error_count'] == 0)) {
            // Execute function
            if ($PHPDateArray['year'] == '') {
                $PHPDateArray['year'] = strftime('%Y');
            }
            if ($PHPDateArray['year'] < 1900) {
                return Functions::VALUE();
            }
            if ($PHPDateArray['month'] == '') {
                $PHPDateArray['month'] = strftime('%m');
            }
            if ($PHPDateArray['day'] == '') {
                $PHPDateArray['day'] = strftime('%d');
            }
            if (!checkdate($PHPDateArray['month'], $PHPDateArray['day'], $PHPDateArray['year'])) {
                return Functions::VALUE();
            }
            $excelDateValue = floor(
                Date::formattedPHPToExcel(
                    $PHPDateArray['year'],
                    $PHPDateArray['month'],
                    $PHPDateArray['day'],
                    $PHPDateArray['hour'],
                    $PHPDateArray['minute'],
                    $PHPDateArray['second']
                )
            );
            switch (Functions::getReturnDateType()) {
                case Functions::RETURNDATE_EXCEL:
                    return (float) $excelDateValue;
                case Functions::RETURNDATE_PHP_NUMERIC:
                    return (int) Date::excelToTimestamp($excelDateValue);
                case Functions::RETURNDATE_PHP_OBJECT:
                    return new \DateTime($PHPDateArray['year'] . '-' . $PHPDateArray['month'] . '-' . $PHPDateArray['day'] . ' 00:00:00');
            }
        }

        return Functions::VALUE();
    }

    /**
     * TIMEVALUE.
     *
     * Returns a value that represents a particular time.
     * Use TIMEVALUE to convert a time represented by a text string to an Excel or PHP date/time stamp
     * value.
     *
     * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the time
     * format of your regional settings. PhpSpreadsheet does not change cell formatting in this way.
     *
     * Excel Function:
     *        TIMEVALUE(timeValue)
     *
     * @category Date/Time Functions
     *
     * @param string $timeValue A text string that represents a time in any one of the Microsoft
     *                                    Excel time formats; for example, "6:45 PM" and "18:45" text strings
     *                                    within quotation marks that represent time.
     *                                    Date information in time_text is ignored.
     *
     * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
     *                        depending on the value of the ReturnDateType flag
     */
    public static function TIMEVALUE($timeValue)
    {
        $timeValue = trim(Functions::flattenSingleValue($timeValue), '"');
        $timeValue = str_replace(['/', '.'], '-', $timeValue);

        $arraySplit = preg_split('/[\/:\-\s]/', $timeValue);
        if ((count($arraySplit) == 2 || count($arraySplit) == 3) && $arraySplit[0] > 24) {
            $arraySplit[0] = ($arraySplit[0] % 24);
            $timeValue = implode(':', $arraySplit);
        }

        $PHPDateArray = date_parse($timeValue);
        if (($PHPDateArray !== false) && ($PHPDateArray['error_count'] == 0)) {
            if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) {
                $excelDateValue = Date::formattedPHPToExcel(
                    $PHPDateArray['year'],
                    $PHPDateArray['month'],
                    $PHPDateArray['day'],
                    $PHPDateArray['hour'],
                    $PHPDateArray['minute'],
                    $PHPDateArray['second']
                );
            } else {
                $excelDateValue = Date::formattedPHPToExcel(1900, 1, 1, $PHPDateArray['hour'], $PHPDateArray['minute'], $PHPDateArray['second']) - 1;
            }

            switch (Functions::getReturnDateType()) {
                case Functions::RETURNDATE_EXCEL:
                    return (float) $excelDateValue;
                case Functions::RETURNDATE_PHP_NUMERIC:
                    return (int) $phpDateValue = Date::excelToTimestamp($excelDateValue + 25569) - 3600;
                case Functions::RETURNDATE_PHP_OBJECT:
                    return new \DateTime('1900-01-01 ' . $PHPDateArray['hour'] . ':' . $PHPDateArray['minute'] . ':' . $PHPDateArray['second']);
            }
        }

        return Functions::VALUE();
    }

    /**
     * DATEDIF.
     *
     * @param mixed $startDate Excel date serial value, PHP date/time stamp, PHP DateTime object
     *                                    or a standard date string
     * @param mixed $endDate Excel date serial value, PHP date/time stamp, PHP DateTime object
     *                                    or a standard date string
     * @param string $unit
     *
     * @return int Interval between the dates
     */
    public static function DATEDIF($startDate = 0, $endDate = 0, $unit = 'D')
    {
        $startDate = Functions::flattenSingleValue($startDate);
        $endDate = Functions::flattenSingleValue($endDate);
        $unit = strtoupper(Functions::flattenSingleValue($unit));

        if (is_string($startDate = self::getDateValue($startDate))) {
            return Functions::VALUE();
        }
        if (is_string($endDate = self::getDateValue($endDate))) {
            return Functions::VALUE();
        }

        // Validate parameters
        if ($startDate > $endDate) {
            return Functions::NAN();
        }

        // Execute function
        $difference = $endDate - $startDate;

        $PHPStartDateObject = Date::excelToDateTimeObject($startDate);
        $startDays = $PHPStartDateObject->format('j');
        $startMonths = $PHPStartDateObject->format('n');
        $startYears = $PHPStartDateObject->format('Y');

        $PHPEndDateObject = Date::excelToDateTimeObject($endDate);
        $endDays = $PHPEndDateObject->format('j');
        $endMonths = $PHPEndDateObject->format('n');
        $endYears = $PHPEndDateObject->format('Y');

        $retVal = Functions::NAN();
        switch ($unit) {
            case 'D':
                $retVal = (int) $difference;

                break;
            case 'M':
                $retVal = (int) ($endMonths - $startMonths) + ((int) ($endYears - $startYears) * 12);
                //    We're only interested in full months
                if ($endDays < $startDays) {
                    --$retVal;
                }

                break;
            case 'Y':
                $retVal = (int) ($endYears - $startYears);
                //    We're only interested in full months
                if ($endMonths < $startMonths) {
                    --$retVal;
                } elseif (($endMonths == $startMonths) && ($endDays < $startDays)) {
                    // Remove start month
                    --$retVal;
                    // Remove end month
                    --$retVal;
                }

                break;
            case 'MD':
                if ($endDays < $startDays) {
                    $retVal = $endDays;
                    $PHPEndDateObject->modify('-' . $endDays . ' days');
                    $adjustDays = $PHPEndDateObject->format('j');
                    $retVal += ($adjustDays - $startDays);
                } else {
                    $retVal = $endDays - $startDays;
                }

                break;
            case 'YM':
                $retVal = (int) ($endMonths - $startMonths);
                if ($retVal < 0) {
                    $retVal += 12;
                }
                //    We're only interested in full months
                if ($endDays < $startDays) {
                    --$retVal;
                }

                break;
            case 'YD':
                $retVal = (int) $difference;
                if ($endYears > $startYears) {
                    $isLeapStartYear = $PHPStartDateObject->format('L');
                    $wasLeapEndYear = $PHPEndDateObject->format('L');

                    // Adjust end year to be as close as possible as start year
                    while ($PHPEndDateObject >= $PHPStartDateObject) {
                        $PHPEndDateObject->modify('-1 year');
                        $endYears = $PHPEndDateObject->format('Y');
                    }
                    $PHPEndDateObject->modify('+1 year');

                    // Get the result
                    $retVal = $PHPEndDateObject->diff($PHPStartDateObject)->days;

                    // Adjust for leap years cases
                    $isLeapEndYear = $PHPEndDateObject->format('L');
                    $limit = new \DateTime($PHPEndDateObject->format('Y-02-29'));
                    if (!$isLeapStartYear && !$wasLeapEndYear && $isLeapEndYear && $PHPEndDateObject >= $limit) {
                        --$retVal;
                    }
                }

                break;
            default:
                $retVal = Functions::VALUE();
        }

        return $retVal;
    }

    /**
     * DAYS360.
     *
     * Returns the number of days between two dates based on a 360-day year (twelve 30-day months),
     * which is used in some accounting calculations. Use this function to help compute payments if
     * your accounting system is based on twelve 30-day months.
     *
     * Excel Function:
     *        DAYS360(startDate,endDate[,method])
     *
     * @category Date/Time Functions
     *
     * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
     *                                        PHP DateTime object, or a standard date string
     * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer),
     *                                        PHP DateTime object, or a standard date string
     * @param bool $method US or European Method
     *                                        FALSE or omitted: U.S. (NASD) method. If the starting date is
     *                                        the last day of a month, it becomes equal to the 30th of the
     *                                        same month. If the ending date is the last day of a month and
     *                                        the starting date is earlier than the 30th of a month, the
     *                                        ending date becomes equal to the 1st of the next month;
     *                                        otherwise the ending date becomes equal to the 30th of the
     *                                        same month.
     *                                        TRUE: European method. Starting dates and ending dates that
     *                                        occur on the 31st of a month become equal to the 30th of the
     *                                        same month.
     *
     * @return int Number of days between start date and end date
     */
    public static function DAYS360($startDate = 0, $endDate = 0, $method = false)
    {
        $startDate = Functions::flattenSingleValue($startDate);
        $endDate = Functions::flattenSingleValue($endDate);

        if (is_string($startDate = self::getDateValue($startDate))) {
            return Functions::VALUE();
        }
        if (is_string($endDate = self::getDateValue($endDate))) {
            return Functions::VALUE();
        }

        if (!is_bool($method)) {
            return Functions::VALUE();
        }

        // Execute function
        $PHPStartDateObject = Date::excelToDateTimeObject($startDate);
        $startDay = $PHPStartDateObject->format('j');
        $startMonth = $PHPStartDateObject->format('n');
        $startYear = $PHPStartDateObject->format('Y');

        $PHPEndDateObject = Date::excelToDateTimeObject($endDate);
        $endDay = $PHPEndDateObject->format('j');
        $endMonth = $PHPEndDateObject->format('n');
        $endYear = $PHPEndDateObject->format('Y');

        return self::dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, !$method);
    }

    /**
     * YEARFRAC.
     *
     * Calculates the fraction of the year represented by the number of whole days between two dates
     * (the start_date and the end_date).
     * Use the YEARFRAC worksheet function to identify the proportion of a whole year's benefits or
     * obligations to assign to a specific term.
     *
     * Excel Function:
     *        YEARFRAC(startDate,endDate[,method])
     *
     * @category Date/Time Functions
     *
     * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
     *                                    PHP DateTime object, or a standard date string
     * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer),
     *                                    PHP DateTime object, or a standard date string
     * @param int $method Method used for the calculation
     *                                        0 or omitted    US (NASD) 30/360
     *                                        1                Actual/actual
     *                                        2                Actual/360
     *                                        3                Actual/365
     *                                        4                European 30/360
     *
     * @return float fraction of the year
     */
    public static function YEARFRAC($startDate = 0, $endDate = 0, $method = 0)
    {
        $startDate = Functions::flattenSingleValue($startDate);
        $endDate = Functions::flattenSingleValue($endDate);
        $method = Functions::flattenSingleValue($method);

        if (is_string($startDate = self::getDateValue($startDate))) {
            return Functions::VALUE();
        }
        if (is_string($endDate = self::getDateValue($endDate))) {
            return Functions::VALUE();
        }

        if (((is_numeric($method)) && (!is_string($method))) || ($method == '')) {
            switch ($method) {
                case 0:
                    return self::DAYS360($startDate, $endDate) / 360;
                case 1:
                    $days = self::DATEDIF($startDate, $endDate);
                    $startYear = self::YEAR($startDate);
                    $endYear = self::YEAR($endDate);
                    $years = $endYear - $startYear + 1;
                    $leapDays = 0;
                    if ($years == 1) {
                        if (self::isLeapYear($endYear)) {
                            $startMonth = self::MONTHOFYEAR($startDate);
                            $endMonth = self::MONTHOFYEAR($endDate);
                            $endDay = self::DAYOFMONTH($endDate);
                            if (($startMonth < 3) ||
                                (($endMonth * 100 + $endDay) >= (2 * 100 + 29))) {
                                $leapDays += 1;
                            }
                        }
                    } else {
                        for ($year = $startYear; $year <= $endYear; ++$year) {
                            if ($year == $startYear) {
                                $startMonth = self::MONTHOFYEAR($startDate);
                                $startDay = self::DAYOFMONTH($startDate);
                                if ($startMonth < 3) {
                                    $leapDays += (self::isLeapYear($year)) ? 1 : 0;
                                }
                            } elseif ($year == $endYear) {
                                $endMonth = self::MONTHOFYEAR($endDate);
                                $endDay = self::DAYOFMONTH($endDate);
                                if (($endMonth * 100 + $endDay) >= (2 * 100 + 29)) {
                                    $leapDays += (self::isLeapYear($year)) ? 1 : 0;
                                }
                            } else {
                                $leapDays += (self::isLeapYear($year)) ? 1 : 0;
                            }
                        }
                        if ($years == 2) {
                            if (($leapDays == 0) && (self::isLeapYear($startYear)) && ($days > 365)) {
                                $leapDays = 1;
                            } elseif ($days < 366) {
                                $years = 1;
                            }
                        }
                        $leapDays /= $years;
                    }

                    return $days / (365 + $leapDays);
                case 2:
                    return self::DATEDIF($startDate, $endDate) / 360;
                case 3:
                    return self::DATEDIF($startDate, $endDate) / 365;
                case 4:
                    return self::DAYS360($startDate, $endDate, true) / 360;
            }
        }

        return Functions::VALUE();
    }

    /**
     * NETWORKDAYS.
     *
     * Returns the number of whole working days between start_date and end_date. Working days
     * exclude weekends and any dates identified in holidays.
     * Use NETWORKDAYS to calculate employee benefits that accrue based on the number of days
     * worked during a specific term.
     *
     * Excel Function:
     *        NETWORKDAYS(startDate,endDate[,holidays[,holiday[,...]]])
     *
     * @category Date/Time Functions
     *
     * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
     *                                            PHP DateTime object, or a standard date string
     * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer),
     *                                            PHP DateTime object, or a standard date string
     *
     * @return int Interval between the dates
     */
    public static function NETWORKDAYS($startDate, $endDate, ...$dateArgs)
    {
        //    Retrieve the mandatory start and end date that are referenced in the function definition
        $startDate = Functions::flattenSingleValue($startDate);
        $endDate = Functions::flattenSingleValue($endDate);
        //    Get the optional days
        $dateArgs = Functions::flattenArray($dateArgs);

        //    Validate the start and end dates
        if (is_string($startDate = $sDate = self::getDateValue($startDate))) {
            return Functions::VALUE();
        }
        $startDate = (float) floor($startDate);
        if (is_string($endDate = $eDate = self::getDateValue($endDate))) {
            return Functions::VALUE();
        }
        $endDate = (float) floor($endDate);

        if ($sDate > $eDate) {
            $startDate = $eDate;
            $endDate = $sDate;
        }

        // Execute function
        $startDoW = 6 - self::WEEKDAY($startDate, 2);
        if ($startDoW < 0) {
            $startDoW = 0;
        }
        $endDoW = self::WEEKDAY($endDate, 2);
        if ($endDoW >= 6) {
            $endDoW = 0;
        }

        $wholeWeekDays = floor(($endDate - $startDate) / 7) * 5;
        $partWeekDays = $endDoW + $startDoW;
        if ($partWeekDays > 5) {
            $partWeekDays -= 5;
        }

        //    Test any extra holiday parameters
        $holidayCountedArray = [];
        foreach ($dateArgs as $holidayDate) {
            if (is_string($holidayDate = self::getDateValue($holidayDate))) {
                return Functions::VALUE();
            }
            if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) {
                if ((self::WEEKDAY($holidayDate, 2) < 6) && (!in_array($holidayDate, $holidayCountedArray))) {
                    --$partWeekDays;
                    $holidayCountedArray[] = $holidayDate;
                }
            }
        }

        if ($sDate > $eDate) {
            return 0 - ($wholeWeekDays + $partWeekDays);
        }

        return $wholeWeekDays + $partWeekDays;
    }

    /**
     * WORKDAY.
     *
     * Returns the date that is the indicated number of working days before or after a date (the
     * starting date). Working days exclude weekends and any dates identified as holidays.
     * Use WORKDAY to exclude weekends or holidays when you calculate invoice due dates, expected
     * delivery times, or the number of days of work performed.
     *
     * Excel Function:
     *        WORKDAY(startDate,endDays[,holidays[,holiday[,...]]])
     *
     * @category Date/Time Functions
     *
     * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
     *                                        PHP DateTime object, or a standard date string
     * @param int $endDays The number of nonweekend and nonholiday days before or after
     *                                        startDate. A positive value for days yields a future date; a
     *                                        negative value yields a past date.
     *
     * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
     *                        depending on the value of the ReturnDateType flag
     */
    public static function WORKDAY($startDate, $endDays, ...$dateArgs)
    {
        //    Retrieve the mandatory start date and days that are referenced in the function definition
        $startDate = Functions::flattenSingleValue($startDate);
        $endDays = Functions::flattenSingleValue($endDays);
        //    Get the optional days
        $dateArgs = Functions::flattenArray($dateArgs);

        if ((is_string($startDate = self::getDateValue($startDate))) || (!is_numeric($endDays))) {
            return Functions::VALUE();
        }
        $startDate = (float) floor($startDate);
        $endDays = (int) floor($endDays);
        //    If endDays is 0, we always return startDate
        if ($endDays == 0) {
            return $startDate;
        }

        $decrementing = ($endDays < 0) ? true : false;

        //    Adjust the start date if it falls over a weekend

        $startDoW = self::WEEKDAY($startDate, 3);
        if (self::WEEKDAY($startDate, 3) >= 5) {
            $startDate += ($decrementing) ? -$startDoW + 4 : 7 - $startDoW;
            ($decrementing) ? $endDays++ : $endDays--;
        }

        //    Add endDays
        $endDate = (float) $startDate + ((int) ($endDays / 5) * 7) + ($endDays % 5);

        //    Adjust the calculated end date if it falls over a weekend
        $endDoW = self::WEEKDAY($endDate, 3);
        if ($endDoW >= 5) {
            $endDate += ($decrementing) ? -$endDoW + 4 : 7 - $endDoW;
        }

        //    Test any extra holiday parameters
        if (!empty($dateArgs)) {
            $holidayCountedArray = $holidayDates = [];
            foreach ($dateArgs as $holidayDate) {
                if (($holidayDate !== null) && (trim($holidayDate) > '')) {
                    if (is_string($holidayDate = self::getDateValue($holidayDate))) {
                        return Functions::VALUE();
                    }
                    if (self::WEEKDAY($holidayDate, 3) < 5) {
                        $holidayDates[] = $holidayDate;
                    }
                }
            }
            if ($decrementing) {
                rsort($holidayDates, SORT_NUMERIC);
            } else {
                sort($holidayDates, SORT_NUMERIC);
            }
            foreach ($holidayDates as $holidayDate) {
                if ($decrementing) {
                    if (($holidayDate <= $startDate) && ($holidayDate >= $endDate)) {
                        if (!in_array($holidayDate, $holidayCountedArray)) {
                            --$endDate;
                            $holidayCountedArray[] = $holidayDate;
                        }
                    }
                } else {
                    if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) {
                        if (!in_array($holidayDate, $holidayCountedArray)) {
                            ++$endDate;
                            $holidayCountedArray[] = $holidayDate;
                        }
                    }
                }
                //    Adjust the calculated end date if it falls over a weekend
                $endDoW = self::WEEKDAY($endDate, 3);
                if ($endDoW >= 5) {
                    $endDate += ($decrementing) ? -$endDoW + 4 : 7 - $endDoW;
                }
            }
        }

        switch (Functions::getReturnDateType()) {
            case Functions::RETURNDATE_EXCEL:
                return (float) $endDate;
            case Functions::RETURNDATE_PHP_NUMERIC:
                return (int) Date::excelToTimestamp($endDate);
            case Functions::RETURNDATE_PHP_OBJECT:
                return Date::excelToDateTimeObject($endDate);
        }
    }

    /**
     * DAYOFMONTH.
     *
     * Returns the day of the month, for a specified date. The day is given as an integer
     * ranging from 1 to 31.
     *
     * Excel Function:
     *        DAY(dateValue)
     *
     * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
     *                                    PHP DateTime object, or a standard date string
     *
     * @return int Day of the month
     */
    public static function DAYOFMONTH($dateValue = 1)
    {
        $dateValue = Functions::flattenSingleValue($dateValue);

        if ($dateValue === null) {
            $dateValue = 1;
        } elseif (is_string($dateValue = self::getDateValue($dateValue))) {
            return Functions::VALUE();
        }

        if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_EXCEL) {
            if ($dateValue < 0.0) {
                return Functions::NAN();
            } elseif ($dateValue < 1.0) {
                return 0;
            }
        }

        // Execute function
        $PHPDateObject = Date::excelToDateTimeObject($dateValue);

        return (int) $PHPDateObject->format('j');
    }

    /**
     * WEEKDAY.
     *
     * Returns the day of the week for a specified date. The day is given as an integer
     * ranging from 0 to 7 (dependent on the requested style).
     *
     * Excel Function:
     *        WEEKDAY(dateValue[,style])
     *
     * @param int $dateValue Excel date serial value (float), PHP date timestamp (integer),
     *                                    PHP DateTime object, or a standard date string
     * @param int $style A number that determines the type of return value
     *                                        1 or omitted    Numbers 1 (Sunday) through 7 (Saturday).
     *                                        2                Numbers 1 (Monday) through 7 (Sunday).
     *                                        3                Numbers 0 (Monday) through 6 (Sunday).
     *
     * @return int Day of the week value
     */
    public static function WEEKDAY($dateValue = 1, $style = 1)
    {
        $dateValue = Functions::flattenSingleValue($dateValue);
        $style = Functions::flattenSingleValue($style);

        if (!is_numeric($style)) {
            return Functions::VALUE();
        } elseif (($style < 1) || ($style > 3)) {
            return Functions::NAN();
        }
        $style = floor($style);

        if ($dateValue === null) {
            $dateValue = 1;
        } elseif (is_string($dateValue = self::getDateValue($dateValue))) {
            return Functions::VALUE();
        } elseif ($dateValue < 0.0) {
            return Functions::NAN();
        }

        // Execute function
        $PHPDateObject = Date::excelToDateTimeObject($dateValue);
        $DoW = $PHPDateObject->format('w');

        $firstDay = 1;
        switch ($style) {
            case 1:
                ++$DoW;

                break;
            case 2:
                if ($DoW == 0) {
                    $DoW = 7;
                }

                break;
            case 3:
                if ($DoW == 0) {
                    $DoW = 7;
                }
                $firstDay = 0;
                --$DoW;

                break;
        }
        if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_EXCEL) {
            //    Test for Excel's 1900 leap year, and introduce the error as required
            if (($PHPDateObject->format('Y') == 1900) && ($PHPDateObject->format('n') <= 2)) {
                --$DoW;
                if ($DoW < $firstDay) {
                    $DoW += 7;
                }
            }
        }

        return (int) $DoW;
    }

    /**
     * WEEKNUM.
     *
     * Returns the week of the year for a specified date.
     * The WEEKNUM function considers the week containing January 1 to be the first week of the year.
     * However, there is a European standard that defines the first week as the one with the majority
     * of days (four or more) falling in the new year. This means that for years in which there are
     * three days or less in the first week of January, the WEEKNUM function returns week numbers
     * that are incorrect according to the European standard.
     *
     * Excel Function:
     *        WEEKNUM(dateValue[,style])
     *
     * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
     *                                    PHP DateTime object, or a standard date string
     * @param int $method Week begins on Sunday or Monday
     *                                        1 or omitted    Week begins on Sunday.
     *                                        2                Week begins on Monday.
     *
     * @return int Week Number
     */
    public static function WEEKNUM($dateValue = 1, $method = 1)
    {
        $dateValue = Functions::flattenSingleValue($dateValue);
        $method = Functions::flattenSingleValue($method);

        if (!is_numeric($method)) {
            return Functions::VALUE();
        } elseif (($method < 1) || ($method > 2)) {
            return Functions::NAN();
        }
        $method = floor($method);

        if ($dateValue === null) {
            $dateValue = 1;
        } elseif (is_string($dateValue = self::getDateValue($dateValue))) {
            return Functions::VALUE();
        } elseif ($dateValue < 0.0) {
            return Functions::NAN();
        }

        // Execute function
        $PHPDateObject = Date::excelToDateTimeObject($dateValue);
        $dayOfYear = $PHPDateObject->format('z');
        $PHPDateObject->modify('-' . $dayOfYear . ' days');
        $firstDayOfFirstWeek = $PHPDateObject->format('w');
        $daysInFirstWeek = (6 - $firstDayOfFirstWeek + $method) % 7;
        $interval = $dayOfYear - $daysInFirstWeek;
        $weekOfYear = floor($interval / 7) + 1;

        if ($daysInFirstWeek) {
            ++$weekOfYear;
        }

        return (int) $weekOfYear;
    }

    /**
     * MONTHOFYEAR.
     *
     * Returns the month of a date represented by a serial number.
     * The month is given as an integer, ranging from 1 (January) to 12 (December).
     *
     * Excel Function:
     *        MONTH(dateValue)
     *
     * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
     *                                    PHP DateTime object, or a standard date string
     *
     * @return int Month of the year
     */
    public static function MONTHOFYEAR($dateValue = 1)
    {
        $dateValue = Functions::flattenSingleValue($dateValue);

        if (empty($dateValue)) {
            $dateValue = 1;
        }
        if (is_string($dateValue = self::getDateValue($dateValue))) {
            return Functions::VALUE();
        } elseif ($dateValue < 0.0) {
            return Functions::NAN();
        }

        // Execute function
        $PHPDateObject = Date::excelToDateTimeObject($dateValue);

        return (int) $PHPDateObject->format('n');
    }

    /**
     * YEAR.
     *
     * Returns the year corresponding to a date.
     * The year is returned as an integer in the range 1900-9999.
     *
     * Excel Function:
     *        YEAR(dateValue)
     *
     * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
     *                                    PHP DateTime object, or a standard date string
     *
     * @return int Year
     */
    public static function YEAR($dateValue = 1)
    {
        $dateValue = Functions::flattenSingleValue($dateValue);

        if ($dateValue === null) {
            $dateValue = 1;
        } elseif (is_string($dateValue = self::getDateValue($dateValue))) {
            return Functions::VALUE();
        } elseif ($dateValue < 0.0) {
            return Functions::NAN();
        }

        // Execute function
        $PHPDateObject = Date::excelToDateTimeObject($dateValue);

        return (int) $PHPDateObject->format('Y');
    }

    /**
     * HOUROFDAY.
     *
     * Returns the hour of a time value.
     * The hour is given as an integer, ranging from 0 (12:00 A.M.) to 23 (11:00 P.M.).
     *
     * Excel Function:
     *        HOUR(timeValue)
     *
     * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer),
     *                                    PHP DateTime object, or a standard time string
     *
     * @return int Hour
     */
    public static function HOUROFDAY($timeValue = 0)
    {
        $timeValue = Functions::flattenSingleValue($timeValue);

        if (!is_numeric($timeValue)) {
            if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) {
                $testVal = strtok($timeValue, '/-: ');
                if (strlen($testVal) < strlen($timeValue)) {
                    return Functions::VALUE();
                }
            }
            $timeValue = self::getTimeValue($timeValue);
            if (is_string($timeValue)) {
                return Functions::VALUE();
            }
        }
        // Execute function
        if ($timeValue >= 1) {
            $timeValue = fmod($timeValue, 1);
        } elseif ($timeValue < 0.0) {
            return Functions::NAN();
        }
        $timeValue = Date::excelToTimestamp($timeValue);

        return (int) gmdate('G', $timeValue);
    }

    /**
     * MINUTE.
     *
     * Returns the minutes of a time value.
     * The minute is given as an integer, ranging from 0 to 59.
     *
     * Excel Function:
     *        MINUTE(timeValue)
     *
     * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer),
     *                                    PHP DateTime object, or a standard time string
     *
     * @return int Minute
     */
    public static function MINUTE($timeValue = 0)
    {
        $timeValue = $timeTester = Functions::flattenSingleValue($timeValue);

        if (!is_numeric($timeValue)) {
            if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) {
                $testVal = strtok($timeValue, '/-: ');
                if (strlen($testVal) < strlen($timeValue)) {
                    return Functions::VALUE();
                }
            }
            $timeValue = self::getTimeValue($timeValue);
            if (is_string($timeValue)) {
                return Functions::VALUE();
            }
        }
        // Execute function
        if ($timeValue >= 1) {
            $timeValue = fmod($timeValue, 1);
        } elseif ($timeValue < 0.0) {
            return Functions::NAN();
        }
        $timeValue = Date::excelToTimestamp($timeValue);

        return (int) gmdate('i', $timeValue);
    }

    /**
     * SECOND.
     *
     * Returns the seconds of a time value.
     * The second is given as an integer in the range 0 (zero) to 59.
     *
     * Excel Function:
     *        SECOND(timeValue)
     *
     * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer),
     *                                    PHP DateTime object, or a standard time string
     *
     * @return int Second
     */
    public static function SECOND($timeValue = 0)
    {
        $timeValue = Functions::flattenSingleValue($timeValue);

        if (!is_numeric($timeValue)) {
            if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) {
                $testVal = strtok($timeValue, '/-: ');
                if (strlen($testVal) < strlen($timeValue)) {
                    return Functions::VALUE();
                }
            }
            $timeValue = self::getTimeValue($timeValue);
            if (is_string($timeValue)) {
                return Functions::VALUE();
            }
        }
        // Execute function
        if ($timeValue >= 1) {
            $timeValue = fmod($timeValue, 1);
        } elseif ($timeValue < 0.0) {
            return Functions::NAN();
        }
        $timeValue = Date::excelToTimestamp($timeValue);

        return (int) gmdate('s', $timeValue);
    }

    /**
     * EDATE.
     *
     * Returns the serial number that represents the date that is the indicated number of months
     * before or after a specified date (the start_date).
     * Use EDATE to calculate maturity dates or due dates that fall on the same day of the month
     * as the date of issue.
     *
     * Excel Function:
     *        EDATE(dateValue,adjustmentMonths)
     *
     * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
     *                                        PHP DateTime object, or a standard date string
     * @param int $adjustmentMonths The number of months before or after start_date.
     *                                        A positive value for months yields a future date;
     *                                        a negative value yields a past date.
     *
     * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
     *                        depending on the value of the ReturnDateType flag
     */
    public static function EDATE($dateValue = 1, $adjustmentMonths = 0)
    {
        $dateValue = Functions::flattenSingleValue($dateValue);
        $adjustmentMonths = Functions::flattenSingleValue($adjustmentMonths);

        if (!is_numeric($adjustmentMonths)) {
            return Functions::VALUE();
        }
        $adjustmentMonths = floor($adjustmentMonths);

        if (is_string($dateValue = self::getDateValue($dateValue))) {
            return Functions::VALUE();
        }

        // Execute function
        $PHPDateObject = self::adjustDateByMonths($dateValue, $adjustmentMonths);

        switch (Functions::getReturnDateType()) {
            case Functions::RETURNDATE_EXCEL:
                return (float) Date::PHPToExcel($PHPDateObject);
            case Functions::RETURNDATE_PHP_NUMERIC:
                return (int) Date::excelToTimestamp(Date::PHPToExcel($PHPDateObject));
            case Functions::RETURNDATE_PHP_OBJECT:
                return $PHPDateObject;
        }
    }

    /**
     * EOMONTH.
     *
     * Returns the date value for the last day of the month that is the indicated number of months
     * before or after start_date.
     * Use EOMONTH to calculate maturity dates or due dates that fall on the last day of the month.
     *
     * Excel Function:
     *        EOMONTH(dateValue,adjustmentMonths)
     *
     * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
     *                                        PHP DateTime object, or a standard date string
     * @param int $adjustmentMonths The number of months before or after start_date.
     *                                        A positive value for months yields a future date;
     *                                        a negative value yields a past date.
     *
     * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
     *                        depending on the value of the ReturnDateType flag
     */
    public static function EOMONTH($dateValue = 1, $adjustmentMonths = 0)
    {
        $dateValue = Functions::flattenSingleValue($dateValue);
        $adjustmentMonths = Functions::flattenSingleValue($adjustmentMonths);

        if (!is_numeric($adjustmentMonths)) {
            return Functions::VALUE();
        }
        $adjustmentMonths = floor($adjustmentMonths);

        if (is_string($dateValue = self::getDateValue($dateValue))) {
            return Functions::VALUE();
        }

        // Execute function
        $PHPDateObject = self::adjustDateByMonths($dateValue, $adjustmentMonths + 1);
        $adjustDays = (int) $PHPDateObject->format('d');
        $adjustDaysString = '-' . $adjustDays . ' days';
        $PHPDateObject->modify($adjustDaysString);

        switch (Functions::getReturnDateType()) {
            case Functions::RETURNDATE_EXCEL:
                return (float) Date::PHPToExcel($PHPDateObject);
            case Functions::RETURNDATE_PHP_NUMERIC:
                return (int) Date::excelToTimestamp(Date::PHPToExcel($PHPDateObject));
            case Functions::RETURNDATE_PHP_OBJECT:
                return $PHPDateObject;
        }
    }
}


<?php
/**
 * Autoload file
 *
 * This file is part of periodic
 *
 * periodic is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; version 3 of the License.
 *
 * periodic is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
 * more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with periodic; if not, write to the Free Software Foundation, Inc., 51
 * Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @package Core
 * @version $Revision: 999 $
 * @license http://www.gnu.org/licenses/lgpl-3.0.txt LGPL
 */

namespace Arbit\Periodic\Logger;

use Arbit\Periodic\Logger;

/**
 * Command line logger
 *
 * Logger, which logs messages directly to command line. By default errors and
 * warnings will be logged to STDERR, while info messages are printed to
 * STDOUT.
 */
class Cli extends Logger
{
    /**
     * Mapping of error levels to pipes
     *
     * @var array
     */
    protected $mapping = array(
        Logger::INFO    => self::STDOUT,
        Logger::WARNING => self::STDERR,
        Logger::ERROR   => self::STDERR,
    );

    /**
     * Do not print any message
     */
    const SILENCE = 0;

    /**
     * Print message to STDOUT
     */
    const STDOUT = 1;

    /**
     * Print message to STDERR
     */
    const STDERR = 2;

    /**
     * Write text to stream
     *
     * Write given text to given stream. Simple wrapper function to make class
     * testable.
     *
     * @param string $stream
     * @param string $text
     * @return void
     */
    protected function write( $stream, $text )
    {
        $fp = fopen( $stream, 'a' );
        fwrite( $fp, $text );
        fclose( $fp );
    }

    /**
     * Log message
     *
     * Log a message, while the message must be convertable into a string.
     * Optionally a log message severity can be specified.
     *
     * @param string $message
     * @param int $severity
     * @return void
     */
    public function log( $message, $severity = self::INFO )
    {
        if ( !isset( $this->mapping[$severity] ) )
        {
            throw new \RuntimeException( "Unknown severity: " . $severity );
        }

        switch ( $pipe = $this->mapping[$severity] )
        {
            case self::SILENCE:
                // Ignore this message
                return;

            case self::STDOUT:
                $stream = 'php://stdout';
                break;

            case self::STDERR:
                $stream = 'php://stderr';
                break;

            default:
                throw new \RuntimeException( "Unknown output pipe: " . $pipe );
        }

        // Generate and output error message
        $this->write( $stream, sprintf( "[%s]%s %s: %s\n",
            date( 'Y/m/d-H:i.s' ),
            ( $this->task ?
                ' (' . $this->task . (
                    $this->command ?
                        '::' . $this->command :
                        ''
                ) . ')' :
                ''
            ),
            $this->names[$severity],
            $message
        ) );
    }

    /**
     * Set output pipe for severity
     *
     * Set the designated output pipe for log messages with the givene
     * severity. The available severities are defined in the logger interface
     * and are:
     *
     * - Logger::INFO
     * - Logger::WARNING
     * - Logger::ERROR
     *
     * The available output pipes are:
     *
     * - Cli::SILENCE, do not output anything
     * - Cli::STDOUT, echo messages to STDOUT
     * - Cli::STDERR, echo messages to STDERR
     *
     * @param int $severity
     * @param int $pipe
     * @return void
     */
    public function setMapping( $severity, $pipe )
    {
        if ( !isset( $this->mapping[$severity] ) )
        {
            throw new \RuntimeException( "Unknown severity: " . $severity );
        }

        if ( ( $pipe !== self::SILENCE ) &&
             ( $pipe !== self::STDOUT ) &&
             ( $pipe !== self::STDERR ) )
        {
            throw new \RuntimeException( "Unknown output pipe: " . $pipe );
        }

        $this->mapping[$severity] = $pipe;
    }
}