From 821c4f7b4a6686d8def812e4a467a24cf6f0dcc0 Mon Sep 17 00:00:00 2001 From: Matias Griese Date: Fri, 19 Jan 2018 20:09:51 +0200 Subject: [PATCH] Clean up Utils class with minor fixes (#1830) --- system/src/Grav/Common/Utils.php | 194 +++++++++++++++++-------------- 1 file changed, 105 insertions(+), 89 deletions(-) diff --git a/system/src/Grav/Common/Utils.php b/system/src/Grav/Common/Utils.php index ba912c857..9193a6708 100644 --- a/system/src/Grav/Common/Utils.php +++ b/system/src/Grav/Common/Utils.php @@ -10,7 +10,9 @@ namespace Grav\Common; use DateTime; use Grav\Common\Helpers\Truncator; +use Grav\Common\Page\Page; use RocketTheme\Toolbox\Event\Event; +use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator; abstract class Utils { @@ -59,63 +61,66 @@ abstract class Utils * Check if the $haystack string starts with the substring $needle * * @param string $haystack - * @param string $needle + * @param string|string[] $needle * * @return bool */ public static function startsWith($haystack, $needle) { - if (is_array($needle)) { - $status = false; - foreach ($needle as $each_needle) { - $status = $status || ($each_needle === '' || strpos($haystack, $each_needle) === 0); - if ($status) { - return $status; - } - } + $status = false; - return $status; + foreach ((array)$needle as $each_needle) { + $status = $each_needle === '' || strpos($haystack, $each_needle) === 0; + if ($status) { + break; + } } - return $needle === '' || strpos($haystack, $needle) === 0; + return $status; } /** * Check if the $haystack string ends with the substring $needle * * @param string $haystack - * @param string $needle + * @param string|string[] $needle * * @return bool */ public static function endsWith($haystack, $needle) { - if (is_array($needle)) { - $status = false; - foreach ($needle as $each_needle) { - $status = $status || ($each_needle === '' || substr($haystack, -strlen($each_needle)) === $each_needle); - if ($status) { - return $status; - } - } + $status = false; - return $status; + foreach ((array)$needle as $each_needle) { + $status = $each_needle === '' || substr($haystack, -strlen($each_needle)) === $each_needle; + if ($status) { + break; + } } - return $needle === '' || substr($haystack, -strlen($needle)) === $needle; + return $status; } /** * Check if the $haystack string contains the substring $needle * * @param string $haystack - * @param string $needle + * @param string|string[] $needle * * @return bool */ public static function contains($haystack, $needle) { - return $needle === '' || strpos($haystack, $needle) !== false; + $status = false; + + foreach ((array)$needle as $each_needle) { + $status = $each_needle === '' || strpos($haystack, $each_needle) !== false; + if ($status) { + break; + } + } + + return $status; } /** @@ -197,14 +202,18 @@ abstract class Utils */ public static function arrayMergeRecursiveUnique($array1, $array2) { - if (empty($array1)) return $array2; //optimize the base case + if (empty($array1)) { + // Optimize the base case + return $array2; + } foreach ($array2 as $key => $value) { - if (is_array($value) && is_array(@$array1[$key])) { + if (is_array($value) && isset($array1[$key]) && is_array($array1[$key])) { $value = static::arrayMergeRecursiveUnique($array1[$key], $value); } $array1[$key] = $value; } + return $array1; } @@ -289,9 +298,9 @@ abstract class Utils { if (mb_strlen($text) <= $length) { return $text; - } else { - return Truncator::truncateLetters($text, $length, $ellipsis); } + + return Truncator::truncateLetters($text, $length, $ellipsis); } /** @@ -317,7 +326,7 @@ abstract class Utils */ public static function generateRandomString($length = 5) { - return substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length); + return substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, $length); } /** @@ -336,7 +345,7 @@ abstract class Utils Grav::instance()->fireEvent('onBeforeDownload', new Event(['file' => $file])); $file_parts = pathinfo($file); - $mimetype = Utils::getMimeByExtension($file_parts['extension']); + $mimetype = static::getMimeByExtension($file_parts['extension']); $size = filesize($file); // File size // clean all buffers @@ -349,7 +358,7 @@ abstract class Utils ini_set('zlib.output_compression', 'Off'); } - header("Content-Type: " . $mimetype); + header('Content-Type: ' . $mimetype); header('Accept-Ranges: bytes'); if ($force_download) { @@ -359,22 +368,23 @@ abstract class Utils // multipart-download and download resuming support if (isset($_SERVER['HTTP_RANGE'])) { - list($a, $range) = explode("=", $_SERVER['HTTP_RANGE'], 2); - list($range) = explode(",", $range, 2); - list($range, $range_end) = explode("-", $range); - $range = intval($range); + list($a, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2); + list($range) = explode(',', $range, 2); + list($range, $range_end) = explode('-', $range); + $range = (int)$range; if (!$range_end) { $range_end = $size - 1; } else { - $range_end = intval($range_end); + $range_end = (int)$range_end; } $new_length = $range_end - $range + 1; - header("HTTP/1.1 206 Partial Content"); - header("Content-Length: $new_length"); - header("Content-Range: bytes $range-$range_end/$size"); + header('HTTP/1.1 206 Partial Content'); + header("Content-Length: {$new_length}"); + header("Content-Range: bytes {$range}-{$range_end}/{$size}"); } else { + $range = 0; $new_length = $size; - header("Content-Length: " . $size); + header('Content-Length: ' . $size); if (Grav::instance()['config']->get('system.cache.enabled')) { $expires = Grav::instance()['config']->get('system.pages.expires'); @@ -384,7 +394,7 @@ abstract class Utils header('Expires: ' . $expires_date); header('Pragma: cache'); } - header('Last-Modified: ' . gmdate("D, d M Y H:i:s T", filemtime($file))); + header('Last-Modified: ' . gmdate('D, d M Y H:i:s T', filemtime($file))); // Return 304 Not Modified if the file is already cached in the browser if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && @@ -400,9 +410,9 @@ abstract class Utils $chunksize = $bytes * 8; //you may want to change this $bytes_send = 0; - $fp = @fopen($file, 'r'); + $fp = @fopen($file, 'rb'); if ($fp) { - if (isset($_SERVER['HTTP_RANGE'])) { + if ($range) { fseek($fp, $range); } while (!feof($fp) && (!connection_aborted()) && ($bytes_send < $new_length) ) { @@ -414,7 +424,7 @@ abstract class Utils } fclose($fp); } else { - throw new \Exception('Error - can not open file.'); + throw new \RuntimeException('Error - can not open file.'); } exit; @@ -488,13 +498,13 @@ abstract class Utils return 'xml'; } - $media_types = Grav::instance()['config']->get('media.types'); + $media_types = (array)Grav::instance()['config']->get('media.types'); foreach ($media_types as $extension => $type) { - if ($extension == 'defaults') { + if ($extension === 'defaults') { continue; } - if (isset($type['mime']) && $type['mime'] == $mime) { + if (isset($type['mime']) && $type['mime'] === $mime) { return $extension; } } @@ -516,13 +526,13 @@ abstract class Utils $segments = explode('/', trim($path, '/')); $ret = []; foreach ($segments as $segment) { - if (($segment == '.') || strlen($segment) == 0) { + if (($segment === '.') || $segment === '') { continue; } - if ($segment == '..') { + if ($segment === '..') { array_pop($ret); } else { - array_push($ret, $segment); + $ret[] = $segment; } } @@ -538,7 +548,7 @@ abstract class Utils */ public static function isFunctionDisabled($function) { - return in_array($function, explode(',', ini_get('disable_functions'))); + return in_array($function, explode(',', ini_get('disable_functions')), true); } /** @@ -600,7 +610,7 @@ abstract class Utils /** * Flatten an array * - * @param $array + * @param array $array * @return array */ public static function arrayFlatten($array) @@ -633,7 +643,7 @@ abstract class Utils $languages_enabled = Grav::instance()['config']->get('system.languages.supported', []); - if ($string[0] == '/' && $string[3] == '/' && in_array(substr($string, 1, 2), $languages_enabled)) { + if ($string[0] === '/' && $string[3] === '/' && in_array(substr($string, 1, 2), $languages_enabled)) { return true; } @@ -660,17 +670,21 @@ abstract class Utils $datetime = new DateTime($date); } - // fallback to strtotime if DateTime approach failed + // fallback to strtotime() if DateTime approach failed if ($datetime !== false) { return $datetime->getTimestamp(); - } else { - return strtotime($date); } + + return strtotime($date); } /** - * @deprecated Use getDotNotation() method instead + * @param array $array + * @param string $path + * @param null $default + * @return mixed * + * @deprecated Use getDotNotation() method instead */ public static function resolve(array $array, $path, $default = null) { @@ -750,7 +764,7 @@ abstract class Utils { $secondsInHalfADay = 60 * 60 * 12; - return (int)ceil(time() / ($secondsInHalfADay)); + return (int)ceil(time() / $secondsInHalfADay); } /** @@ -790,7 +804,7 @@ abstract class Utils /** * Verify the passed nonce for the give action * - * @param string $nonce the nonce to verify + * @param string|string[] $nonce the nonce to verify * @param string $action the action to verify the nonce to * * @return boolean verified or not @@ -803,26 +817,25 @@ abstract class Utils } //Nonce generated 0-12 hours ago - if ($nonce == self::getNonce($action)) { + if ($nonce === self::getNonce($action)) { return true; } //Nonce generated 12-24 hours ago $plusOneTick = true; - if ($nonce == self::getNonce($action, $plusOneTick)) { + if ($nonce === self::getNonce($action, $plusOneTick)) { return true; } - //Added in version 1.0.8 to ensure that existing nonces are not broken. //Nonce generated 0-12 hours ago - if ($nonce == self::getNonceOldStyle($action)) { + if ($nonce === self::getNonceOldStyle($action)) { return true; } //Nonce generated 12-24 hours ago $plusOneTick = true; - if ($nonce == self::getNonceOldStyle($action, $plusOneTick)) { + if ($nonce === self::getNonceOldStyle($action, $plusOneTick)) { return true; } @@ -854,15 +867,16 @@ abstract class Utils */ public static function getDotNotation($array, $key, $default = null) { - if (is_null($key)) return $array; + if (null === $key) { + return $array; + } - if (isset($array[$key])) return $array[$key]; + if (isset($array[$key])) { + return $array[$key]; + } - foreach (explode('.', $key) as $segment) - { - if ( ! is_array($array) || - ! array_key_exists($segment, $array)) - { + foreach (explode('.', $key) as $segment) { + if (!is_array($array) || !array_key_exists($segment, $array)) { return $default; } @@ -885,12 +899,13 @@ abstract class Utils */ public static function setDotNotation(&$array, $key, $value, $merge = false) { - if (is_null($key)) return $array = $value; + if (null === $key) { + return $array = $value; + } $keys = explode('.', $key); - while (count($keys) > 1) - { + while (count($keys) > 1) { $key = array_shift($keys); if ( ! isset($array[$key]) || ! is_array($array[$key])) @@ -918,8 +933,9 @@ abstract class Utils * * @return bool */ - public static function isWindows() { - return strncasecmp(PHP_OS, 'WIN', 3) == 0; + public static function isWindows() + { + return strncasecmp(PHP_OS, 'WIN', 3) === 0; } /** @@ -928,7 +944,7 @@ abstract class Utils * @return bool */ public static function isApache() { - return strpos($_SERVER["SERVER_SOFTWARE"], 'Apache') !== false; + return isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') !== false; } /** @@ -938,7 +954,8 @@ abstract class Utils * @param array $orderArray * @return array */ - public static function sortArrayByArray(array $array, array $orderArray) { + public static function sortArrayByArray(array $array, array $orderArray) + { $ordered = array(); foreach ($orderArray as $key) { if (array_key_exists($key, $array)) { @@ -953,8 +970,9 @@ abstract class Utils * Get's path based on a token * * @param $path - * @param null $page + * @param Page|null $page * @return string + * @throws \RuntimeException */ public static function getPagePathFromToken($path, $page = null) { @@ -972,7 +990,7 @@ abstract class Utils if ($matches) { if ($matches[1]) { - if (is_null($page)) { + if (null === $page) { throw new \RuntimeException('Page not available for this self@ reference'); } } elseif ($matches[2]) { @@ -1031,10 +1049,10 @@ abstract class Utils $unit = preg_replace('/[^bkmgtpezy]/i', '', $size); $size = preg_replace('/[^0-9\.]/', '', $size); if ($unit) { - return intval($size * pow(1024, stripos('bkmgtpezy', $unit[0]))); - } else { - return intval($size); + return (int)($size * pow(1024, stripos('bkmgtpezy', $unit[0]))); } + + return (int)$size; } /** @@ -1042,13 +1060,13 @@ abstract class Utils * * @param $url * @return mixed + * @throws \InvalidArgumentException */ public static function multibyteParseUrl($url) { $enc_url = preg_replace_callback( '%[^:/@?&=#]+%usD', - function ($matches) - { + function ($matches) { return urlencode($matches[0]); }, $url @@ -1056,13 +1074,11 @@ abstract class Utils $parts = parse_url($enc_url); - if($parts === false) - { + if($parts === false) { throw new \InvalidArgumentException('Malformed URL: ' . $url); } - foreach($parts as $name => $value) - { + foreach($parts as $name => $value) { $parts[$name] = urldecode($value); }