From 30b55ae15035faddb993446fbbdc3ea746a616f4 Mon Sep 17 00:00:00 2001 From: Matias Griese Date: Fri, 24 Sep 2021 12:19:41 +0300 Subject: [PATCH] Phpstan fixes --- system/src/Grav/Common/Assets/BaseAsset.php | 6 +++- system/src/Grav/Common/Assets/Pipeline.php | 2 +- .../Common/Assets/Traits/AssetUtilsTrait.php | 6 ++-- system/src/Grav/Common/Backup/Backups.php | 2 +- system/src/Grav/Common/Cache.php | 8 ++--- system/src/Grav/Common/Data/Blueprint.php | 4 +-- system/src/Grav/Common/Data/Data.php | 2 +- system/src/Grav/Common/Data/Validation.php | 4 +-- system/src/Grav/Common/Debugger.php | 2 +- system/src/Grav/Common/Filesystem/Folder.php | 5 +-- .../Grav/Common/Filesystem/ZipArchiver.php | 7 ++-- system/src/Grav/Common/Flex/FlexObject.php | 2 +- .../Flex/Types/Pages/PageCollection.php | 7 ++-- .../Common/Flex/Types/Pages/PageIndex.php | 19 +++++++---- .../Common/Flex/Types/Pages/PageObject.php | 12 ++++--- .../Types/Pages/Traits/PageLegacyTrait.php | 5 ++- .../Flex/Types/Users/UserCollection.php | 4 +-- .../Common/Flex/Types/Users/UserIndex.php | 4 +-- system/src/Grav/Common/Grav.php | 24 +++++++------- system/src/Grav/Common/Helpers/Excerpts.php | 7 +++- system/src/Grav/Common/Helpers/LogViewer.php | 22 +++++++------ system/src/Grav/Common/Iterator.php | 4 +-- .../Grav/Common/Language/LanguageCodes.php | 13 ++------ system/src/Grav/Common/Page/Collection.php | 2 +- system/src/Grav/Common/Page/Page.php | 4 +-- system/src/Grav/Common/Page/Pages.php | 32 ++++++++++++------- system/src/Grav/Common/Scheduler/Job.php | 2 +- system/src/Grav/Common/Security.php | 6 ++-- system/src/Grav/Common/Session.php | 4 +-- system/src/Grav/Common/Taxonomy.php | 2 +- system/src/Grav/Common/Utils.php | 20 ++++-------- 31 files changed, 125 insertions(+), 118 deletions(-) diff --git a/system/src/Grav/Common/Assets/BaseAsset.php b/system/src/Grav/Common/Assets/BaseAsset.php index 192ea81cd..a115ce9ec 100644 --- a/system/src/Grav/Common/Assets/BaseAsset.php +++ b/system/src/Grav/Common/Assets/BaseAsset.php @@ -92,6 +92,10 @@ abstract class BaseAsset extends PropertyObject */ public function init($asset, $options) { + if (!$asset) { + return false; + } + $config = Grav::instance()['config']; $uri = Grav::instance()['uri']; @@ -259,6 +263,6 @@ abstract class BaseAsset extends PropertyObject */ protected function cssRewrite($file, $dir, $local) { - return; + return ''; } } diff --git a/system/src/Grav/Common/Assets/Pipeline.php b/system/src/Grav/Common/Assets/Pipeline.php index 2e499f98f..948104ab9 100644 --- a/system/src/Grav/Common/Assets/Pipeline.php +++ b/system/src/Grav/Common/Assets/Pipeline.php @@ -254,7 +254,7 @@ class Pipeline extends PropertyObject $old_url = ltrim($old_url, '/'); } - $new_url = ($local ? $this->base_url: '') . $old_url; + $new_url = ($local ? $this->base_url : '') . $old_url; return str_replace($matches[2], $new_url, $matches[0]); }, $file); diff --git a/system/src/Grav/Common/Assets/Traits/AssetUtilsTrait.php b/system/src/Grav/Common/Assets/Traits/AssetUtilsTrait.php index ac6e55a31..3f5a690fb 100644 --- a/system/src/Grav/Common/Assets/Traits/AssetUtilsTrait.php +++ b/system/src/Grav/Common/Assets/Traits/AssetUtilsTrait.php @@ -68,8 +68,6 @@ trait AssetUtilsTrait protected function gatherLinks(array $assets, $css = true) { $buffer = ''; - - foreach ($assets as $id => $asset) { $local = true; @@ -135,7 +133,7 @@ trait AssetUtilsTrait $imports = []; - $file = (string)preg_replace_callback($regex, function ($matches) use (&$imports) { + $file = (string)preg_replace_callback($regex, static function ($matches) use (&$imports) { $imports[] = $matches[0]; return ''; @@ -200,7 +198,7 @@ trait AssetUtilsTrait } if ($this->timestamp) { - if (Utils::contains($asset, '?') || $querystring) { + if ($querystring || Utils::contains($asset, '?')) { $querystring .= '&' . $this->timestamp; } else { $querystring .= '?' . $this->timestamp; diff --git a/system/src/Grav/Common/Backup/Backups.php b/system/src/Grav/Common/Backup/Backups.php index 9483b15f7..b70def96f 100644 --- a/system/src/Grav/Common/Backup/Backups.php +++ b/system/src/Grav/Common/Backup/Backups.php @@ -222,7 +222,7 @@ class Backups $backup_root = rtrim(GRAV_ROOT . $backup_root, '/'); } - if (!file_exists($backup_root)) { + if (!$backup_root || !file_exists($backup_root)) { throw new RuntimeException("Backup location: {$backup_root} does not exist..."); } diff --git a/system/src/Grav/Common/Cache.php b/system/src/Grav/Common/Cache.php index a961904de..a50351836 100644 --- a/system/src/Grav/Common/Cache.php +++ b/system/src/Grav/Common/Cache.php @@ -141,7 +141,7 @@ class Cache extends Getters $uniqueness = substr(md5($uri->rootUrl(true) . $this->config->key() . GRAV_VERSION), 2, 8); // Cache key allows us to invalidate all cache on configuration changes. - $this->key = ($prefix ? $prefix : 'g') . '-' . $uniqueness; + $this->key = ($prefix ?: 'g') . '-' . $uniqueness; $this->cache_dir = $grav['locator']->findResource('cache://doctrine/' . $uniqueness, true, true); $this->driver_setting = $this->config->get('system.cache.driver'); $this->driver = $this->getCacheDriver(); @@ -618,11 +618,7 @@ class Cache extends Getters */ public function isVolatileDriver($setting) { - if (in_array($setting, ['apc', 'apcu', 'xcache', 'wincache'])) { - return true; - } - - return false; + return in_array($setting, ['apc', 'apcu', 'xcache', 'wincache'], true); } /** diff --git a/system/src/Grav/Common/Data/Blueprint.php b/system/src/Grav/Common/Data/Blueprint.php index 29a26369c..287819939 100644 --- a/system/src/Grav/Common/Data/Blueprint.php +++ b/system/src/Grav/Common/Data/Blueprint.php @@ -37,7 +37,7 @@ class Blueprint extends BlueprintForm /** @var string|null */ protected $scope; - /** @var BlueprintSchema */ + /** @var BlueprintSchema|null */ protected $blueprintSchema; /** @var object|null */ @@ -54,7 +54,7 @@ class Blueprint extends BlueprintForm */ public function __clone() { - if ($this->blueprintSchema) { + if (null !== $this->blueprintSchema) { $this->blueprintSchema = clone $this->blueprintSchema; } } diff --git a/system/src/Grav/Common/Data/Data.php b/system/src/Grav/Common/Data/Data.php index 67fb0a831..4de437dcb 100644 --- a/system/src/Grav/Common/Data/Data.php +++ b/system/src/Grav/Common/Data/Data.php @@ -264,7 +264,7 @@ class Data implements DataInterface, ArrayAccess, \Countable, JsonSerializable, */ public function blueprints() { - if (!$this->blueprints) { + if (null === $this->blueprints) { $this->blueprints = new Blueprint(); } elseif (is_callable($this->blueprints)) { // Lazy load blueprints. diff --git a/system/src/Grav/Common/Data/Validation.php b/system/src/Grav/Common/Data/Validation.php index 7ee60e415..c5b21ffac 100644 --- a/system/src/Grav/Common/Data/Validation.php +++ b/system/src/Grav/Common/Data/Validation.php @@ -608,7 +608,7 @@ class Validation */ public static function typeColor($value, array $params, array $field) { - return preg_match('/^\#[0-9a-fA-F]{3}[0-9a-fA-F]{3}?$/u', $value); + return (bool)preg_match('/^\#[0-9a-fA-F]{3}[0-9a-fA-F]{3}?$/u', $value); } /** @@ -1189,7 +1189,7 @@ class Validation */ public static function filterItem_List($value, $params) { - return array_values(array_filter($value, function ($v) { + return array_values(array_filter($value, static function ($v) { return !empty($v); })); } diff --git a/system/src/Grav/Common/Debugger.php b/system/src/Grav/Common/Debugger.php index 6a1e256b9..b8143f68b 100644 --- a/system/src/Grav/Common/Debugger.php +++ b/system/src/Grav/Common/Debugger.php @@ -332,7 +332,7 @@ class Debugger return new Response(404, $headers, json_encode($response)); } - $data = is_array($data) ? array_map(function ($item) { + $data = is_array($data) ? array_map(static function ($item) { return $item->toArray(); }, $data) : $data->toArray(); diff --git a/system/src/Grav/Common/Filesystem/Folder.php b/system/src/Grav/Common/Filesystem/Folder.php index ec3ac5801..ecbc6ceac 100644 --- a/system/src/Grav/Common/Filesystem/Folder.php +++ b/system/src/Grav/Common/Filesystem/Folder.php @@ -197,7 +197,7 @@ abstract class Folder * Shift first directory out of the path. * * @param string $path - * @return string + * @return string|null */ public static function shift(&$path) { @@ -417,7 +417,8 @@ abstract class Folder if (!$success) { $error = error_get_last(); - throw new RuntimeException($error['message']); + + throw new RuntimeException($error['message'] ?? 'Unknown error'); } // Make sure that the change will be detected when caching. diff --git a/system/src/Grav/Common/Filesystem/ZipArchiver.php b/system/src/Grav/Common/Filesystem/ZipArchiver.php index 450a58126..6e53e70a3 100644 --- a/system/src/Grav/Common/Filesystem/ZipArchiver.php +++ b/system/src/Grav/Common/Filesystem/ZipArchiver.php @@ -57,7 +57,9 @@ class ZipArchiver extends Archiver throw new InvalidArgumentException('ZipArchiver: Zip PHP module not installed...'); } - if (!file_exists($source)) { + // Get real path for our folder + $rootPath = realpath($source); + if (!$rootPath) { throw new InvalidArgumentException('ZipArchiver: ' . $source . ' cannot be found...'); } @@ -66,9 +68,6 @@ class ZipArchiver extends Archiver throw new InvalidArgumentException('ZipArchiver:' . $this->archive_file . ' cannot be created...'); } - // Get real path for our folder - $rootPath = realpath($source); - $files = $this->getArchiveFiles($rootPath); $status && $status([ diff --git a/system/src/Grav/Common/Flex/FlexObject.php b/system/src/Grav/Common/Flex/FlexObject.php index 66e5412aa..b64aea1df 100644 --- a/system/src/Grav/Common/Flex/FlexObject.php +++ b/system/src/Grav/Common/Flex/FlexObject.php @@ -43,7 +43,7 @@ abstract class FlexObject extends \Grav\Framework\Flex\FlexObject implements Med // Handle media fields. $settings = $this->getFieldSettings($name); - if ($settings['media_field'] ?? false === true) { + if (($settings['media_field'] ?? false) === true) { return $this->parseFileProperty($value, $settings); } diff --git a/system/src/Grav/Common/Flex/Types/Pages/PageCollection.php b/system/src/Grav/Common/Flex/Types/Pages/PageCollection.php index 08f192fe7..7503653b8 100644 --- a/system/src/Grav/Common/Flex/Types/Pages/PageCollection.php +++ b/system/src/Grav/Common/Flex/Types/Pages/PageCollection.php @@ -19,7 +19,6 @@ use Grav\Common\Page\Header; use Grav\Common\Page\Interfaces\PageCollectionInterface; use Grav\Common\Page\Interfaces\PageInterface; use Grav\Common\Utils; -use Grav\Framework\Flex\Interfaces\FlexObjectInterface; use Grav\Framework\Flex\Pages\FlexPageCollection; use Collator; use InvalidArgumentException; @@ -159,7 +158,7 @@ class PageCollection extends FlexPageCollection implements PageCollectionInterfa */ public function addPage(PageInterface $page) { - if (!$page instanceof FlexObjectInterface) { + if (!$page instanceof PageObject) { throw new InvalidArgumentException('$page is not a flex page.'); } @@ -400,8 +399,8 @@ class PageCollection extends FlexPageCollection implements PageCollectionInterfa $i = count($manual); $new_list = []; foreach ($list as $key => $dummy) { - $child = $this[$key]; - $order = array_search($child->slug, $manual, true); + $child = $this[$key] ?? null; + $order = $child ? array_search($child->slug, $manual, true) : false; if ($order === false) { $order = $i++; } diff --git a/system/src/Grav/Common/Flex/Types/Pages/PageIndex.php b/system/src/Grav/Common/Flex/Types/Pages/PageIndex.php index dd06f5868..f02a64866 100644 --- a/system/src/Grav/Common/Flex/Types/Pages/PageIndex.php +++ b/system/src/Grav/Common/Flex/Types/Pages/PageIndex.php @@ -109,6 +109,10 @@ class PageIndex extends FlexPageIndex implements PageCollectionInterface } $element = parent::get($key); + if (null === $element) { + return null; + } + if (isset($params)) { $element = $element->getTranslation(ltrim($params, '.')); } @@ -331,7 +335,10 @@ class PageIndex extends FlexPageIndex implements PageCollectionInterface */ protected function filterByParent(array $filters) { - return parent::filterBy($filters); + /** @var static $index */ + $index = parent::filterBy($filters); + + return $index; } /** @@ -673,12 +680,13 @@ class PageIndex extends FlexPageIndex implements PageCollectionInterface $child_count = $tmp->count(); $count = $filters ? $tmp->filterBy($filters, true)->count() : null; $route = $child->getRoute(); + $route = $route ? ($route->toString(false) ?: '/') : ''; $payload = [ 'item-key' => htmlspecialchars(basename($child->rawRoute() ?? $child->getKey())), 'icon' => $icon, 'title' => htmlspecialchars($child->menu()), 'route' => [ - 'display' => htmlspecialchars(($route ? ($route->toString(false) ?: '/') : null) ?? ''), + 'display' => htmlspecialchars($route) ?: null, 'raw' => htmlspecialchars($child->rawRoute()), ], 'modified' => $this->jsDate($child->modified()), @@ -834,12 +842,11 @@ class PageIndex extends FlexPageIndex implements PageCollectionInterface /** * Remove item from the list. * - * @param PageInterface|string|null $key - * - * @return $this + * @param string $key + * @return PageObject|null * @throws InvalidArgumentException */ - public function remove($key = null) + public function remove($key) { return $this->getCollection()->remove($key); } diff --git a/system/src/Grav/Common/Flex/Types/Pages/PageObject.php b/system/src/Grav/Common/Flex/Types/Pages/PageObject.php index 5ad456b77..4c83f959b 100644 --- a/system/src/Grav/Common/Flex/Types/Pages/PageObject.php +++ b/system/src/Grav/Common/Flex/Types/Pages/PageObject.php @@ -104,12 +104,12 @@ class PageObject extends FlexPageObject */ public function getRoute($query = []): ?Route { - $route = $this->route(); - if (null === $route) { + $path = $this->route(); + if (null === $path) { return null; } - $route = RouteFactory::createFromString($route); + $route = RouteFactory::createFromString($path); if ($lang = $route->getLanguage()) { $grav = Grav::instance(); if (!$grav['config']->get('system.languages.include_default_lang')) { @@ -441,7 +441,8 @@ class PageObject extends FlexPageObject // Add missing siblings into the end of the list, keeping the previous ordering between them. foreach ($siblings as $sibling) { - $basename = preg_replace('|^\d+\.|', '', $sibling->getProperty('folder')); + $folder = (string)$sibling->getProperty('folder'); + $basename = preg_replace('|^\d+\.|', '', $folder); if (!in_array($basename, $ordering, true)) { $ordering[] = $basename; } @@ -451,7 +452,8 @@ class PageObject extends FlexPageObject $ordering = array_flip(array_values($ordering)); $count = count($ordering); foreach ($siblings as $sibling) { - $basename = preg_replace('|^\d+\.|', '', $sibling->getProperty('folder')); + $folder = (string)$sibling->getProperty('folder'); + $basename = preg_replace('|^\d+\.|', '', $folder); $newOrder = $ordering[$basename] ?? null; $newOrder = null !== $newOrder ? $newOrder + 1 : (int)$sibling->order() + $count; $sibling->order($newOrder); diff --git a/system/src/Grav/Common/Flex/Types/Pages/Traits/PageLegacyTrait.php b/system/src/Grav/Common/Flex/Types/Pages/Traits/PageLegacyTrait.php index d8193df7c..589ea881a 100644 --- a/system/src/Grav/Common/Flex/Types/Pages/Traits/PageLegacyTrait.php +++ b/system/src/Grav/Common/Flex/Types/Pages/Traits/PageLegacyTrait.php @@ -103,7 +103,10 @@ trait PageLegacyTrait $parent = $this->parent(); $collection = $parent ? $parent->collection('content', false) : null; if (null !== $path && $collection instanceof PageCollectionInterface) { - return $collection->adjacentSibling($path, $direction); + $child = $collection->adjacentSibling($path, $direction); + if ($child instanceof PageInterface) { + return $child; + } } return false; diff --git a/system/src/Grav/Common/Flex/Types/Users/UserCollection.php b/system/src/Grav/Common/Flex/Types/Users/UserCollection.php index e17525a9c..9b6490a8a 100644 --- a/system/src/Grav/Common/Flex/Types/Users/UserCollection.php +++ b/system/src/Grav/Common/Flex/Types/Users/UserCollection.php @@ -92,7 +92,7 @@ class UserCollection extends FlexCollection implements UserCollectionInterface } else { $user = parent::find($query, $field); } - if ($user) { + if ($user instanceof UserObject) { return $user; } } @@ -123,7 +123,7 @@ class UserCollection extends FlexCollection implements UserCollectionInterface * @param string $key * @return string */ - protected function filterUsername(string $key) + protected function filterUsername(string $key): string { $storage = $this->getFlexDirectory()->getStorage(); if (method_exists($storage, 'normalizeKey')) { diff --git a/system/src/Grav/Common/Flex/Types/Users/UserIndex.php b/system/src/Grav/Common/Flex/Types/Users/UserIndex.php index 4a3f58773..6e0bc65fe 100644 --- a/system/src/Grav/Common/Flex/Types/Users/UserIndex.php +++ b/system/src/Grav/Common/Flex/Types/Users/UserIndex.php @@ -62,7 +62,7 @@ class UserIndex extends FlexIndex implements UserCollectionInterface * @param FlexStorageInterface $storage * @return void */ - public static function updateObjectMeta(array &$meta, array $data, FlexStorageInterface $storage) + public static function updateObjectMeta(array &$meta, array $data, FlexStorageInterface $storage): void { // Username can also be number and stored as such. $key = (string)($data['username'] ?? $meta['key'] ?? $meta['storage_key']); @@ -187,7 +187,7 @@ class UserIndex extends FlexIndex implements UserCollectionInterface * @param array $updated * @param array $removed */ - protected static function onChanges(array $entries, array $added, array $updated, array $removed) + protected static function onChanges(array $entries, array $added, array $updated, array $removed): void { $message = sprintf('Flex: User index updated, %d objects (%d added, %d updated, %d removed).', count($entries), count($added), count($updated), count($removed)); diff --git a/system/src/Grav/Common/Grav.php b/system/src/Grav/Common/Grav.php index ffbb50818..f5919613b 100644 --- a/system/src/Grav/Common/Grav.php +++ b/system/src/Grav/Common/Grav.php @@ -135,7 +135,7 @@ class Grav extends Container * * @return void */ - public static function resetInstance() + public static function resetInstance(): void { if (self::$instance) { // @phpstan-ignore-next-line @@ -242,7 +242,7 @@ class Grav extends Container * * @return void */ - public function process() + public function process(): void { if (isset($this->initialized['process'])) { return; @@ -474,7 +474,7 @@ class Grav extends Container * @param int $code Redirection code (30x) * @return void */ - public function redirectLangSafe($route, $code = null) + public function redirectLangSafe($route, $code = null): void { if (!$this['uri']->isExternal($route)) { $this->redirect($this['pages']->route($route), $code); @@ -489,7 +489,7 @@ class Grav extends Container * @param ResponseInterface|null $response * @return void */ - public function header(ResponseInterface $response = null) + public function header(ResponseInterface $response = null): void { if (null === $response) { /** @var PageInterface $page */ @@ -514,7 +514,7 @@ class Grav extends Container * * @return void */ - public function setLocale() + public function setLocale(): void { // Initialize Locale if set and configured. if ($this['language']->enabled() && $this['config']->get('system.languages.override_locale')) { @@ -575,7 +575,7 @@ class Grav extends Container * * @return void */ - public function shutdown() + public function shutdown(): void { // Prevent user abort allowing onShutdown event to run without interruptions. if (function_exists('ignore_user_abort')) { @@ -694,7 +694,7 @@ class Grav extends Container * * @return void */ - protected function registerServices() + protected function registerServices(): void { foreach (self::$diMap as $serviceKey => $serviceClass) { if (is_int($serviceKey)) { @@ -761,12 +761,10 @@ class Grav extends Container // unsupported media type, try to download it... if ($uri_extension) { $extension = $uri_extension; + } elseif (isset($path_parts['extension'])) { + $extension = $path_parts['extension']; } else { - if (isset($path_parts['extension'])) { - $extension = $path_parts['extension']; - } else { - $extension = null; - } + $extension = null; } if ($extension) { @@ -781,6 +779,6 @@ class Grav extends Container return false; } - return $page; + return $page ?? false; } } diff --git a/system/src/Grav/Common/Helpers/Excerpts.php b/system/src/Grav/Common/Helpers/Excerpts.php index cd285cf87..173850a53 100644 --- a/system/src/Grav/Common/Helpers/Excerpts.php +++ b/system/src/Grav/Common/Helpers/Excerpts.php @@ -33,6 +33,9 @@ class Excerpts public static function processImageHtml($html, PageInterface $page = null) { $excerpt = static::getExcerptFromHtml($html, 'img'); + if (null === $excerpt) { + return ''; + } $original_src = $excerpt['element']['attributes']['src']; $excerpt['element']['attributes']['href'] = $original_src; @@ -61,6 +64,9 @@ class Excerpts public static function processLinkHtml($html, PageInterface $page = null) { $excerpt = static::getExcerptFromHtml($html, 'a'); + if (null === $excerpt) { + return ''; + } $original_href = $excerpt['element']['attributes']['href']; $excerpt = static::processLinkExcerpt($excerpt, $page, 'link'); @@ -89,7 +95,6 @@ class Excerpts $excerpt = null; $inner = []; - /** @var DOMElement $element */ foreach ($elements as $element) { $attributes = []; foreach ($element->attributes as $name => $value) { diff --git a/system/src/Grav/Common/Helpers/LogViewer.php b/system/src/Grav/Common/Helpers/LogViewer.php index a03fde810..187828ae3 100644 --- a/system/src/Grav/Common/Helpers/LogViewer.php +++ b/system/src/Grav/Common/Helpers/LogViewer.php @@ -53,7 +53,6 @@ class LogViewer */ public function tail($filepath, $lines = 1) { - $f = $filepath ? @fopen($filepath, 'rb') : false; if ($f === false) { return false; @@ -62,13 +61,12 @@ class LogViewer $buffer = ($lines < 2 ? 64 : ($lines < 10 ? 512 : 4096)); fseek($f, -1, SEEK_END); - if (fread($f, 1) != "\n") { - $lines -= 1; + if (fread($f, 1) !== "\n") { + --$lines; } // Start reading $output = ''; - $chunk = ''; // While we would like more while (ftell($f) > 0 && $lines >= 0) { // Figure out how far back we should jump @@ -76,7 +74,11 @@ class LogViewer // Do the jump (backwards, relative to where we are) fseek($f, -$seek, SEEK_CUR); // Read a chunk and prepend it to our output - $output = ($chunk = fread($f, $seek)) . $output; + $chunk = fread($f, $seek); + if ($chunk === false) { + throw new \RuntimeException('Cannot read file'); + } + $output = $chunk . $output; // Jump back to where we started reading fseek($f, -mb_strlen($chunk, '8bit'), SEEK_CUR); // Decrease our line counter @@ -123,13 +125,13 @@ class LogViewer */ public function parse($line) { - if (!is_string($line) || strlen($line) === 0) { - return array(); + if (!is_string($line) || $line === '') { + return []; } preg_match($this->pattern, $line, $data); if (!isset($data['date'])) { - return array(); + return []; } preg_match('/(.*)- Trace:(.*)/', $data['message'], $matches); @@ -138,7 +140,7 @@ class LogViewer $data['trace'] = trim($matches[2]); } - return array( + return [ 'date' => DateTime::createFromFormat('Y-m-d H:i:s', $data['date']), 'logger' => $data['logger'], 'level' => $data['level'], @@ -146,7 +148,7 @@ class LogViewer 'trace' => isset($data['trace']) ? $this->parseTrace($data['trace']) : null, 'context' => json_decode($data['context'], true), 'extra' => json_decode($data['extra'], true) - ); + ]; } /** diff --git a/system/src/Grav/Common/Iterator.php b/system/src/Grav/Common/Iterator.php index cc7cf9286..6e80b947e 100644 --- a/system/src/Grav/Common/Iterator.php +++ b/system/src/Grav/Common/Iterator.php @@ -230,9 +230,7 @@ class Iterator implements \ArrayAccess, \Iterator, \Countable, \Serializable public function filter(callable $callback = null) { foreach ($this->items as $key => $value) { - if ((!$callback && !(bool)$value) || - ($callback && !$callback($value, $key)) - ) { + if ((!$callback && !(bool)$value) || ($callback && !$callback($value, $key))) { unset($this->items[$key]); } } diff --git a/system/src/Grav/Common/Language/LanguageCodes.php b/system/src/Grav/Common/Language/LanguageCodes.php index 9282070d6..f0a35322d 100644 --- a/system/src/Grav/Common/Language/LanguageCodes.php +++ b/system/src/Grav/Common/Language/LanguageCodes.php @@ -187,12 +187,7 @@ class LanguageCodes */ public static function getOrientation($code) { - if (isset(static::$codes[$code])) { - if (isset(static::$codes[$code]['orientation'])) { - return static::get($code, 'orientation'); - } - } - return 'ltr'; + return static::$codes[$code]['orientation'] ?? 'ltr'; } /** @@ -226,11 +221,7 @@ class LanguageCodes */ public static function get($code, $type) { - if (isset(static::$codes[$code][$type])) { - return static::$codes[$code][$type]; - } - - return false; + return static::$codes[$code][$type] ?? false; } /** diff --git a/system/src/Grav/Common/Page/Collection.php b/system/src/Grav/Common/Page/Collection.php index c9a3cdbd5..32b917cd2 100644 --- a/system/src/Grav/Common/Page/Collection.php +++ b/system/src/Grav/Common/Page/Collection.php @@ -47,7 +47,7 @@ class Collection extends Iterator implements PageCollectionInterface parent::__construct($items); $this->params = $params; - $this->pages = $pages ? $pages : Grav::instance()->offsetGet('pages'); + $this->pages = $pages ?: Grav::instance()->offsetGet('pages'); } /** diff --git a/system/src/Grav/Common/Page/Page.php b/system/src/Grav/Common/Page/Page.php index a0356134c..2099be212 100644 --- a/system/src/Grav/Common/Page/Page.php +++ b/system/src/Grav/Common/Page/Page.php @@ -2274,11 +2274,11 @@ class Page implements PageInterface { if ($var !== null) { // make sure first level are arrays - array_walk($var, function (&$value) { + array_walk($var, static function (&$value) { $value = (array) $value; }); // make sure all values are strings - array_walk_recursive($var, function (&$value) { + array_walk_recursive($var, static function (&$value) { $value = (string) $value; }); $this->taxonomy = $var; diff --git a/system/src/Grav/Common/Page/Pages.php b/system/src/Grav/Common/Page/Pages.php index c5e08e45a..941c9a7b3 100644 --- a/system/src/Grav/Common/Page/Pages.php +++ b/system/src/Grav/Common/Page/Pages.php @@ -326,7 +326,7 @@ class Pages * * @return void */ - public function reset() + public function reset(): void { $this->initialized = false; @@ -606,7 +606,7 @@ class Pages if (is_array($sort_flags)) { $sort_flags = array_map('constant', $sort_flags); //transform strings to constant value - $sort_flags = array_reduce($sort_flags, function ($a, $b) { + $sort_flags = array_reduce($sort_flags, static function ($a, $b) { return $a | $b; }, 0); //merge constant values using bit or } @@ -715,29 +715,39 @@ class Pages switch ($type) { case 'all': - return $page->children(); + $collection = $page->children(); + break; case 'modules': case 'modular': - return $page->children()->modules(); + $collection = $page->children()->modules(); + break; case 'pages': case 'children': - return $page->children()->pages(); + $collection = $page->children()->pages(); + break; case 'page': case 'self': - return !$page->root() ? (new Collection())->addPage($page) : new Collection(); + $collection = !$page->root() ? (new Collection())->addPage($page) : new Collection(); + break; case 'parent': $parent = $page->parent(); $collection = new Collection(); - return $parent ? $collection->addPage($parent) : $collection; + $collection = $parent ? $collection->addPage($parent) : $collection; + break; case 'siblings': $parent = $page->parent(); - return $parent ? $parent->children()->remove($page->path()) : new Collection(); + $collection = $parent ? $parent->children()->remove($page->path()) : new Collection(); + break; case 'descendants': - return $this->all($page)->remove($page->path())->pages(); + $collection = $this->all($page)->remove($page->path())->pages(); + break; default: // Unknown type; return empty collection. - return new Collection(); + $collection = new Collection(); + break; } + + return $collection; } /** @@ -1813,7 +1823,7 @@ class Pages // Build regular expression for all the allowed page extensions. $page_extensions = $language->getFallbackPageExtensions(); $regex = '/^[^\.]*(' . implode('|', array_map( - function ($str) { + static function ($str) { return preg_quote($str, '/'); }, $page_extensions diff --git a/system/src/Grav/Common/Scheduler/Job.php b/system/src/Grav/Common/Scheduler/Job.php index 94fbaf102..13059a572 100644 --- a/system/src/Grav/Common/Scheduler/Job.php +++ b/system/src/Grav/Common/Scheduler/Job.php @@ -271,7 +271,7 @@ class Job if ($whenOverlapping) { $this->whenOverlapping = $whenOverlapping; } else { - $this->whenOverlapping = function () { + $this->whenOverlapping = static function () { return false; }; } diff --git a/system/src/Grav/Common/Security.php b/system/src/Grav/Common/Security.php index 50d9a5d46..833e64808 100644 --- a/system/src/Grav/Common/Security.php +++ b/system/src/Grav/Common/Security.php @@ -107,7 +107,7 @@ class Security $content = $page->value('content'); $data = ['header' => $header, 'content' => $content]; - $results = Security::detectXssFromArray($data); + $results = static::detectXssFromArray($data); if (!empty($results)) { if ($route) { @@ -199,7 +199,7 @@ class Security $string = urldecode($string); // Convert Hexadecimals - $string = (string)preg_replace_callback('!(&#|\\\)[xX]([0-9a-fA-F]+);?!u', function ($m) { + $string = (string)preg_replace_callback('!(&#|\\\)[xX]([0-9a-fA-F]+);?!u', static function ($m) { return chr(hexdec($m[2])); }, $string); @@ -239,7 +239,7 @@ class Security } } - return false; + return null; } public static function getXssDefaults(): array diff --git a/system/src/Grav/Common/Session.php b/system/src/Grav/Common/Session.php index 2dbc3073a..322162705 100644 --- a/system/src/Grav/Common/Session.php +++ b/system/src/Grav/Common/Session.php @@ -129,12 +129,12 @@ class Session extends \Grav\Framework\Session\Session /** @var Uri $uri */ $uri = $grav['uri']; /** @var Forms|null $form */ - $form = $grav['forms']->getActiveForm(); // @phpstan-ignore-line + $form = $grav['forms']->getActiveForm(); // @phpstan-ignore-line (form plugin) $sessionField = base64_encode($uri->url); /** @var FormFlash|null $flash */ - $flash = $form ? $form->getFlash() : null; // @phpstan-ignore-line + $flash = $form ? $form->getFlash() : null; // @phpstan-ignore-line (form plugin) $object = $flash && method_exists($flash, 'getLegacyFiles') ? [$sessionField => $flash->getLegacyFiles()] : null; } } diff --git a/system/src/Grav/Common/Taxonomy.php b/system/src/Grav/Common/Taxonomy.php index de3c4526c..0d0a450b0 100644 --- a/system/src/Grav/Common/Taxonomy.php +++ b/system/src/Grav/Common/Taxonomy.php @@ -105,7 +105,7 @@ class Taxonomy } } elseif (is_string($value)) { if (!empty($key)) { - $taxonomy = $taxonomy . $key; + $taxonomy .= $key; } $this->taxonomy_map[$taxonomy][(string) $value][$page->path()] = ['slug' => $page->slug()]; } diff --git a/system/src/Grav/Common/Utils.php b/system/src/Grav/Common/Utils.php index 34b6e0f13..f843a0c66 100644 --- a/system/src/Grav/Common/Utils.php +++ b/system/src/Grav/Common/Utils.php @@ -166,9 +166,9 @@ abstract class Utils if ($locator->isStream($path)) { $path = $locator->findResource($path, true); - } elseif (!Utils::startsWith($path, GRAV_ROOT)) { + } elseif (!static::startsWith($path, GRAV_ROOT)) { $base_url = Grav::instance()['base_url']; - $path = GRAV_ROOT . '/' . ltrim(Utils::replaceFirstOccurrence($base_url, '', $path), '/'); + $path = GRAV_ROOT . '/' . ltrim(static::replaceFirstOccurrence($base_url, '', $path), '/'); } return $path; @@ -767,13 +767,13 @@ abstract class Utils if (is_string($http_accept)) { $negotiator = new Negotiator(); - $supported_types = Utils::getSupportPageTypes(['html', 'json']); - $priorities = Utils::getMimeTypes($supported_types); + $supported_types = static::getSupportPageTypes(['html', 'json']); + $priorities = static::getMimeTypes($supported_types); $media_type = $negotiator->getBest($http_accept, $priorities); $mimetype = $media_type instanceof Accept ? $media_type->getValue() : ''; - return Utils::getExtensionByMime($mimetype); + return static::getExtensionByMime($mimetype); } return 'html'; @@ -808,13 +808,7 @@ abstract class Utils $media_types = Grav::instance()['config']->get('media.types'); - if (isset($media_types[$extension])) { - if (isset($media_types[$extension]['mime'])) { - return $media_types[$extension]['mime']; - } - } - - return $default; + return $media_types[$extension]['mime'] ?? $default; } /** @@ -1756,7 +1750,7 @@ abstract class Utils { $enc_url = preg_replace_callback( '%[^:/@?&=#]+%usD', - function ($matches) { + static function ($matches) { return urlencode($matches[0]); }, $url