From 17548131d361e57bb8904dc561c674991cc30e8e Mon Sep 17 00:00:00 2001 From: Andy Miller Date: Mon, 9 Dec 2024 17:23:56 -0700 Subject: [PATCH] rector fixes for PHP 8.2+ Signed-off-by: Andy Miller --- .../Doctrine/Common/Cache/FilesystemCache.php | 2 +- system/src/Grav/Common/Assets.php | 33 +- system/src/Grav/Common/Assets/BaseAsset.php | 2 +- system/src/Grav/Common/Assets/BlockAssets.php | 6 +- system/src/Grav/Common/Assets/Pipeline.php | 2 +- .../Common/Assets/Traits/AssetUtilsTrait.php | 16 +- .../Assets/Traits/LegacyAssetsTrait.php | 4 +- .../Assets/Traits/TestingAssetsTrait.php | 2 +- system/src/Grav/Common/Backup/Backups.php | 8 +- system/src/Grav/Common/Browser.php | 2 +- system/src/Grav/Common/Cache.php | 6 +- .../src/Grav/Common/Config/CompiledBase.php | 6 +- system/src/Grav/Common/Config/Config.php | 2 +- .../Grav/Common/Config/ConfigFileFinder.php | 8 +- system/src/Grav/Common/Config/Setup.php | 2 +- system/src/Grav/Common/Data/Blueprint.php | 7 +- .../src/Grav/Common/Data/BlueprintSchema.php | 2 +- system/src/Grav/Common/Data/Blueprints.php | 5 +- system/src/Grav/Common/Data/Data.php | 4 +- system/src/Grav/Common/Data/DataInterface.php | 2 +- system/src/Grav/Common/Data/Validation.php | 245 ++++++--------- .../Grav/Common/Data/ValidationException.php | 4 +- system/src/Grav/Common/Debugger.php | 35 +-- .../Grav/Common/Errors/SimplePageHandler.php | 6 +- system/src/Grav/Common/File/CompiledFile.php | 11 +- system/src/Grav/Common/Filesystem/Folder.php | 22 +- .../Grav/Common/Filesystem/ZipArchiver.php | 2 +- .../Flex/Traits/FlexCollectionTrait.php | 2 +- .../Common/Flex/Traits/FlexObjectTrait.php | 2 +- .../Flex/Types/Pages/PageCollection.php | 14 +- .../Common/Flex/Types/Pages/PageIndex.php | 23 +- .../Common/Flex/Types/Pages/PageObject.php | 8 +- .../Flex/Types/Pages/Storage/PageStorage.php | 6 +- .../Types/Pages/Traits/PageTranslateTrait.php | 4 +- .../Flex/Types/UserGroups/UserGroupObject.php | 6 +- .../Users/Traits/UserObjectLegacyTrait.php | 10 +- .../Common/Flex/Types/Users/UserIndex.php | 2 +- .../Common/Flex/Types/Users/UserObject.php | 10 +- system/src/Grav/Common/GPM/Common/Package.php | 7 +- system/src/Grav/Common/GPM/GPM.php | 33 +- system/src/Grav/Common/GPM/Installer.php | 2 +- system/src/Grav/Common/GPM/Local/Package.php | 2 +- .../GPM/Remote/AbstractPackageCollection.php | 4 +- .../src/Grav/Common/GPM/Remote/GravCore.php | 2 +- system/src/Grav/Common/Getters.php | 5 +- system/src/Grav/Common/Grav.php | 80 ++--- system/src/Grav/Common/HTTP/Client.php | 18 +- system/src/Grav/Common/HTTP/Response.php | 2 +- system/src/Grav/Common/Helpers/Truncator.php | 8 +- system/src/Grav/Common/Inflector.php | 42 ++- system/src/Grav/Common/Iterator.php | 9 +- system/src/Grav/Common/Language/Language.php | 8 +- system/src/Grav/Common/Markdown/Parsedown.php | 2 +- .../Grav/Common/Markdown/ParsedownExtra.php | 2 +- .../Common/Markdown/ParsedownGravTrait.php | 12 +- .../Media/Interfaces/MediaObjectInterface.php | 5 +- .../Common/Media/Traits/ImageMediaTrait.php | 2 +- .../Common/Media/Traits/MediaFileTrait.php | 2 +- .../Common/Media/Traits/MediaObjectTrait.php | 6 +- .../Grav/Common/Media/Traits/MediaTrait.php | 6 +- .../Common/Media/Traits/MediaUploadTrait.php | 10 +- .../Media/Traits/ThumbnailMediaTrait.php | 2 +- system/src/Grav/Common/Page/Collection.php | 6 +- .../Page/Interfaces/PageLegacyInterface.php | 6 +- .../Grav/Common/Page/Markdown/Excerpts.php | 18 +- system/src/Grav/Common/Page/Media.php | 4 +- .../src/Grav/Common/Page/Medium/ImageFile.php | 6 +- .../Grav/Common/Page/Medium/ImageMedium.php | 4 +- system/src/Grav/Common/Page/Medium/Link.php | 5 +- system/src/Grav/Common/Page/Medium/Medium.php | 2 +- .../Grav/Common/Page/Medium/MediumFactory.php | 29 +- system/src/Grav/Common/Page/Page.php | 48 +-- system/src/Grav/Common/Page/Pages.php | 74 ++--- .../Grav/Common/Page/Traits/PageFormTrait.php | 2 +- system/src/Grav/Common/Page/Types.php | 2 +- system/src/Grav/Common/Plugin.php | 19 +- system/src/Grav/Common/Plugins.php | 4 +- .../Common/Processors/InitializeProcessor.php | 6 +- .../Grav/Common/Processors/TasksProcessor.php | 2 +- system/src/Grav/Common/Scheduler/Cron.php | 17 +- system/src/Grav/Common/Scheduler/Job.php | 14 +- .../src/Grav/Common/Scheduler/Scheduler.php | 20 +- system/src/Grav/Common/Security.php | 14 +- .../Common/Service/AssetsServiceProvider.php | 4 +- .../Common/Service/ConfigServiceProvider.php | 16 +- .../Service/FilesystemServiceProvider.php | 4 +- .../Service/InflectorServiceProvider.php | 4 +- .../Common/Service/PagesServiceProvider.php | 4 +- .../Common/Service/RequestServiceProvider.php | 8 +- .../Service/SchedulerServiceProvider.php | 4 +- .../Common/Service/SessionServiceProvider.php | 4 +- system/src/Grav/Common/Session.php | 18 +- system/src/Grav/Common/Themes.php | 4 +- .../Twig/Extension/FilesystemExtension.php | 92 +++--- .../Common/Twig/Extension/GravExtension.php | 287 ++++++++---------- .../Twig/TokenParser/TwigTokenParserCache.php | 2 +- .../TokenParser/TwigTokenParserMarkdown.php | 2 +- .../TokenParser/TwigTokenParserScript.php | 2 +- .../Twig/TokenParser/TwigTokenParserStyle.php | 2 +- .../TokenParser/TwigTokenParserSwitch.php | 4 +- .../TokenParser/TwigTokenParserTryCatch.php | 4 +- system/src/Grav/Common/Twig/Twig.php | 10 +- system/src/Grav/Common/Uri.php | 50 ++- system/src/Grav/Common/User/DataUser/User.php | 12 +- .../Common/User/DataUser/UserCollection.php | 8 +- .../Common/User/Interfaces/UserInterface.php | 10 +- .../src/Grav/Common/User/Traits/UserTrait.php | 4 +- system/src/Grav/Common/User/User.php | 12 +- system/src/Grav/Common/Utils.php | 61 ++-- .../Grav/Console/Application/Application.php | 2 +- .../CommandLoader/PluginCommandLoader.php | 2 +- .../src/Grav/Console/Cli/InstallCommand.php | 8 +- .../Cli/PageSystemValidatorCommand.php | 2 +- .../src/Grav/Console/Cli/SchedulerCommand.php | 2 +- .../src/Grav/Console/Cli/SecurityCommand.php | 6 +- system/src/Grav/Console/ConsoleTrait.php | 2 +- system/src/Grav/Console/Gpm/IndexCommand.php | 12 +- system/src/Grav/Console/Gpm/InfoCommand.php | 6 +- .../src/Grav/Console/Gpm/InstallCommand.php | 14 +- .../Grav/Console/Gpm/SelfupgradeCommand.php | 10 +- .../src/Grav/Console/Gpm/VersionCommand.php | 2 +- system/src/Grav/Console/GpmCommand.php | 2 +- system/src/Grav/Framework/Acl/Access.php | 7 +- system/src/Grav/Framework/Acl/Permissions.php | 3 +- .../Framework/Cache/Adapter/ChainCache.php | 2 +- .../Framework/Cache/Adapter/FileCache.php | 4 +- .../Grav/Framework/Cache/CacheInterface.php | 9 +- .../src/Grav/Framework/Cache/CacheTrait.php | 16 +- .../Collection/AbstractFileCollection.php | 9 +- .../Collection/AbstractIndexCollection.php | 32 +- .../Collection/AbstractLazyCollection.php | 2 +- .../Framework/ContentBlock/ContentBlock.php | 4 +- .../Grav/Framework/ContentBlock/HtmlBlock.php | 8 +- .../Traits/ControllerResponseTrait.php | 14 +- .../src/Grav/Framework/File/AbstractFile.php | 4 +- .../File/Formatter/AbstractFormatter.php | 6 +- .../Framework/File/Formatter/CsvFormatter.php | 6 +- .../Framework/File/Formatter/IniFormatter.php | 2 +- .../File/Formatter/SerializeFormatter.php | 3 +- .../Interfaces/FileFormatterInterface.php | 2 +- .../File/Interfaces/FileInterface.php | 2 +- .../Grav/Framework/Filesystem/Filesystem.php | 6 +- system/src/Grav/Framework/Flex/Flex.php | 4 +- .../Grav/Framework/Flex/FlexCollection.php | 19 +- .../src/Grav/Framework/Flex/FlexDirectory.php | 30 +- .../Grav/Framework/Flex/FlexDirectoryForm.php | 9 +- system/src/Grav/Framework/Flex/FlexForm.php | 9 +- .../src/Grav/Framework/Flex/FlexFormFlash.php | 2 +- .../Grav/Framework/Flex/FlexIdentifier.php | 6 +- system/src/Grav/Framework/Flex/FlexIndex.php | 21 +- system/src/Grav/Framework/Flex/FlexObject.php | 42 +-- .../Interfaces/FlexDirectoryInterface.php | 3 +- .../Flex/Interfaces/FlexObjectInterface.php | 2 +- .../Framework/Flex/Pages/FlexPageObject.php | 15 +- .../Flex/Pages/Traits/PageAuthorsTrait.php | 2 +- .../Flex/Pages/Traits/PageContentTrait.php | 50 ++- .../Flex/Pages/Traits/PageLegacyTrait.php | 58 ++-- .../Flex/Pages/Traits/PageRoutableTrait.php | 8 +- .../Flex/Pages/Traits/PageTranslateTrait.php | 6 +- .../Storage/AbstractFilesystemStorage.php | 19 +- .../Framework/Flex/Storage/FileStorage.php | 2 +- .../Framework/Flex/Storage/FolderStorage.php | 8 +- .../Framework/Flex/Storage/SimpleStorage.php | 4 +- .../Flex/Traits/FlexAuthorizeTrait.php | 2 +- .../Framework/Flex/Traits/FlexMediaTrait.php | 2 +- .../Flex/Traits/FlexRelatedDirectoryTrait.php | 4 +- system/src/Grav/Framework/Form/FormFlash.php | 10 +- .../src/Grav/Framework/Form/FormFlashFile.php | 8 +- .../Grav/Framework/Form/Traits/FormTrait.php | 8 +- .../Media/Interfaces/MediaObjectInterface.php | 2 +- .../Grav/Framework/Media/MediaIdentifier.php | 2 +- .../src/Grav/Framework/Media/MediaObject.php | 15 +- .../Framework/Media/UploadedMediaObject.php | 23 +- .../Object/Access/ArrayAccessTrait.php | 8 +- .../Object/Access/NestedArrayAccessTrait.php | 8 +- .../Access/NestedPropertyCollectionTrait.php | 4 +- .../Object/Access/NestedPropertyTrait.php | 4 +- .../Object/Access/OverloadedPropertyTrait.php | 8 +- .../Object/Base/ObjectCollectionTrait.php | 14 +- .../Framework/Object/Base/ObjectTrait.php | 8 +- .../Collection/ObjectExpressionVisitor.php | 95 ++---- .../Object/Identifiers/Identifier.php | 9 +- .../NestedObjectCollectionInterface.php | 4 +- .../Interfaces/NestedObjectInterface.php | 4 +- .../Interfaces/ObjectCollectionInterface.php | 4 +- .../Object/Interfaces/ObjectInterface.php | 4 +- .../src/Grav/Framework/Object/ObjectIndex.php | 2 +- .../Object/Property/ArrayPropertyTrait.php | 8 +- .../Object/Property/LazyPropertyTrait.php | 8 +- .../Object/Property/MixedPropertyTrait.php | 4 +- .../Object/Property/ObjectPropertyTrait.php | 13 +- .../Pagination/AbstractPagination.php | 4 +- .../src/Grav/Framework/Psr7/AbstractUri.php | 6 +- system/src/Grav/Framework/Psr7/Response.php | 4 +- .../src/Grav/Framework/Psr7/ServerRequest.php | 17 +- .../Framework/Relationships/Relationships.php | 20 +- .../Traits/RelationshipTrait.php | 2 +- .../Exception/InvalidArgumentException.php | 7 +- .../Exception/RequestException.php | 7 +- .../RequestHandler/Middlewares/Exceptions.php | 2 +- .../Middlewares/MultipartRequestSupport.php | 4 +- system/src/Grav/Framework/Route/Route.php | 17 +- .../src/Grav/Framework/Route/RouteFactory.php | 10 +- system/src/Grav/Framework/Session/Session.php | 13 +- .../Framework/Session/SessionInterface.php | 3 +- system/src/Grav/Framework/Uri/UriFactory.php | 14 +- .../src/Grav/Framework/Uri/UriPartsFilter.php | 12 +- system/src/Grav/Installer/VersionUpdate.php | 5 +- system/src/Grav/Installer/VersionUpdater.php | 15 +- system/src/Grav/Installer/Versions.php | 13 +- system/src/Grav/Installer/YamlUpdater.php | 13 +- 211 files changed, 1096 insertions(+), 1645 deletions(-) diff --git a/system/src/Doctrine/Common/Cache/FilesystemCache.php b/system/src/Doctrine/Common/Cache/FilesystemCache.php index 5c6845fb0..e8c4c83a4 100644 --- a/system/src/Doctrine/Common/Cache/FilesystemCache.php +++ b/system/src/Doctrine/Common/Cache/FilesystemCache.php @@ -19,7 +19,7 @@ class FilesystemCache extends CacheProvider */ public function __construct($directory, $extension = self::EXTENSION, $umask = 0002) { - user_error(__CLASS__ . ' is deprecated since Grav 1.8, use Symfony cache instead', E_USER_DEPRECATED); + user_error(self::class . ' is deprecated since Grav 1.8, use Symfony cache instead', E_USER_DEPRECATED); $this->pool = new FilesystemAdapter('', 0, $directory); } diff --git a/system/src/Grav/Common/Assets.php b/system/src/Grav/Common/Assets.php index f62f45b56..f8279c0de 100644 --- a/system/src/Grav/Common/Assets.php +++ b/system/src/Grav/Common/Assets.php @@ -194,12 +194,12 @@ class Assets extends PropertyObject } $params = array_merge([$location], $params); - call_user_func_array([$this, 'add'], $params); + call_user_func_array($this->add(...), $params); } } elseif (isset($this->collections[$asset])) { array_shift($args); $args = array_merge([$this->collections[$asset]], $args); - call_user_func_array([$this, 'add'], $args); + call_user_func_array($this->add(...), $args); } else { // Get extension $path = parse_url($asset, PHP_URL_PATH); @@ -209,11 +209,11 @@ class Assets extends PropertyObject if ($extension !== '') { $extension = strtolower($extension); if ($extension === 'css') { - call_user_func_array([$this, 'addCss'], $args); + call_user_func_array($this->addCss(...), $args); } elseif ($extension === 'js') { - call_user_func_array([$this, 'addJs'], $args); + call_user_func_array($this->addJs(...), $args); } elseif ($extension === 'mjs') { - call_user_func_array([$this, 'addJsModule'], $args); + call_user_func_array($this->addJsModule(...), $args); } } } @@ -261,7 +261,7 @@ class Assets extends PropertyObject $default = 'before'; } - $options['position'] = $options['position'] ?? $default; + $options['position'] ??= $default; } unset($options['pipeline']); @@ -432,9 +432,7 @@ class Assets extends PropertyObject */ protected function sortAssets($assets) { - uasort($assets, static function ($a, $b) { - return $b['priority'] <=> $a['priority'] ?: $a['order'] <=> $b['order']; - }); + uasort($assets, static fn($a, $b) => $b['priority'] <=> $a['priority'] ?: $a['order'] <=> $b['order']); return $assets; } @@ -577,18 +575,11 @@ class Assets extends PropertyObject */ protected function getBaseType($type) { - switch ($type) { - case $this::JS_TYPE: - case $this::INLINE_JS_TYPE: - $base_type = $this::JS; - break; - case $this::JS_MODULE_TYPE: - case $this::INLINE_JS_MODULE_TYPE: - $base_type = $this::JS_MODULE; - break; - default: - $base_type = $this::CSS; - } + $base_type = match ($type) { + $this::JS_TYPE, $this::INLINE_JS_TYPE => $this::JS, + $this::JS_MODULE_TYPE, $this::INLINE_JS_MODULE_TYPE => $this::JS_MODULE, + default => $this::CSS, + }; return $base_type; } diff --git a/system/src/Grav/Common/Assets/BaseAsset.php b/system/src/Grav/Common/Assets/BaseAsset.php index 0659ff85c..92d5cb82a 100644 --- a/system/src/Grav/Common/Assets/BaseAsset.php +++ b/system/src/Grav/Common/Assets/BaseAsset.php @@ -114,7 +114,7 @@ abstract class BaseAsset extends PropertyObject // Do some special stuff for CSS/JS (not inline) if (!Utils::startsWith($this->getType(), 'inline')) { - $this->base_url = rtrim($uri->rootUrl($config->get('system.absolute_urls')), '/') . '/'; + $this->base_url = rtrim((string) $uri->rootUrl($config->get('system.absolute_urls')), '/') . '/'; $this->remote = static::isRemoteLink($asset); // Move this to render? diff --git a/system/src/Grav/Common/Assets/BlockAssets.php b/system/src/Grav/Common/Assets/BlockAssets.php index 7c33f7d05..a24b8c56e 100644 --- a/system/src/Grav/Common/Assets/BlockAssets.php +++ b/system/src/Grav/Common/Assets/BlockAssets.php @@ -192,15 +192,15 @@ class BlockAssets { $grav = Grav::instance(); - $base = rtrim($grav['base_url'], '/') ?: '/'; + $base = rtrim((string) $grav['base_url'], '/') ?: '/'; - if (strpos($url, $base) === 0) { + if (str_starts_with($url, $base)) { if ($pipeline) { // Remove file timestamp if CSS pipeline has been enabled. $url = preg_replace('|[?#].*|', '', $url); } - return substr($url, strlen($base) - 1); + return substr((string) $url, strlen($base) - 1); } return $url; } diff --git a/system/src/Grav/Common/Assets/Pipeline.php b/system/src/Grav/Common/Assets/Pipeline.php index 3fd542e3e..f48e9f1c4 100644 --- a/system/src/Grav/Common/Assets/Pipeline.php +++ b/system/src/Grav/Common/Assets/Pipeline.php @@ -283,7 +283,7 @@ class Pipeline extends PropertyObject } else { return str_replace($matches[2], $new_url, $matches[0]); } - }, $file); + }, (string) $file); return $file; } diff --git a/system/src/Grav/Common/Assets/Traits/AssetUtilsTrait.php b/system/src/Grav/Common/Assets/Traits/AssetUtilsTrait.php index 874633f84..cc7afc671 100644 --- a/system/src/Grav/Common/Assets/Traits/AssetUtilsTrait.php +++ b/system/src/Grav/Common/Assets/Traits/AssetUtilsTrait.php @@ -55,7 +55,7 @@ trait AssetUtilsTrait return false; } - return (0 === strpos($link, 'http://') || 0 === strpos($link, 'https://') || 0 === strpos($link, '//')); + return (str_starts_with($link, 'http://') || str_starts_with($link, 'https://') || str_starts_with($link, '//')); } /** @@ -76,18 +76,18 @@ trait AssetUtilsTrait if (static::isRemoteLink($link)) { $local = false; - if (0 === strpos($link, '//')) { + if (str_starts_with((string) $link, '//')) { $link = 'http:' . $link; } - $relative_dir = dirname($relative_path); + $relative_dir = dirname((string) $relative_path); } else { // Fix to remove relative dir if grav is in one if (($this->base_url !== '/') && Utils::startsWith($relative_path, $this->base_url)) { $base_url = '#' . preg_quote($this->base_url, '#') . '#'; - $relative_path = ltrim(preg_replace($base_url, '/', $link, 1), '/'); + $relative_path = ltrim(preg_replace($base_url, '/', (string) $link, 1), '/'); } - $relative_dir = dirname($relative_path); + $relative_dir = dirname((string) $relative_path); $link = GRAV_ROOT . '/' . $relative_path; } @@ -101,7 +101,7 @@ trait AssetUtilsTrait // Double check last character being if ($type === self::JS_ASSET || $type === self::JS_MODULE_ASSET) { - $file = rtrim($file, ' ;') . ';'; + $file = rtrim((string) $file, ' ;') . ';'; } // If this is CSS + the file is local + rewrite enabled @@ -113,7 +113,7 @@ trait AssetUtilsTrait $file = $this->jsRewrite($file, $relative_dir, $local); } - $file = rtrim($file) . PHP_EOL; + $file = rtrim((string) $file) . PHP_EOL; $buffer .= $file; } @@ -191,7 +191,7 @@ trait AssetUtilsTrait { $querystring = ''; - $asset = $asset ?? $this->asset; + $asset ??= $this->asset; $attributes = $this->attributes; if (!empty($this->query)) { diff --git a/system/src/Grav/Common/Assets/Traits/LegacyAssetsTrait.php b/system/src/Grav/Common/Assets/Traits/LegacyAssetsTrait.php index 08a59e2b8..d8ae7454f 100644 --- a/system/src/Grav/Common/Assets/Traits/LegacyAssetsTrait.php +++ b/system/src/Grav/Common/Assets/Traits/LegacyAssetsTrait.php @@ -113,7 +113,7 @@ trait LegacyAssetsTrait */ public function addAsyncJs($asset, $priority = 10, $pipeline = true, $group = 'head') { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use dynamic method with [\'loading\' => \'async\']', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use dynamic method with [\'loading\' => \'async\']', E_USER_DEPRECATED); return $this->addJs($asset, $priority, $pipeline, 'async', $group); } @@ -130,7 +130,7 @@ trait LegacyAssetsTrait */ public function addDeferJs($asset, $priority = 10, $pipeline = true, $group = 'head') { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use dynamic method with [\'loading\' => \'defer\']', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use dynamic method with [\'loading\' => \'defer\']', E_USER_DEPRECATED); return $this->addJs($asset, $priority, $pipeline, 'defer', $group); } diff --git a/system/src/Grav/Common/Assets/Traits/TestingAssetsTrait.php b/system/src/Grav/Common/Assets/Traits/TestingAssetsTrait.php index c2648686f..b69e7acb2 100644 --- a/system/src/Grav/Common/Assets/Traits/TestingAssetsTrait.php +++ b/system/src/Grav/Common/Assets/Traits/TestingAssetsTrait.php @@ -338,7 +338,7 @@ trait TestingAssetsTrait $directory, FilesystemIterator::SKIP_DOTS )), $pattern); - $offset = strlen($ltrim); + $offset = strlen((string) $ltrim); $files = []; foreach ($iterator as $file) { diff --git a/system/src/Grav/Common/Backup/Backups.php b/system/src/Grav/Common/Backup/Backups.php index d9a1531a6..be1329db4 100644 --- a/system/src/Grav/Common/Backup/Backups.php +++ b/system/src/Grav/Common/Backup/Backups.php @@ -54,7 +54,7 @@ class Backups /** @var EventDispatcher $dispatcher */ $dispatcher = $grav['events']; - $dispatcher->addListener('onSchedulerInitialized', [$this, 'onSchedulerInitialized']); + $dispatcher->addListener('onSchedulerInitialized', $this->onSchedulerInitialized(...)); $grav->fireEvent('onBackupsInitialized', new Event(['backups' => $this])); } @@ -106,7 +106,7 @@ class Backups { $param_sep = Grav::instance()['config']->get('system.param_sep', ':'); $download = urlencode(base64_encode(Utils::basename($backup))); - $url = rtrim(Grav::instance()['uri']->rootUrl(true), '/') . '/' . trim( + $url = rtrim((string) Grav::instance()['uri']->rootUrl(true), '/') . '/' . trim( $base_url, '/' ) . '/task' . $param_sep . 'backup/download' . $param_sep . $download . '/admin-nonce' . $param_sep . Utils::getNonce('admin-form'); @@ -158,7 +158,7 @@ class Backups static::$backups = []; $grav = Grav::instance(); - $backups_itr = new GlobIterator(static::$backup_dir . '/*.zip', FilesystemIterator::KEY_AS_FILENAME); + $backups_itr = new GlobIterator(static::$backup_dir . '/*.zip', FilesystemIterator::KEY_AS_FILENAME | \FilesystemIterator::SKIP_DOTS); $inflector = $grav['inflector']; $long_date_format = DATE_RFC2822; @@ -210,7 +210,7 @@ class Backups $name = $grav['inflector']->underscorize($backup->name); $date = date(static::BACKUP_DATE_FORMAT, time()); - $filename = trim($name, '_') . '--' . $date . '.zip'; + $filename = trim((string) $name, '_') . '--' . $date . '.zip'; $destination = static::$backup_dir . DS . $filename; $max_execution_time = ini_set('max_execution_time', '600'); $backup_root = $backup->root; diff --git a/system/src/Grav/Common/Browser.php b/system/src/Grav/Common/Browser.php index 6a92eeea2..24517b75e 100644 --- a/system/src/Grav/Common/Browser.php +++ b/system/src/Grav/Common/Browser.php @@ -27,7 +27,7 @@ class Browser { try { $this->useragent = parse_user_agent(); - } catch (InvalidArgumentException $e) { + } catch (InvalidArgumentException) { $this->useragent = parse_user_agent("Mozilla/5.0 (compatible; Unknown;)"); } } diff --git a/system/src/Grav/Common/Cache.php b/system/src/Grav/Common/Cache.php index 4d70089ca..7bd90c6c9 100644 --- a/system/src/Grav/Common/Cache.php +++ b/system/src/Grav/Common/Cache.php @@ -160,7 +160,7 @@ class Cache extends Getters /** @var EventDispatcher $dispatcher */ $dispatcher = Grav::instance()['events']; - $dispatcher->addListener('onSchedulerInitialized', [$this, 'onSchedulerInitialized']); + $dispatcher->addListener('onSchedulerInitialized', $this->onSchedulerInitialized(...)); } /** @@ -264,8 +264,8 @@ class Cache extends Getters } $this->driver_name = $driver_name; - $namespace = $namespace ?? $this->key; - $defaultLifetime = $defaultLifetime ?? 0; + $namespace ??= $this->key; + $defaultLifetime ??= 0; switch ($driver_name) { case 'apc': diff --git a/system/src/Grav/Common/Config/CompiledBase.php b/system/src/Grav/Common/Config/CompiledBase.php index 1e29ab5b3..b60f05098 100644 --- a/system/src/Grav/Common/Config/CompiledBase.php +++ b/system/src/Grav/Common/Config/CompiledBase.php @@ -202,7 +202,7 @@ abstract class CompiledBase $cache = include $filename; if (!is_array($cache) || !isset($cache['checksum'], $cache['data'], $cache['@class']) - || $cache['@class'] !== get_class($this) + || $cache['@class'] !== static::class ) { return false; } @@ -235,7 +235,7 @@ abstract class CompiledBase // Attempt to lock the file for writing. try { $file->lock(false); - } catch (Exception $e) { + } catch (Exception) { // Another process has locked the file; we will check this in a bit. } @@ -245,7 +245,7 @@ abstract class CompiledBase } $cache = [ - '@class' => get_class($this), + '@class' => static::class, 'timestamp' => time(), 'checksum' => $this->checksum(), 'files' => $this->files, diff --git a/system/src/Grav/Common/Config/Config.php b/system/src/Grav/Common/Config/Config.php index 17eb11784..eb9ef736d 100644 --- a/system/src/Grav/Common/Config/Config.php +++ b/system/src/Grav/Common/Config/Config.php @@ -149,7 +149,7 @@ class Config extends Data */ public function getLanguages() { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use Grav::instance()[\'languages\'] instead', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use Grav::instance()[\'languages\'] instead', E_USER_DEPRECATED); return Grav::instance()['languages']; } diff --git a/system/src/Grav/Common/Config/ConfigFileFinder.php b/system/src/Grav/Common/Config/ConfigFileFinder.php index 6381e48cc..1887e7e82 100644 --- a/system/src/Grav/Common/Config/ConfigFileFinder.php +++ b/system/src/Grav/Common/Config/ConfigFileFinder.php @@ -178,9 +178,7 @@ class ConfigFileFinder 'filters' => [ 'pre-key' => $this->base, 'key' => $pattern, - 'value' => function (RecursiveDirectoryIterator $file) use ($path) { - return ['file' => "{$path}/{$file->getSubPathname()}", 'modified' => $file->getMTime()]; - } + 'value' => fn(RecursiveDirectoryIterator $file) => ['file' => "{$path}/{$file->getSubPathname()}", 'modified' => $file->getMTime()] ], 'key' => 'SubPathname' ]; @@ -254,9 +252,7 @@ class ConfigFileFinder 'filters' => [ 'pre-key' => $this->base, 'key' => $pattern, - 'value' => function (RecursiveDirectoryIterator $file) use ($path) { - return ["{$path}/{$file->getSubPathname()}" => $file->getMTime()]; - } + 'value' => fn(RecursiveDirectoryIterator $file) => ["{$path}/{$file->getSubPathname()}" => $file->getMTime()] ], 'key' => 'SubPathname' ]; diff --git a/system/src/Grav/Common/Config/Setup.php b/system/src/Grav/Common/Config/Setup.php index ba9b52fd4..c7ce0a3b4 100644 --- a/system/src/Grav/Common/Config/Setup.php +++ b/system/src/Grav/Common/Config/Setup.php @@ -202,7 +202,7 @@ class Setup extends Data $setupFile = defined('GRAV_SETUP_PATH') ? GRAV_SETUP_PATH : (getenv('GRAV_SETUP_PATH') ?: null); if (null !== $setupFile) { // Make sure that the custom setup file exists. Terminates the script if not. - if (!str_starts_with($setupFile, '/')) { + if (!str_starts_with((string) $setupFile, '/')) { $setupFile = GRAV_WEBROOT . '/' . $setupFile; } if (!is_file($setupFile)) { diff --git a/system/src/Grav/Common/Data/Blueprint.php b/system/src/Grav/Common/Data/Blueprint.php index 3e84dce10..ef31f4aa4 100644 --- a/system/src/Grav/Common/Data/Blueprint.php +++ b/system/src/Grav/Common/Data/Blueprint.php @@ -168,7 +168,7 @@ class Blueprint extends BlueprintForm // Set dynamic property. foreach ($data as $property => $call) { $action = $call['action']; - $method = 'dynamic' . ucfirst($action); + $method = 'dynamic' . ucfirst((string) $action); $call['object'] = $this->object; if (isset($this->handlers[$action])) { @@ -434,7 +434,7 @@ class Blueprint extends BlueprintForm $params = []; } - [$o, $f] = explode('::', $function, 2); + [$o, $f] = explode('::', (string) $function, 2); $data = null; if (!$f) { @@ -574,10 +574,9 @@ class Blueprint extends BlueprintForm /** * @param array $field * @param string $property - * @param mixed $value * @return void */ - public static function addPropertyRecursive(array &$field, $property, $value) + public static function addPropertyRecursive(array &$field, $property, mixed $value) { if (is_array($value) && isset($field[$property]) && is_array($field[$property])) { $field[$property] = array_merge_recursive($field[$property], $value); diff --git a/system/src/Grav/Common/Data/BlueprintSchema.php b/system/src/Grav/Common/Data/BlueprintSchema.php index 1408cb640..5e13dcae4 100644 --- a/system/src/Grav/Common/Data/BlueprintSchema.php +++ b/system/src/Grav/Common/Data/BlueprintSchema.php @@ -130,7 +130,7 @@ class BlueprintSchema extends BlueprintSchemaBase implements ExportInterface foreach ($items as $key => $rules) { $type = $rules['type'] ?? ''; $ignore = (bool) array_filter((array)($rules['validate']['ignore'] ?? [])) ?? false; - if (!str_starts_with($type, '_') && !str_contains($key, '*') && $ignore !== true) { + if (!str_starts_with((string) $type, '_') && !str_contains((string) $key, '*') && $ignore !== true) { $list[$prefix . $key] = null; } } diff --git a/system/src/Grav/Common/Data/Blueprints.php b/system/src/Grav/Common/Data/Blueprints.php index 5534a1999..f6ad6f094 100644 --- a/system/src/Grav/Common/Data/Blueprints.php +++ b/system/src/Grav/Common/Data/Blueprints.php @@ -22,8 +22,6 @@ use function is_object; */ class Blueprints { - /** @var array|string */ - protected $search; /** @var array */ protected $types; /** @var array */ @@ -32,9 +30,8 @@ class Blueprints /** * @param string|array $search Search path. */ - public function __construct($search = 'blueprints://') + public function __construct(protected $search = 'blueprints://') { - $this->search = $search; } /** diff --git a/system/src/Grav/Common/Data/Data.php b/system/src/Grav/Common/Data/Data.php index 0900a7430..f60b588ca 100644 --- a/system/src/Grav/Common/Data/Data.php +++ b/system/src/Grav/Common/Data/Data.php @@ -103,7 +103,7 @@ class Data implements DataInterface, ArrayAccess, \Countable, JsonSerializable, * @return $this * @throws RuntimeException */ - public function join($name, $value, $separator = '.') + public function join($name, mixed $value, $separator = '.') { $old = $this->get($name, null, $separator); if ($old !== null) { @@ -145,7 +145,7 @@ class Data implements DataInterface, ArrayAccess, \Countable, JsonSerializable, * @param string $separator Separator, defaults to '.' * @return $this */ - public function joinDefaults($name, $value, $separator = '.') + public function joinDefaults($name, mixed $value, $separator = '.') { if (is_object($value)) { $value = (array) $value; diff --git a/system/src/Grav/Common/Data/DataInterface.php b/system/src/Grav/Common/Data/DataInterface.php index a34fe69ad..9cbed8302 100644 --- a/system/src/Grav/Common/Data/DataInterface.php +++ b/system/src/Grav/Common/Data/DataInterface.php @@ -28,7 +28,7 @@ interface DataInterface * @param string $separator Separator, defaults to '.' * @return mixed Value. */ - public function value($name, $default = null, $separator = '.'); + public function value($name, mixed $default = null, $separator = '.'); /** * Merge external data. diff --git a/system/src/Grav/Common/Data/Validation.php b/system/src/Grav/Common/Data/Validation.php index 1b799ad87..a9945f9ec 100644 --- a/system/src/Grav/Common/Data/Validation.php +++ b/system/src/Grav/Common/Data/Validation.php @@ -37,11 +37,10 @@ class Validation /** * Validate value against a blueprint field definition. * - * @param mixed $value * @param array $field * @return array */ - public static function validate($value, array $field) + public static function validate(mixed $value, array $field) { if (!isset($field['type'])) { $field['type'] = 'text'; @@ -76,7 +75,7 @@ class Validation $messages = []; - $success = method_exists(__CLASS__, $method) ? self::$method($value, $validate, $field) : true; + $success = method_exists(self::class, $method) ? self::$method($value, $validate, $field) : true; if (!$success) { $messages[$field['name']][] = $message; } @@ -85,7 +84,7 @@ class Validation foreach ($validate as $rule => $params) { $method = 'validate' . ucfirst(str_replace('-', '_', $rule)); - if (method_exists(__CLASS__, $method)) { + if (method_exists(self::class, $method)) { $success = self::$method($value, $params); if (!$success) { @@ -98,11 +97,10 @@ class Validation } /** - * @param mixed $value * @param array $field * @return array */ - public static function checkSafety($value, array $field) + public static function checkSafety(mixed $value, array $field) { $messages = []; @@ -115,7 +113,7 @@ class Validation $options = []; } - $name = ucfirst($field['label'] ?? $field['name'] ?? 'UNKNOWN'); + $name = ucfirst((string) ($field['label'] ?? $field['name'] ?? 'UNKNOWN')); /** @var UserInterface $user */ $user = Grav::instance()['user'] ?? null; @@ -186,11 +184,10 @@ class Validation /** * Filter value against a blueprint field definition. * - * @param mixed $value * @param array $field * @return mixed Filtered value. */ - public static function filter($value, array $field) + public static function filter(mixed $value, array $field) { $validate = (array)($field['filter'] ?? $field['validate'] ?? null); @@ -211,7 +208,7 @@ class Validation $method = 'filterYaml'; } - if (!method_exists(__CLASS__, $method)) { + if (!method_exists(self::class, $method)) { $method = isset($field['array']) && $field['array'] === true ? 'filterArray' : 'filterText'; } @@ -226,7 +223,7 @@ class Validation * @param array $field Blueprint for the field. * @return bool True if validation succeeded. */ - public static function typeText($value, array $params, array $field) + public static function typeText(mixed $value, array $params, array $field) { if (!is_string($value) && !is_numeric($value)) { return false; @@ -239,7 +236,7 @@ class Validation } $value = preg_replace("/\r\n|\r/um", "\n", $value); - $len = mb_strlen($value); + $len = mb_strlen((string) $value); $min = (int)($params['min'] ?? 0); if ($min && $len < $min) { @@ -258,7 +255,7 @@ class Validation return false; } - if (!$multiline && preg_match('/\R/um', $value)) { + if (!$multiline && preg_match('/\R/um', (string) $value)) { return false; } @@ -266,12 +263,11 @@ class Validation } /** - * @param mixed $value * @param array $params * @param array $field * @return string */ - protected static function filterText($value, array $params, array $field) + protected static function filterText(mixed $value, array $params, array $field) { if (!is_string($value) && !is_numeric($value)) { return ''; @@ -287,12 +283,11 @@ class Validation } /** - * @param mixed $value * @param array $params * @param array $field * @return string|null */ - protected static function filterCheckbox($value, array $params, array $field) + protected static function filterCheckbox(mixed $value, array $params, array $field) { $value = (string)$value; $field_value = (string)($field['value'] ?? '1'); @@ -301,23 +296,21 @@ class Validation } /** - * @param mixed $value * @param array $params * @param array $field * @return array|array[]|false|string[] */ - protected static function filterCommaList($value, array $params, array $field) + protected static function filterCommaList(mixed $value, array $params, array $field) { - return is_array($value) ? $value : preg_split('/\s*,\s*/', $value, -1, PREG_SPLIT_NO_EMPTY); + return is_array($value) ? $value : preg_split('/\s*,\s*/', (string) $value, -1, PREG_SPLIT_NO_EMPTY); } /** - * @param mixed $value * @param array $params * @param array $field * @return bool */ - public static function typeCommaList($value, array $params, array $field) + public static function typeCommaList(mixed $value, array $params, array $field) { if (!isset($params['max'])) { $params['max'] = 2048; @@ -327,34 +320,31 @@ class Validation } /** - * @param mixed $value * @param array $params * @param array $field * @return array|array[]|false|string[] */ - protected static function filterLines($value, array $params, array $field) + protected static function filterLines(mixed $value, array $params, array $field) { - return is_array($value) ? $value : preg_split('/\s*[\r\n]+\s*/', $value, -1, PREG_SPLIT_NO_EMPTY); + return is_array($value) ? $value : preg_split('/\s*[\r\n]+\s*/', (string) $value, -1, PREG_SPLIT_NO_EMPTY); } /** - * @param mixed $value * @param array $params * @return string */ - protected static function filterLower($value, array $params) + protected static function filterLower(mixed $value, array $params) { - return mb_strtolower($value); + return mb_strtolower((string) $value); } /** - * @param mixed $value * @param array $params * @return string */ - protected static function filterUpper($value, array $params) + protected static function filterUpper(mixed $value, array $params) { - return mb_strtoupper($value); + return mb_strtoupper((string) $value); } @@ -366,7 +356,7 @@ class Validation * @param array $field Blueprint for the field. * @return bool True if validation succeeded. */ - public static function typeTextarea($value, array $params, array $field) + public static function typeTextarea(mixed $value, array $params, array $field) { if (!isset($params['multiline'])) { $params['multiline'] = true; @@ -383,7 +373,7 @@ class Validation * @param array $field Blueprint for the field. * @return bool True if validation succeeded. */ - public static function typePassword($value, array $params, array $field) + public static function typePassword(mixed $value, array $params, array $field) { if (!isset($params['max'])) { $params['max'] = 256; @@ -400,7 +390,7 @@ class Validation * @param array $field Blueprint for the field. * @return bool True if validation succeeded. */ - public static function typeHidden($value, array $params, array $field) + public static function typeHidden(mixed $value, array $params, array $field) { return self::typeText($value, $params, $field); } @@ -413,7 +403,7 @@ class Validation * @param array $field Blueprint for the field. * @return bool True if validation succeeded. */ - public static function typeCheckboxes($value, array $params, array $field) + public static function typeCheckboxes(mixed $value, array $params, array $field) { // Set multiple: true so checkboxes can easily use min/max counts to control number of options required $field['multiple'] = true; @@ -422,12 +412,11 @@ class Validation } /** - * @param mixed $value * @param array $params * @param array $field * @return array|null */ - protected static function filterCheckboxes($value, array $params, array $field) + protected static function filterCheckboxes(mixed $value, array $params, array $field) { return self::filterArray($value, $params, $field); } @@ -440,7 +429,7 @@ class Validation * @param array $field Blueprint for the field. * @return bool True if validation succeeded. */ - public static function typeCheckbox($value, array $params, array $field) + public static function typeCheckbox(mixed $value, array $params, array $field) { $value = (string)$value; $field_value = (string)($field['value'] ?? '1'); @@ -456,7 +445,7 @@ class Validation * @param array $field Blueprint for the field. * @return bool True if validation succeeded. */ - public static function typeRadio($value, array $params, array $field) + public static function typeRadio(mixed $value, array $params, array $field) { return self::typeArray((array) $value, $params, $field); } @@ -469,7 +458,7 @@ class Validation * @param array $field Blueprint for the field. * @return bool True if validation succeeded. */ - public static function typeToggle($value, array $params, array $field) + public static function typeToggle(mixed $value, array $params, array $field) { if (is_bool($value)) { $value = (int)$value; @@ -486,18 +475,17 @@ class Validation * @param array $field Blueprint for the field. * @return bool True if validation succeeded. */ - public static function typeFile($value, array $params, array $field) + public static function typeFile(mixed $value, array $params, array $field) { return self::typeArray((array)$value, $params, $field); } /** - * @param mixed $value * @param array $params * @param array $field * @return array */ - protected static function filterFile($value, array $params, array $field) + protected static function filterFile(mixed $value, array $params, array $field) { return (array)$value; } @@ -510,7 +498,7 @@ class Validation * @param array $field Blueprint for the field. * @return bool True if validation succeeded. */ - public static function typeSelect($value, array $params, array $field) + public static function typeSelect(mixed $value, array $params, array $field) { return self::typeArray((array) $value, $params, $field); } @@ -523,7 +511,7 @@ class Validation * @param array $field Blueprint for the field. * @return bool True if validation succeeded. */ - public static function typeNumber($value, array $params, array $field) + public static function typeNumber(mixed $value, array $params, array $field) { if (!is_numeric($value)) { return false; @@ -558,23 +546,21 @@ class Validation } /** - * @param mixed $value * @param array $params * @param array $field * @return float|int */ - protected static function filterNumber($value, array $params, array $field) + protected static function filterNumber(mixed $value, array $params, array $field) { return (string)(int)$value !== (string)(float)$value ? (float)$value : (int)$value; } /** - * @param mixed $value * @param array $params * @param array $field * @return string */ - protected static function filterDateTime($value, array $params, array $field) + protected static function filterDateTime(mixed $value, array $params, array $field) { $format = Grav::instance()['config']->get('system.pages.dateformat.default'); if ($format) { @@ -592,18 +578,17 @@ class Validation * @param array $field Blueprint for the field. * @return bool True if validation succeeded. */ - public static function typeRange($value, array $params, array $field) + public static function typeRange(mixed $value, array $params, array $field) { return self::typeNumber($value, $params, $field); } /** - * @param mixed $value * @param array $params * @param array $field * @return float|int */ - protected static function filterRange($value, array $params, array $field) + protected static function filterRange(mixed $value, array $params, array $field) { return self::filterNumber($value, $params, $field); } @@ -616,9 +601,9 @@ class Validation * @param array $field Blueprint for the field. * @return bool True if validation succeeded. */ - public static function typeColor($value, array $params, array $field) + public static function typeColor(mixed $value, array $params, array $field) { - return (bool)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', (string) $value); } /** @@ -629,7 +614,7 @@ class Validation * @param array $field Blueprint for the field. * @return bool True if validation succeeded. */ - public static function typeEmail($value, array $params, array $field) + public static function typeEmail(mixed $value, array $params, array $field) { if (empty($value)) { return false; @@ -639,10 +624,10 @@ class Validation $params['max'] = 320; } - $values = !is_array($value) ? explode(',', preg_replace('/\s+/', '', $value)) : $value; + $values = !is_array($value) ? explode(',', preg_replace('/\s+/', '', (string) $value)) : $value; foreach ($values as $val) { - if (!(self::typeText($val, $params, $field) && strpos($val, '@', 1))) { + if (!(self::typeText($val, $params, $field) && strpos((string) $val, '@', 1))) { return false; } } @@ -658,7 +643,7 @@ class Validation * @param array $field Blueprint for the field. * @return bool True if validation succeeded. */ - public static function typeUrl($value, array $params, array $field) + public static function typeUrl(mixed $value, array $params, array $field) { if (!isset($params['max'])) { $params['max'] = 2048; @@ -675,7 +660,7 @@ class Validation * @param array $field Blueprint for the field. * @return bool True if validation succeeded. */ - public static function typeDatetime($value, array $params, array $field) + public static function typeDatetime(mixed $value, array $params, array $field) { if ($value instanceof DateTime) { return true; @@ -700,7 +685,7 @@ class Validation * @param array $field Blueprint for the field. * @return bool True if validation succeeded. */ - public static function typeDatetimeLocal($value, array $params, array $field) + public static function typeDatetimeLocal(mixed $value, array $params, array $field) { return self::typeDatetime($value, $params, $field); } @@ -713,7 +698,7 @@ class Validation * @param array $field Blueprint for the field. * @return bool True if validation succeeded. */ - public static function typeDate($value, array $params, array $field) + public static function typeDate(mixed $value, array $params, array $field) { if (!isset($params['format'])) { $params['format'] = 'Y-m-d'; @@ -730,7 +715,7 @@ class Validation * @param array $field Blueprint for the field. * @return bool True if validation succeeded. */ - public static function typeTime($value, array $params, array $field) + public static function typeTime(mixed $value, array $params, array $field) { if (!isset($params['format'])) { $params['format'] = 'H:i'; @@ -747,7 +732,7 @@ class Validation * @param array $field Blueprint for the field. * @return bool True if validation succeeded. */ - public static function typeMonth($value, array $params, array $field) + public static function typeMonth(mixed $value, array $params, array $field) { if (!isset($params['format'])) { $params['format'] = 'Y-m'; @@ -764,9 +749,9 @@ class Validation * @param array $field Blueprint for the field. * @return bool True if validation succeeded. */ - public static function typeWeek($value, array $params, array $field) + public static function typeWeek(mixed $value, array $params, array $field) { - if (!isset($params['format']) && !preg_match('/^\d{4}-W\d{2}$/u', $value)) { + if (!isset($params['format']) && !preg_match('/^\d{4}-W\d{2}$/u', (string) $value)) { return false; } @@ -781,7 +766,7 @@ class Validation * @param array $field Blueprint for the field. * @return bool True if validation succeeded. */ - public static function typeArray($value, array $params, array $field) + public static function typeArray(mixed $value, array $params, array $field) { if (!is_array($value)) { return false; @@ -829,12 +814,11 @@ class Validation } /** - * @param mixed $value * @param array $params * @param array $field * @return array|null */ - protected static function filterFlatten_array($value, $params, $field) + protected static function filterFlatten_array(mixed $value, $params, $field) { $value = static::filterArray($value, $params, $field); @@ -842,12 +826,11 @@ class Validation } /** - * @param mixed $value * @param array $params * @param array $field * @return array|null */ - protected static function filterArray($value, $params, $field) + protected static function filterArray(mixed $value, $params, $field) { $values = (array) $value; $options = isset($field['options']) ? array_keys($field['options']) : []; @@ -871,7 +854,7 @@ class Validation $val = implode(',', $val); $values[$key] = array_map('trim', explode(',', $val)); } else { - $values[$key] = trim($val); + $values[$key] = trim((string) $val); } } } @@ -895,16 +878,11 @@ class Validation { foreach ($values as $key => &$val) { if ($params['key_type']) { - switch ($params['key_type']) { - case 'int': - $result = is_int($key); - break; - case 'string': - $result = is_string($key); - break; - default: - $result = false; - } + $result = match ($params['key_type']) { + 'int' => is_int($key), + 'string' => is_string($key), + default => false, + }; if (!$result) { unset($values[$key]); } @@ -937,7 +915,7 @@ class Validation $val = (string)$val; break; case 'trim': - $val = trim($val); + $val = trim((string) $val); break; } } @@ -952,12 +930,11 @@ class Validation } /** - * @param mixed $value * @param array $params * @param array $field * @return bool */ - public static function typeList($value, array $params, array $field) + public static function typeList(mixed $value, array $params, array $field) { if (!is_array($value)) { return false; @@ -966,7 +943,7 @@ class Validation if (isset($field['fields'])) { foreach ($value as $key => $item) { foreach ($field['fields'] as $subKey => $subField) { - $subKey = trim($subKey, '.'); + $subKey = trim((string) $subKey, '.'); $subValue = $item[$subKey] ?? null; self::validate($subValue, $subField); } @@ -977,22 +954,20 @@ class Validation } /** - * @param mixed $value * @param array $params * @param array $field * @return array */ - protected static function filterList($value, array $params, array $field) + protected static function filterList(mixed $value, array $params, array $field) { return (array) $value; } /** - * @param mixed $value * @param array $params * @return array */ - public static function filterYaml($value, $params) + public static function filterYaml(mixed $value, $params) { if (!is_string($value)) { return $value; @@ -1009,18 +984,17 @@ class Validation * @param array $field Blueprint for the field. * @return bool True if validation succeeded. */ - public static function typeIgnore($value, array $params, array $field) + public static function typeIgnore(mixed $value, array $params, array $field) { return true; } /** - * @param mixed $value * @param array $params * @param array $field * @return mixed */ - public static function filterIgnore($value, array $params, array $field) + public static function filterIgnore(mixed $value, array $params, array $field) { return $value; } @@ -1033,30 +1007,27 @@ class Validation * @param array $field Blueprint for the field. * @return bool True if validation succeeded. */ - public static function typeUnset($value, array $params, array $field) + public static function typeUnset(mixed $value, array $params, array $field) { return true; } /** - * @param mixed $value * @param array $params * @param array $field * @return null */ - public static function filterUnset($value, array $params, array $field) + public static function filterUnset(mixed $value, array $params, array $field) { return null; } // HTML5 attributes (min, max and range are handled inside the types) - /** - * @param mixed $value * @param bool $params * @return bool */ - public static function validateRequired($value, $params) + public static function validateRequired(mixed $value, $params) { if (is_scalar($value)) { return (bool) $params !== true || $value !== ''; @@ -1066,105 +1037,85 @@ class Validation } /** - * @param mixed $value * @param string $params * @return bool */ - public static function validatePattern($value, $params) + public static function validatePattern(mixed $value, $params) { - return (bool) preg_match("`^{$params}$`u", $value); + return (bool) preg_match("`^{$params}$`u", (string) $value); } // Internal types - /** - * @param mixed $value - * @param mixed $params * @return bool */ - public static function validateAlpha($value, $params) + public static function validateAlpha(mixed $value, mixed $params) { - return ctype_alpha($value); + return ctype_alpha((string) $value); } /** - * @param mixed $value - * @param mixed $params * @return bool */ - public static function validateAlnum($value, $params) + public static function validateAlnum(mixed $value, mixed $params) { - return ctype_alnum($value); + return ctype_alnum((string) $value); } /** - * @param mixed $value - * @param mixed $params * @return bool */ - public static function typeBool($value, $params) + public static function typeBool(mixed $value, mixed $params) { return is_bool($value) || $value == 1 || $value == 0; } /** - * @param mixed $value - * @param mixed $params * @return bool */ - public static function validateBool($value, $params) + public static function validateBool(mixed $value, mixed $params) { return is_bool($value) || $value == 1 || $value == 0; } /** - * @param mixed $value - * @param mixed $params * @return bool */ - protected static function filterBool($value, $params) + protected static function filterBool(mixed $value, mixed $params) { return (bool) $value; } /** - * @param mixed $value - * @param mixed $params * @return bool */ - public static function validateDigit($value, $params) + public static function validateDigit(mixed $value, mixed $params) { - return ctype_digit($value); + return ctype_digit((string) $value); } /** - * @param mixed $value - * @param mixed $params * @return bool */ - public static function validateFloat($value, $params) + public static function validateFloat(mixed $value, mixed $params) { return is_float(filter_var($value, FILTER_VALIDATE_FLOAT)); } /** - * @param mixed $value - * @param mixed $params * @return float */ - protected static function filterFloat($value, $params) + protected static function filterFloat(mixed $value, mixed $params) { return (float) $value; } /** - * @param mixed $value - * @param mixed $params * @return bool */ - public static function validateHex($value, $params) + public static function validateHex(mixed $value, mixed $params) { - return ctype_xdigit($value); + return ctype_xdigit((string) $value); } /** @@ -1175,7 +1126,7 @@ class Validation * @param array $field Blueprint for the field. * @return bool True if validation succeeded. */ - public static function typeInt($value, array $params, array $field) + public static function typeInt(mixed $value, array $params, array $field) { $params['step'] = max(1, (int)($params['step'] ?? 0)); @@ -1183,54 +1134,42 @@ class Validation } /** - * @param mixed $value - * @param mixed $params * @return bool */ - public static function validateInt($value, $params) + public static function validateInt(mixed $value, mixed $params) { return is_numeric($value) && (int)$value == $value; } /** - * @param mixed $value - * @param mixed $params * @return int */ - protected static function filterInt($value, $params) + protected static function filterInt(mixed $value, mixed $params) { return (int)$value; } /** - * @param mixed $value - * @param mixed $params * @return bool */ - public static function validateArray($value, $params) + public static function validateArray(mixed $value, mixed $params) { return is_array($value) || ($value instanceof ArrayAccess && $value instanceof Traversable && $value instanceof Countable); } /** - * @param mixed $value - * @param mixed $params * @return array */ - public static function filterItem_List($value, $params) + public static function filterItem_List(mixed $value, mixed $params) { - return array_values(array_filter($value, static function ($v) { - return !empty($v); - })); + return array_values(array_filter($value, static fn($v) => !empty($v))); } /** - * @param mixed $value - * @param mixed $params * @return bool */ - public static function validateJson($value, $params) + public static function validateJson(mixed $value, mixed $params) { - return (bool) (@json_decode($value)); + return (bool) (@json_decode((string) $value)); } } diff --git a/system/src/Grav/Common/Data/ValidationException.php b/system/src/Grav/Common/Data/ValidationException.php index 72570a16f..73a1955ed 100644 --- a/system/src/Grav/Common/Data/ValidationException.php +++ b/system/src/Grav/Common/Data/ValidationException.php @@ -37,7 +37,7 @@ class ValidationException extends RuntimeException implements JsonSerializable foreach ($messages as $list) { $list = array_unique($list); foreach ($list as $message) { - $this->message .= '
' . htmlspecialchars($message, ENT_QUOTES | ENT_HTML5, 'UTF-8'); + $this->message .= '
' . htmlspecialchars((string) $message, ENT_QUOTES | ENT_HTML5, 'UTF-8'); } } @@ -49,7 +49,7 @@ class ValidationException extends RuntimeException implements JsonSerializable $first = reset($this->messages); $message = reset($first); - $this->message = $escape ? htmlspecialchars($message, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $message; + $this->message = $escape ? htmlspecialchars((string) $message, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $message; } /** diff --git a/system/src/Grav/Common/Debugger.php b/system/src/Grav/Common/Debugger.php index c732cbeaf..0bac330bd 100644 --- a/system/src/Grav/Common/Debugger.php +++ b/system/src/Grav/Common/Debugger.php @@ -328,9 +328,7 @@ class Debugger return new Response(404, $headers, json_encode($response)); } - $data = is_array($data) ? array_map(static function ($item) { - return $item->toArray(); - }, $data) : $data->toArray(); + $data = is_array($data) ? array_map(static fn($item) => $item->toArray(), $data) : $data->toArray(); return new Response(200, $headers, json_encode($data)); } @@ -619,13 +617,9 @@ class Debugger protected function buildProfilerTimings(array $timings): array { // Filter method calls which take almost no time. - $timings = array_filter($timings, function ($value) { - return $value['wt'] > 50; - }); + $timings = array_filter($timings, fn($value) => $value['wt'] > 50); - uasort($timings, function (array $a, array $b) { - return $b['wt'] <=> $a['wt']; - }); + uasort($timings, fn(array $a, array $b) => $b['wt'] <=> $a['wt']); $table = []; foreach ($timings as $key => $timing) { @@ -639,7 +633,7 @@ class Debugger } // Do not profile library calls. - if (strpos($context, 'Grav\\') !== 0) { + if (!str_starts_with((string) $context, 'Grav\\')) { continue; } @@ -721,12 +715,11 @@ class Debugger /** * Dump variables into the Messages tab of the Debug Bar * - * @param mixed $message * @param string $label * @param mixed|bool $isString * @return $this */ - public function addMessage($message, $label = 'info', $isString = true) + public function addMessage(mixed $message, $label = 'info', $isString = true) { if ($this->enabled) { if ($this->censored) { @@ -779,7 +772,7 @@ class Debugger public function addEvent(string $name, $event, EventDispatcherInterface $dispatcher, ?float $time = null) { if ($this->enabled && $this->clockwork) { - $time = $time ?? microtime(true); + $time ??= microtime(true); $duration = (microtime(true) - $time) * 1000; $data = null; @@ -829,7 +822,7 @@ class Debugger public function setErrorHandler() { $this->errorHandler = set_error_handler( - [$this, 'deprecatedErrorHandler'] + $this->deprecatedErrorHandler(...) ); } @@ -858,7 +851,7 @@ class Debugger $scope = 'unknown'; if (stripos($errstr, 'grav') !== false) { $scope = 'grav'; - } elseif (strpos($errfile, '/twig/') !== false) { + } elseif (str_contains($errfile, '/twig/')) { $scope = 'twig'; // TODO: remove when upgrading to Twig 2+ if (str_contains($errstr, '#[\ReturnTypeWillChange]') || str_contains($errstr, 'Passing null to parameter')) { @@ -866,7 +859,7 @@ class Debugger } } elseif (stripos($errfile, '/yaml/') !== false) { $scope = 'yaml'; - } elseif (strpos($errfile, '/vendor/') !== false) { + } elseif (str_contains($errfile, '/vendor/')) { $scope = 'vendor'; } @@ -912,7 +905,7 @@ class Debugger } elseif (is_scalar($arg)) { $arg = $arg; } elseif (is_object($arg)) { - $arg = get_class($arg) . ' $object'; + $arg = $arg::class . ' $object'; } elseif (is_array($arg)) { $arg = '$array'; } else { @@ -938,7 +931,7 @@ class Debugger if ($object instanceof Template) { $file = $current['file'] ?? null; - if (preg_match('`(Template.php|TemplateWrapper.php)$`', $file)) { + if (preg_match('`(Template.php|TemplateWrapper.php)$`', (string) $file)) { $current = null; continue; } @@ -998,7 +991,7 @@ class Debugger if (!isset($current['file'])) { continue; } - if (strpos($current['file'], '/vendor/') !== false) { + if (str_contains($current['file'], '/vendor/')) { $cut = $i + 1; continue; } @@ -1073,7 +1066,7 @@ class Debugger /** @var array $deprecated */ foreach ($this->deprecations as $deprecated) { - list($message, $scope) = $this->getDepracatedMessage($deprecated); + [$message, $scope] = $this->getDepracatedMessage($deprecated); $collector->addMessage($message, $scope); } @@ -1140,7 +1133,7 @@ class Debugger protected function resolveCallable(callable $callable) { if (is_array($callable)) { - return get_class($callable[0]) . '->' . $callable[1] . '()'; + return $callable[0]::class . '->' . $callable[1] . '()'; } return 'unknown'; diff --git a/system/src/Grav/Common/Errors/SimplePageHandler.php b/system/src/Grav/Common/Errors/SimplePageHandler.php index 4f11fdd77..50143c3f2 100644 --- a/system/src/Grav/Common/Errors/SimplePageHandler.php +++ b/system/src/Grav/Common/Errors/SimplePageHandler.php @@ -54,11 +54,7 @@ class SimplePageHandler extends Handler $code = Misc::translateErrorCode($code); } - $vars = array( - 'stylesheet' => file_get_contents($cssFile), - 'code' => $code, - 'message' => htmlspecialchars(strip_tags(rawurldecode($message)), ENT_QUOTES, 'UTF-8'), - ); + $vars = ['stylesheet' => file_get_contents($cssFile), 'code' => $code, 'message' => htmlspecialchars(strip_tags(rawurldecode($message)), ENT_QUOTES, 'UTF-8')]; $helper->setVariables($vars); $helper->render($templateFile); diff --git a/system/src/Grav/Common/File/CompiledFile.php b/system/src/Grav/Common/File/CompiledFile.php index 1266e9dc9..d7ea266e0 100644 --- a/system/src/Grav/Common/File/CompiledFile.php +++ b/system/src/Grav/Common/File/CompiledFile.php @@ -28,10 +28,9 @@ trait CompiledFile /** * Get/set parsed file contents. * - * @param mixed $var * @return array */ - public function content($var = null) + public function content(mixed $var = null) { try { $filename = $this->filename; @@ -44,12 +43,12 @@ trait CompiledFile if (!$modified) { try { return $this->decode($this->raw()); - } catch (Throwable $e) { + } catch (Throwable) { // If the compiled file is broken, we can safely ignore the error and continue. } } - $class = get_class($this); + $class = $this::class; $size = filesize($filename); $cache = $file->exists() ? $file->content() : null; @@ -115,7 +114,7 @@ trait CompiledFile * @return void * @throws RuntimeException */ - public function save($data = null) + public function save(mixed $data = null) { // Make sure that the cache file is always up to date! $key = md5($this->filename); @@ -135,7 +134,7 @@ trait CompiledFile if ($locked) { $modified = $this->modified(); $filename = $this->filename; - $class = get_class($this); + $class = $this::class; $size = filesize($filename); // windows doesn't play nicely with this as it can't read when locked diff --git a/system/src/Grav/Common/Filesystem/Folder.php b/system/src/Grav/Common/Filesystem/Folder.php index 06f489de5..f6ce1b3af 100644 --- a/system/src/Grav/Common/Filesystem/Folder.php +++ b/system/src/Grav/Common/Filesystem/Folder.php @@ -153,8 +153,8 @@ abstract class Folder if ($base) { $base = preg_replace('![\\\/]+!', '/', $base); $path = preg_replace('![\\\/]+!', '/', $path); - if (strpos($path, $base) === 0) { - $path = ltrim(substr($path, strlen($base)), '/'); + if (str_starts_with((string) $path, (string) $base)) { + $path = ltrim(substr((string) $path, strlen((string) $base)), '/'); } } @@ -178,8 +178,8 @@ abstract class Folder return ''; } - $baseParts = explode('/', ltrim($base, '/')); - $pathParts = explode('/', ltrim($path, '/')); + $baseParts = explode('/', ltrim((string) $base, '/')); + $pathParts = explode('/', ltrim((string) $path, '/')); array_pop($baseParts); $lastPart = array_pop($pathParts); @@ -194,7 +194,7 @@ abstract class Folder $path = str_repeat('../', count($baseParts)) . implode('/', $pathParts); return '' === $path - || strpos($path, '/') === 0 + || str_starts_with($path, '/') || false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos) ? "./$path" : $path; } @@ -266,7 +266,7 @@ abstract class Folder /** @var RecursiveDirectoryIterator $file */ foreach ($iterator as $file) { // Ignore hidden files. - if (strpos($file->getFilename(), '.') === 0 && $file->isFile()) { + if (str_starts_with($file->getFilename(), '.') && $file->isFile()) { continue; } if (!$folders && $file->isDir()) { @@ -275,7 +275,7 @@ abstract class Folder if (!$files && $file->isFile()) { continue; } - if ($compare && $pattern && !preg_match($pattern, $file->{$compare}())) { + if ($compare && $pattern && !preg_match($pattern, (string) $file->{$compare}())) { continue; } $fileKey = $key ? $file->{$key}() : null; @@ -283,14 +283,14 @@ abstract class Folder if ($filters) { if (isset($filters['key'])) { $pre = !empty($filters['pre-key']) ? $filters['pre-key'] : ''; - $fileKey = $pre . preg_replace($filters['key'], '', $fileKey); + $fileKey = $pre . preg_replace($filters['key'], '', (string) $fileKey); } if (isset($filters['value'])) { $filter = $filters['value']; if (is_callable($filter)) { $filePath = $filter($file); } else { - $filePath = preg_replace($filter, '', $filePath); + $filePath = preg_replace($filter, '', (string) $filePath); } } } @@ -331,7 +331,7 @@ abstract class Folder // Go through all sub-directories and copy everything. $files = self::all($source); foreach ($files as $file) { - if ($ignore && preg_match($ignore, $file)) { + if ($ignore && preg_match($ignore, (string) $file)) { continue; } $src = $source .'/'. $file; @@ -377,7 +377,7 @@ abstract class Folder return; } - if (strpos($target, $source . '/') === 0) { + if (str_starts_with($target, $source . '/')) { throw new RuntimeException('Cannot move folder to itself'); } diff --git a/system/src/Grav/Common/Filesystem/ZipArchiver.php b/system/src/Grav/Common/Filesystem/ZipArchiver.php index 82b5a769c..05d77ead7 100644 --- a/system/src/Grav/Common/Filesystem/ZipArchiver.php +++ b/system/src/Grav/Common/Filesystem/ZipArchiver.php @@ -77,7 +77,7 @@ class ZipArchiver extends Archiver foreach ($files as $file) { $filePath = $file->getPathname(); - $relativePath = ltrim(substr($filePath, strlen($rootPath)), '/'); + $relativePath = ltrim(substr((string) $filePath, strlen($rootPath)), '/'); if ($file->isDir()) { $zip->addEmptyDir($relativePath); diff --git a/system/src/Grav/Common/Flex/Traits/FlexCollectionTrait.php b/system/src/Grav/Common/Flex/Traits/FlexCollectionTrait.php index ba1b8a133..3d9dcee2b 100644 --- a/system/src/Grav/Common/Flex/Traits/FlexCollectionTrait.php +++ b/system/src/Grav/Common/Flex/Traits/FlexCollectionTrait.php @@ -35,7 +35,7 @@ trait FlexCollectionTrait 'collection' => $this ]); } - if (strpos($name, 'onFlexCollection') !== 0 && strpos($name, 'on') === 0) { + if (!str_starts_with($name, 'onFlexCollection') && str_starts_with($name, 'on')) { $name = 'onFlexCollection' . substr($name, 2); } diff --git a/system/src/Grav/Common/Flex/Traits/FlexObjectTrait.php b/system/src/Grav/Common/Flex/Traits/FlexObjectTrait.php index 2a058062f..26c4e035c 100644 --- a/system/src/Grav/Common/Flex/Traits/FlexObjectTrait.php +++ b/system/src/Grav/Common/Flex/Traits/FlexObjectTrait.php @@ -46,7 +46,7 @@ trait FlexObjectTrait if (isset($events['name'])) { $name = $events['name']; - } elseif (strpos($name, 'onFlexObject') !== 0 && strpos($name, 'on') === 0) { + } elseif (!str_starts_with($name, 'onFlexObject') && str_starts_with($name, 'on')) { $name = 'onFlexObject' . substr($name, 2); } diff --git a/system/src/Grav/Common/Flex/Types/Pages/PageCollection.php b/system/src/Grav/Common/Flex/Types/Pages/PageCollection.php index a061f86ef..679e7fbda 100644 --- a/system/src/Grav/Common/Flex/Types/Pages/PageCollection.php +++ b/system/src/Grav/Common/Flex/Types/Pages/PageCollection.php @@ -172,7 +172,7 @@ class PageCollection extends FlexPageCollection implements PageCollectionInterfa * @return static * @phpstan-return static */ - public function merge(PageCollectionInterface $collection) + public function merge(PageCollectionInterface $collection): never { throw new RuntimeException(__METHOD__ . '(): Not Implemented'); } @@ -184,7 +184,7 @@ class PageCollection extends FlexPageCollection implements PageCollectionInterfa * @return static * @phpstan-return static */ - public function intersect(PageCollectionInterface $collection) + public function intersect(PageCollectionInterface $collection): never { throw new RuntimeException(__METHOD__ . '(): Not Implemented'); } @@ -242,7 +242,7 @@ class PageCollection extends FlexPageCollection implements PageCollectionInterfa * @return static * @phpstan-return static */ - public function append($items) + public function append($items): never { throw new RuntimeException(__METHOD__ . '(): Not Implemented'); } @@ -303,7 +303,7 @@ class PageCollection extends FlexPageCollection implements PageCollectionInterfa // do this header query work only once $header_query = null; $header_default = null; - if (strpos($order_by, 'header.') === 0) { + if (str_starts_with($order_by, 'header.')) { $query = explode('|', str_replace('header.', '', $order_by), 2); $header_query = array_shift($query) ?? ''; $header_default = array_shift($query); @@ -373,9 +373,7 @@ class PageCollection extends FlexPageCollection implements PageCollectionInterfa if ($col) { $col->setAttribute(Collator::NUMERIC_COLLATION, Collator::ON); if (($sort_flags & SORT_NATURAL) === SORT_NATURAL) { - $list = preg_replace_callback('~([0-9]+)\.~', static function ($number) { - return sprintf('%032d.', $number[0]); - }, $list); + $list = preg_replace_callback('~([0-9]+)\.~', static fn($number) => sprintf('%032d.', $number[0]), $list); if (!is_array($list)) { throw new RuntimeException('Internal Error'); } @@ -457,7 +455,7 @@ class PageCollection extends FlexPageCollection implements PageCollectionInterfa continue; } - $date = $field ? strtotime($object->getNestedProperty($field)) : $object->date(); + $date = $field ? strtotime((string) $object->getNestedProperty($field)) : $object->date(); if ((!$start || $date >= $start) && (!$end || $date <= $end)) { $entries[$key] = $object; diff --git a/system/src/Grav/Common/Flex/Types/Pages/PageIndex.php b/system/src/Grav/Common/Flex/Types/Pages/PageIndex.php index 82e8501ea..c3b393752 100644 --- a/system/src/Grav/Common/Flex/Types/Pages/PageIndex.php +++ b/system/src/Grav/Common/Flex/Types/Pages/PageIndex.php @@ -239,10 +239,9 @@ class PageIndex extends FlexPageIndex implements PageCollectionInterface * Set a parameter to the Collection * * @param string $name - * @param mixed $value * @return $this */ - public function setParam(string $name, $value) + public function setParam(string $name, mixed $value) { $this->_params[$name] = $value; @@ -495,7 +494,7 @@ class PageIndex extends FlexPageIndex implements PageCollectionInterface */ protected function getFallbackLanguages(?string $languageCode = null, ?bool $fallback = null): array { - $fallback = $fallback ?? true; + $fallback ??= true; if (!$fallback && null !== $languageCode) { return [$languageCode]; } @@ -504,7 +503,7 @@ class PageIndex extends FlexPageIndex implements PageCollectionInterface /** @var Language $language */ $language = $grav['language']; - $languageCode = $languageCode ?? ''; + $languageCode ??= ''; if ($languageCode === '' && $fallback) { return $language->getFallbackLanguages(null, true); } @@ -533,7 +532,7 @@ class PageIndex extends FlexPageIndex implements PageCollectionInterface // Handle leaf_route $leaf = null; if ($leaf_route && $route !== $leaf_route) { - $nodes = explode('/', $leaf_route); + $nodes = explode('/', (string) $leaf_route); $sub_route = '/' . implode('/', array_slice($nodes, 1, $options['level']++)); $options['route'] = $sub_route; @@ -544,7 +543,7 @@ class PageIndex extends FlexPageIndex implements PageCollectionInterface if (!$route) { $page = $this->getRoot(); } else { - $page = $this->get(trim($route, '/')); + $page = $this->get(trim((string) $route, '/')); } $path = $page ? $page->path() : null; @@ -558,7 +557,7 @@ class PageIndex extends FlexPageIndex implements PageCollectionInterface // Clean up filter. $filter_type = (array)($filters['type'] ?? []); unset($filters['type']); - $filters = array_filter($filters, static function($val) { return $val !== null && $val !== ''; }); + $filters = array_filter($filters, static fn($val) => $val !== null && $val !== ''); if ($page) { $status = 'success'; @@ -682,9 +681,7 @@ class PageIndex extends FlexPageIndex implements PageCollectionInterface 'tags' => $tags, 'actions' => $this->getListingActions($child, $user), ]; - $extras = array_filter($extras, static function ($v) { - return $v !== null; - }); + $extras = array_filter($extras, static fn($v) => $v !== null); /** @var PageIndex $tmp */ $tmp = $child->children()->getIndex(); @@ -698,7 +695,7 @@ class PageIndex extends FlexPageIndex implements PageCollectionInterface 'title' => htmlspecialchars($child->menu()), 'route' => [ 'display' => htmlspecialchars($route) ?: null, - 'raw' => htmlspecialchars($child->rawRoute()), + 'raw' => htmlspecialchars((string) $child->rawRoute()), ], 'modified' => $this->jsDate($child->modified()), 'child_count' => $child_count ?: null, @@ -706,9 +703,7 @@ class PageIndex extends FlexPageIndex implements PageCollectionInterface 'filters_hit' => $filters ? ($child->filterBy($filters, false) ?: null) : null, 'extras' => $extras ]; - $payload = array_filter($payload, static function ($v) { - return $v !== null; - }); + $payload = array_filter($payload, static fn($v) => $v !== null); } // Add children if any diff --git a/system/src/Grav/Common/Flex/Types/Pages/PageObject.php b/system/src/Grav/Common/Flex/Types/Pages/PageObject.php index 2af4ee7c8..e41c35fc1 100644 --- a/system/src/Grav/Common/Flex/Types/Pages/PageObject.php +++ b/system/src/Grav/Common/Flex/Types/Pages/PageObject.php @@ -521,7 +521,7 @@ class PageObject extends FlexPageObject $template = $this->getProperty('template') . ($name ? '.' . $name : ''); $blueprint = $this->getFlexDirectory()->getBlueprint($template, 'blueprints://pages'); - } catch (RuntimeException $e) { + } catch (RuntimeException) { $template = 'default' . ($name ? '.' . $name : ''); $blueprint = $this->getFlexDirectory()->getBlueprint($template, 'blueprints://pages'); @@ -554,7 +554,7 @@ class PageObject extends FlexPageObject $initial = $options['initial'] ?? null; $var = $initial ? 'leaf_route' : 'route'; $route = $options[$var] ?? ''; - if ($route !== '' && !str_starts_with($route, '/')) { + if ($route !== '' && !str_starts_with((string) $route, '/')) { $filesystem = Filesystem::getInstance(); $route = "/{$this->getKey()}/{$route}"; @@ -600,7 +600,7 @@ class PageObject extends FlexPageObject $matches = $test->search((string)$value) > 0.0; break; case 'page_type': - $types = $value ? explode(',', $value) : []; + $types = $value ? explode(',', (string) $value) : []; $matches = in_array($test->template(), $types, true); break; case 'extension': @@ -698,7 +698,7 @@ class PageObject extends FlexPageObject } elseif (array_key_exists('ordering', $elements) && array_key_exists('order', $elements)) { // Store ordering. $ordering = $elements['order'] ?? null; - $this->_reorder = !empty($ordering) ? explode(',', $ordering) : []; + $this->_reorder = !empty($ordering) ? explode(',', (string) $ordering) : []; $order = false; if ((bool)($elements['ordering'] ?? false)) { diff --git a/system/src/Grav/Common/Flex/Types/Pages/Storage/PageStorage.php b/system/src/Grav/Common/Flex/Types/Pages/Storage/PageStorage.php index 577a0d7aa..a74d2f92f 100644 --- a/system/src/Grav/Common/Flex/Types/Pages/Storage/PageStorage.php +++ b/system/src/Grav/Common/Flex/Types/Pages/Storage/PageStorage.php @@ -394,14 +394,14 @@ class PageStorage extends FolderStorage if ($oldFolder !== $newFolder && file_exists($oldFolder)) { $isCopy = $row['__META']['copy'] ?? false; if ($isCopy) { - if (strpos($newFolder, $oldFolder . '/') === 0) { + if (str_starts_with($newFolder, $oldFolder . '/')) { throw new RuntimeException(sprintf('Page /%s cannot be copied to itself', $oldKey)); } $this->copyRow($oldKey, $newKey); $debugger->addMessage("Page copied: {$oldFolder} => {$newFolder}", 'debug'); } else { - if (strpos($newFolder, $oldFolder . '/') === 0) { + if (str_starts_with($newFolder, $oldFolder . '/')) { throw new RuntimeException(sprintf('Page /%s cannot be moved to itself', $oldKey)); } @@ -538,7 +538,7 @@ class PageStorage extends FolderStorage if ($reload || !isset($this->meta[$key])) { /** @var UniformResourceLocator $locator */ $locator = Grav::instance()['locator']; - if (mb_strpos($key, '@@') === false) { + if (mb_strpos((string) $key, '@@') === false) { $path = $this->getStoragePath($key); if (is_string($path)) { $path = $locator->isStream($path) ? $locator->findResource($path) : GRAV_ROOT . "/{$path}"; diff --git a/system/src/Grav/Common/Flex/Types/Pages/Traits/PageTranslateTrait.php b/system/src/Grav/Common/Flex/Types/Pages/Traits/PageTranslateTrait.php index d8d86b0b4..5e18cc4e0 100644 --- a/system/src/Grav/Common/Flex/Types/Pages/Traits/PageTranslateTrait.php +++ b/system/src/Grav/Common/Flex/Types/Pages/Traits/PageTranslateTrait.php @@ -92,9 +92,7 @@ trait PageTranslateTrait $list[$languageCode ?: $defaultCode] = $route ?? ''; } - $list = array_filter($list, static function ($var) { - return null !== $var; - }); + $list = array_filter($list, static fn($var) => null !== $var); // Hack to get the same result as with old pages. foreach ($list as &$path) { diff --git a/system/src/Grav/Common/Flex/Types/UserGroups/UserGroupObject.php b/system/src/Grav/Common/Flex/Types/UserGroups/UserGroupObject.php index 9e753d21b..bbffc8d01 100644 --- a/system/src/Grav/Common/Flex/Types/UserGroups/UserGroupObject.php +++ b/system/src/Grav/Common/Flex/Types/UserGroups/UserGroupObject.php @@ -100,10 +100,9 @@ class UserGroupObject extends FlexObject implements UserGroupInterface } /** - * @param mixed $value * @return array */ - protected function offsetLoad_access($value): array + protected function offsetLoad_access(mixed $value): array { if (!$value instanceof Access) { $value = new Access($value); @@ -115,10 +114,9 @@ class UserGroupObject extends FlexObject implements UserGroupInterface } /** - * @param mixed $value * @return array */ - protected function offsetPrepare_access($value): array + protected function offsetPrepare_access(mixed $value): array { return $this->offsetLoad_access($value); } diff --git a/system/src/Grav/Common/Flex/Types/Users/Traits/UserObjectLegacyTrait.php b/system/src/Grav/Common/Flex/Types/Users/Traits/UserObjectLegacyTrait.php index 5ce9fe4e0..2f634ab1d 100644 --- a/system/src/Grav/Common/Flex/Types/Users/Traits/UserObjectLegacyTrait.php +++ b/system/src/Grav/Common/Flex/Types/Users/Traits/UserObjectLegacyTrait.php @@ -30,7 +30,7 @@ trait UserObjectLegacyTrait */ public function merge(array $data) { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use ->update($data) method instead', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use ->update($data) method instead', E_USER_DEPRECATED); $this->setElements($this->getBlueprint()->mergeData($this->toArray(), $data)); @@ -45,7 +45,7 @@ trait UserObjectLegacyTrait */ public function getAvatarMedia() { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use ->getAvatarImage() method instead', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use ->getAvatarImage() method instead', E_USER_DEPRECATED); return $this->getAvatarImage(); } @@ -58,7 +58,7 @@ trait UserObjectLegacyTrait */ public function avatarUrl() { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use ->getAvatarUrl() method instead', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use ->getAvatarUrl() method instead', E_USER_DEPRECATED); return $this->getAvatarUrl(); } @@ -73,7 +73,7 @@ trait UserObjectLegacyTrait */ public function authorise($action) { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use ->authorize() method instead', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use ->authorize() method instead', E_USER_DEPRECATED); return $this->authorize($action) ?? false; } @@ -87,7 +87,7 @@ trait UserObjectLegacyTrait #[\ReturnTypeWillChange] public function count() { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6', E_USER_DEPRECATED); return count($this->jsonSerialize()); } diff --git a/system/src/Grav/Common/Flex/Types/Users/UserIndex.php b/system/src/Grav/Common/Flex/Types/Users/UserIndex.php index 74524106d..d97b74a38 100644 --- a/system/src/Grav/Common/Flex/Types/Users/UserIndex.php +++ b/system/src/Grav/Common/Flex/Types/Users/UserIndex.php @@ -67,7 +67,7 @@ class UserIndex extends FlexIndex implements UserCollectionInterface // Username can also be number and stored as such. $key = (string)($data['username'] ?? $meta['key'] ?? $meta['storage_key']); $meta['key'] = static::filterUsername($key, $storage); - $meta['email'] = isset($data['email']) ? mb_strtolower($data['email']) : null; + $meta['email'] = isset($data['email']) ? mb_strtolower((string) $data['email']) : null; } /** diff --git a/system/src/Grav/Common/Flex/Types/Users/UserObject.php b/system/src/Grav/Common/Flex/Types/Users/UserObject.php index 1a3eb3fa2..7f9759e70 100644 --- a/system/src/Grav/Common/Flex/Types/Users/UserObject.php +++ b/system/src/Grav/Common/Flex/Types/Users/UserObject.php @@ -286,7 +286,7 @@ class UserObject extends FlexObject implements UserInterface, Countable return false; } - if (strpos($action, 'login') === false && !$this->getProperty('authorized')) { + if (!str_contains($action, 'login') && !$this->getProperty('authorized')) { // User needs to be authorized (2FA). return false; } @@ -401,7 +401,7 @@ class UserObject extends FlexObject implements UserInterface, Countable */ public function join($name, $value, $separator = null) { - $separator = $separator ?? '.'; + $separator ??= '.'; $old = $this->get($name, null, $separator); if ($old !== null) { if (!is_array($old)) { @@ -1027,10 +1027,9 @@ class UserObject extends FlexObject implements UserInterface, Countable } /** - * @param mixed $value * @return array */ - protected function offsetLoad_access($value): array + protected function offsetLoad_access(mixed $value): array { if (!$value instanceof Access) { $value = new Access($value); @@ -1040,10 +1039,9 @@ class UserObject extends FlexObject implements UserInterface, Countable } /** - * @param mixed $value * @return array */ - protected function offsetPrepare_access($value): array + protected function offsetPrepare_access(mixed $value): array { return $this->offsetLoad_access($value); } diff --git a/system/src/Grav/Common/GPM/Common/Package.php b/system/src/Grav/Common/GPM/Common/Package.php index 2b359d166..401b22ef9 100644 --- a/system/src/Grav/Common/GPM/Common/Package.php +++ b/system/src/Grav/Common/GPM/Common/Package.php @@ -14,7 +14,7 @@ use Grav\Common\Data\Data; /** * @property string $name */ -class Package +class Package implements \Stringable { /** @var Data */ protected $data; @@ -53,11 +53,10 @@ class Package /** * @param string $key - * @param mixed $value * @return void */ #[\ReturnTypeWillChange] - public function __set($key, $value) + public function __set($key, mixed $value) { $this->data->set($key, $value); } @@ -76,7 +75,7 @@ class Package * @return string */ #[\ReturnTypeWillChange] - public function __toString() + public function __toString(): string { return $this->toJson(); } diff --git a/system/src/Grav/Common/GPM/GPM.php b/system/src/Grav/Common/GPM/GPM.php index 2f05a76e7..fd61ffe13 100644 --- a/system/src/Grav/Common/GPM/GPM.php +++ b/system/src/Grav/Common/GPM/GPM.php @@ -37,8 +37,6 @@ class GPM extends Iterator private $repository; /** @var Remote\GravCore|null Remove Grav Packages */ private $grav; - /** @var bool */ - private $refresh; /** @var callable|null */ private $callback; @@ -57,7 +55,7 @@ class GPM extends Iterator * @param bool $refresh Applies to Remote Packages only and forces a refetch of data * @param callable|null $callback Either a function or callback in array notation */ - public function __construct($refresh = false, $callback = null) + public function __construct(private $refresh = false, $callback = null) { parent::__construct(); @@ -65,7 +63,6 @@ class GPM extends Iterator $this->cache = []; $this->installed = new Local\Packages(); - $this->refresh = $refresh; $this->callback = $callback; } @@ -78,12 +75,10 @@ class GPM extends Iterator #[\ReturnTypeWillChange] public function __get($offset) { - switch ($offset) { - case 'grav': - return $this->getGrav(); - } - - return parent::__get($offset); + return match ($offset) { + 'grav' => $this->getGrav(), + default => parent::__get($offset), + }; } /** @@ -95,12 +90,10 @@ class GPM extends Iterator #[\ReturnTypeWillChange] public function __isset($offset) { - switch ($offset) { - case 'grav': - return $this->getGrav() !== null; - } - - return parent::__isset($offset); + return match ($offset) { + 'grav' => $this->getGrav() !== null, + default => parent::__isset($offset), + }; } /** @@ -550,7 +543,7 @@ class GPM extends Iterator if (null === $this->repository) { try { $this->repository = new Remote\Packages($this->refresh, $this->callback); - } catch (Exception $e) {} + } catch (Exception) {} } return $this->repository; @@ -566,7 +559,7 @@ class GPM extends Iterator if (null === $this->grav) { try { $this->grav = new Remote\GravCore($this->refresh, $this->callback); - } catch (Exception $e) {} + } catch (Exception) {} } return $this->grav; @@ -1220,7 +1213,7 @@ class GPM extends Iterator */ public function versionFormatIsNextSignificantRelease($version): bool { - return strpos($version, '~') === 0; + return str_starts_with($version, '~'); } /** @@ -1233,7 +1226,7 @@ class GPM extends Iterator */ public function versionFormatIsEqualOrHigher($version): bool { - return strpos($version, '>=') === 0; + return str_starts_with($version, '>='); } /** diff --git a/system/src/Grav/Common/GPM/Installer.php b/system/src/Grav/Common/GPM/Installer.php index 2987e4a27..de0697835 100644 --- a/system/src/Grav/Common/GPM/Installer.php +++ b/system/src/Grav/Common/GPM/Installer.php @@ -81,7 +81,7 @@ class Installer { $destination = rtrim($destination, DS); $options = array_merge(self::$options, $options); - $install_path = rtrim($destination . DS . ltrim($options['install_path'], DS), DS); + $install_path = rtrim($destination . DS . ltrim((string) $options['install_path'], DS), DS); if (!self::isGravInstance($destination) || !self::isValidDestination( $install_path, diff --git a/system/src/Grav/Common/GPM/Local/Package.php b/system/src/Grav/Common/GPM/Local/Package.php index 53b249ae8..72b07b332 100644 --- a/system/src/Grav/Common/GPM/Local/Package.php +++ b/system/src/Grav/Common/GPM/Local/Package.php @@ -37,7 +37,7 @@ class Package extends BasePackage $html_description = Parsedown::instance()->line($this->__get('description')); $this->data->set('slug', $package->__get('slug')); $this->data->set('description_html', $html_description); - $this->data->set('description_plain', strip_tags($html_description)); + $this->data->set('description_plain', strip_tags((string) $html_description)); $this->data->set('symlink', is_link(USER_DIR . $package_type . DS . $this->__get('slug'))); } diff --git a/system/src/Grav/Common/GPM/Remote/AbstractPackageCollection.php b/system/src/Grav/Common/GPM/Remote/AbstractPackageCollection.php index c08108af9..bcbafe4c6 100644 --- a/system/src/Grav/Common/GPM/Remote/AbstractPackageCollection.php +++ b/system/src/Grav/Common/GPM/Remote/AbstractPackageCollection.php @@ -53,10 +53,10 @@ class AbstractPackageCollection extends BaseCollection $this->raw = $this->cache->fetch(md5($this->repository)); $this->fetch($refresh, $callback); - foreach (json_decode($this->raw, true) as $slug => $data) { + foreach (json_decode((string) $this->raw, true) as $slug => $data) { // Temporarily fix for using multi-sites if (isset($data['install_path'])) { - $path = preg_replace('~^user/~i', 'user://', $data['install_path']); + $path = preg_replace('~^user/~i', 'user://', (string) $data['install_path']); $data['install_path'] = Grav::instance()['locator']->findResource($path, false, true); } $this->items[$slug] = new Package($data, $this->type); diff --git a/system/src/Grav/Common/GPM/Remote/GravCore.php b/system/src/Grav/Common/GPM/Remote/GravCore.php index d97eb834f..c3a3c9bdc 100644 --- a/system/src/Grav/Common/GPM/Remote/GravCore.php +++ b/system/src/Grav/Common/GPM/Remote/GravCore.php @@ -46,7 +46,7 @@ class GravCore extends AbstractPackageCollection $this->fetch($refresh, $callback); - $this->data = json_decode($this->raw, true); + $this->data = json_decode((string) $this->raw, true); $this->version = $this->data['version'] ?? '-'; $this->date = $this->data['date'] ?? '-'; $this->min_php = $this->data['min_php'] ?? null; diff --git a/system/src/Grav/Common/Getters.php b/system/src/Grav/Common/Getters.php index aca39bc07..3ddb1020e 100644 --- a/system/src/Grav/Common/Getters.php +++ b/system/src/Grav/Common/Getters.php @@ -29,7 +29,7 @@ abstract class Getters implements ArrayAccess, Countable * @param mixed $value Medium value */ #[\ReturnTypeWillChange] - public function __set($offset, $value) + public function __set($offset, mixed $value) { $this->offsetSet($offset, $value); } @@ -103,10 +103,9 @@ abstract class Getters implements ArrayAccess, Countable /** * @param int|string $offset - * @param mixed $value */ #[\ReturnTypeWillChange] - public function offsetSet($offset, $value) + public function offsetSet($offset, mixed $value) { if ($this->gettersVariable) { $var = $this->gettersVariable; diff --git a/system/src/Grav/Common/Grav.php b/system/src/Grav/Common/Grav.php index f9c9b00fb..e170c9362 100644 --- a/system/src/Grav/Common/Grav.php +++ b/system/src/Grav/Common/Grav.php @@ -261,51 +261,23 @@ class Grav extends Container $container = new Container( [ - 'multipartRequestSupport' => function () { - return new MultipartRequestSupport(); - }, - 'initializeProcessor' => function () { - return new InitializeProcessor($this); - }, - 'backupsProcessor' => function () { - return new BackupsProcessor($this); - }, - 'pluginsProcessor' => function () { - return new PluginsProcessor($this); - }, - 'themesProcessor' => function () { - return new ThemesProcessor($this); - }, - 'schedulerProcessor' => function () { - return new SchedulerProcessor($this); - }, - 'requestProcessor' => function () { - return new RequestProcessor($this); - }, - 'tasksProcessor' => function () { - return new TasksProcessor($this); - }, - 'assetsProcessor' => function () { - return new AssetsProcessor($this); - }, - 'twigProcessor' => function () { - return new TwigProcessor($this); - }, - 'pagesProcessor' => function () { - return new PagesProcessor($this); - }, - 'debuggerAssetsProcessor' => function () { - return new DebuggerAssetsProcessor($this); - }, - 'renderProcessor' => function () { - return new RenderProcessor($this); - }, + 'multipartRequestSupport' => fn() => new MultipartRequestSupport(), + 'initializeProcessor' => fn() => new InitializeProcessor($this), + 'backupsProcessor' => fn() => new BackupsProcessor($this), + 'pluginsProcessor' => fn() => new PluginsProcessor($this), + 'themesProcessor' => fn() => new ThemesProcessor($this), + 'schedulerProcessor' => fn() => new SchedulerProcessor($this), + 'requestProcessor' => fn() => new RequestProcessor($this), + 'tasksProcessor' => fn() => new TasksProcessor($this), + 'assetsProcessor' => fn() => new AssetsProcessor($this), + 'twigProcessor' => fn() => new TwigProcessor($this), + 'pagesProcessor' => fn() => new PagesProcessor($this), + 'debuggerAssetsProcessor' => fn() => new DebuggerAssetsProcessor($this), + 'renderProcessor' => fn() => new RenderProcessor($this), ] ); - $default = static function () { - return new Response(404, ['Expires' => 0, 'Cache-Control' => 'no-store, max-age=0'], 'Not Found'); - }; + $default = static fn() => new Response(404, ['Expires' => 0, 'Cache-Control' => 'no-store, max-age=0'], 'Not Found'); $collection = new RequestHandler($this->middleware, $default, $container); @@ -326,7 +298,7 @@ class Grav extends Container $etag = md5($body); $response = $response->withHeader('ETag', '"' . $etag . '"'); - $search = trim($this['request']->getHeaderLine('If-None-Match'), '"'); + $search = trim((string) $this['request']->getHeaderLine('If-None-Match'), '"'); if ($noCache === false && $search === $etag) { $response = $response->withStatus(304); $body = ''; @@ -403,7 +375,7 @@ class Grav extends Container $etag = md5($body); $response = $response->withHeader('ETag', '"' . $etag . '"'); - $search = trim($this['request']->getHeaderLine('If-None-Match'), '"'); + $search = trim((string) $this['request']->getHeaderLine('If-None-Match'), '"'); if ($noCache === false && $search === $etag) { $response = $response->withStatus(304); $body = ''; @@ -461,7 +433,7 @@ class Grav extends Container if (null === $code) { // Check for redirect code in the route: e.g. /new/[301], /new[301]/route or /new[301].html $regex = '/.*(\[(30[1-7])\])(.\w+|\/.*?)?$/'; - preg_match($regex, $route, $matches); + preg_match($regex, (string) $route, $matches); if ($matches) { $route = str_replace($matches[1], '', $matches[0]); $code = $matches[2]; @@ -474,9 +446,9 @@ class Grav extends Container $url = rtrim($uri->rootUrl(), '/') . '/'; if ($this['config']->get('system.pages.redirect_trailing_slash', true)) { - $url .= trim($route, '/'); // Remove trailing slash + $url .= trim((string) $route, '/'); // Remove trailing slash } else { - $url .= ltrim($route, '/'); // Support trailing slash default routes + $url .= ltrim((string) $route, '/'); // Support trailing slash default routes } } } elseif ($route instanceof Route) { @@ -533,7 +505,7 @@ class Grav extends Container header("HTTP/{$response->getProtocolVersion()} {$response->getStatusCode()} {$response->getReasonPhrase()}"); foreach ($response->getHeaders() as $key => $values) { // Skip internal Grav headers. - if (strpos($key, 'Grav-Internal-') === 0) { + if (str_starts_with($key, 'Grav-Internal-')) { continue; } foreach ($values as $i => $value) { @@ -552,7 +524,7 @@ class Grav extends Container // Initialize Locale if set and configured. if ($this['language']->enabled() && $this['config']->get('system.languages.override_locale')) { $language = $this['language']->getLanguage(); - setlocale(LC_ALL, strlen($language) < 3 ? ($language . '_' . strtoupper($language)) : $language); + setlocale(LC_ALL, strlen((string) $language) < 3 ? ($language . '_' . strtoupper((string) $language)) : $language); } elseif ($this['config']->get('system.default_locale')) { setlocale(LC_ALL, $this['config']->get('system.default_locale')); } @@ -566,7 +538,7 @@ class Grav extends Container { /** @var EventDispatcherInterface $events */ $events = $this['events']; - $eventName = get_class($event); + $eventName = $event::class; $timestamp = microtime(true); $event = $events->dispatch($event); @@ -734,9 +706,7 @@ class Grav extends Container if (is_int($serviceKey)) { $this->register(new $serviceClass); } else { - $this[$serviceKey] = function ($c) use ($serviceClass) { - return new $serviceClass($c); - }; + $this[$serviceKey] = fn($c) => new $serviceClass($c); } } } @@ -799,7 +769,7 @@ class Grav extends Container $medium = $media[$media_file]; foreach ($uri->query(null, true) as $action => $params) { if (in_array($action, ImageMedium::$magic_actions, true)) { - call_user_func_array([&$medium, $action], explode(',', $params)); + call_user_func_array([&$medium, $action], explode(',', (string) $params)); } } Utils::download($medium->path(), false); @@ -816,7 +786,7 @@ class Grav extends Container if ($extension) { $download = true; - if (in_array(ltrim($extension, '.'), $config->get('system.media.unsupported_inline_types', []), true)) { + if (in_array(ltrim((string) $extension, '.'), $config->get('system.media.unsupported_inline_types', []), true)) { $download = false; } Utils::download($page->path() . DIRECTORY_SEPARATOR . $uri->basename(), $download); diff --git a/system/src/Grav/Common/HTTP/Client.php b/system/src/Grav/Common/HTTP/Client.php index 4c9a79616..dce738e24 100644 --- a/system/src/Grav/Common/HTTP/Client.php +++ b/system/src/Grav/Common/HTTP/Client.php @@ -33,7 +33,7 @@ class Client // Use callback if provided if ($callback) { self::$callback = $callback; - $options->setOnProgress([Client::class, 'progress']); + $options->setOnProgress(Client::progress(...)); } $settings = array_merge($options->toArray(), $overrides); @@ -43,17 +43,11 @@ class Client $preferred_method = $config->get('system.gpm.method', 'auto'); } - switch ($preferred_method) { - case 'curl': - $client = new CurlHttpClient($settings, $connections); - break; - case 'fopen': - case 'native': - $client = new NativeHttpClient($settings, $connections); - break; - default: - $client = HttpClient::create($settings, $connections); - } + $client = match ($preferred_method) { + 'curl' => new CurlHttpClient($settings, $connections), + 'fopen', 'native' => new NativeHttpClient($settings, $connections), + default => HttpClient::create($settings, $connections), + }; return $client; } diff --git a/system/src/Grav/Common/HTTP/Response.php b/system/src/Grav/Common/HTTP/Response.php index ca3a6efba..2d42d7c18 100644 --- a/system/src/Grav/Common/HTTP/Response.php +++ b/system/src/Grav/Common/HTTP/Response.php @@ -73,7 +73,7 @@ class Response if (Utils::functionExists('set_time_limit')) { @set_time_limit(0); } - } catch (Exception $e) {} + } catch (Exception) {} $client = Client::getClient($overrides, 6, $callback); diff --git a/system/src/Grav/Common/Helpers/Truncator.php b/system/src/Grav/Common/Helpers/Truncator.php index d09c52cbf..c854a7edd 100644 --- a/system/src/Grav/Common/Helpers/Truncator.php +++ b/system/src/Grav/Common/Helpers/Truncator.php @@ -62,7 +62,7 @@ class Truncator $curNode->nodeValue = substr( $curNode->nodeValue, 0, - $words[$offset][1] + strlen($words[$offset][0]) + $words[$offset][1] + strlen((string) $words[$offset][0]) ); self::removeProceedingNodes($curNode, $container); @@ -216,7 +216,7 @@ class Truncator */ private static function insertEllipsis($domNode, $ellipsis) { - $avoid = array('a', 'strong', 'em', 'h1', 'h2', 'h3', 'h4', 'h5'); //html tags to avoid appending the ellipsis to + $avoid = ['a', 'strong', 'em', 'h1', 'h2', 'h3', 'h4', 'h5']; //html tags to avoid appending the ellipsis to if ($domNode->parentNode->parentNode !== null && in_array($domNode->parentNode->nodeName, $avoid, true)) { // Append as text node to parent instead @@ -252,7 +252,7 @@ class Truncator ) { if ($considerHtml) { // if the plain text is shorter than the maximum length, return the whole text - if (strlen(preg_replace('/<.*?>/', '', $text)) <= $length) { + if (strlen((string) preg_replace('/<.*?>/', '', $text)) <= $length) { return $text; } @@ -284,7 +284,7 @@ class Truncator $truncate .= $line_matchings[1]; } // calculate the length of the plain text part of the line; handle entities as one character - $content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2])); + $content_length = strlen((string) preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2])); if ($total_length+$content_length> $length) { // the number of characters which are left $left = $length - $total_length; diff --git a/system/src/Grav/Common/Inflector.php b/system/src/Grav/Common/Inflector.php index 284b8dd46..cde645e3f 100644 --- a/system/src/Grav/Common/Inflector.php +++ b/system/src/Grav/Common/Inflector.php @@ -72,7 +72,7 @@ class Inflector if (is_array(static::$uncountable)) { foreach (static::$uncountable as $_uncountable) { - if (substr($lowercased_word, -1 * strlen($_uncountable)) === $_uncountable) { + if (substr($lowercased_word, -1 * strlen((string) $_uncountable)) === $_uncountable) { return $word; } } @@ -81,7 +81,7 @@ class Inflector if (is_array(static::$irregular)) { foreach (static::$irregular as $_plural => $_singular) { if (preg_match('/(' . $_plural . ')$/i', $word, $arr)) { - return preg_replace('/(' . $_plural . ')$/i', substr($arr[0], 0, 1) . substr($_singular, 1), $word); + return preg_replace('/(' . $_plural . ')$/i', substr($arr[0], 0, 1) . substr((string) $_singular, 1), $word); } } } @@ -89,7 +89,7 @@ class Inflector if (is_array(static::$plural)) { foreach (static::$plural as $rule => $replacement) { if (preg_match($rule, $word)) { - return preg_replace($rule, $replacement, $word); + return preg_replace($rule, (string) $replacement, $word); } } } @@ -117,7 +117,7 @@ class Inflector if (is_array(static::$uncountable)) { foreach (static::$uncountable as $_uncountable) { - if (substr($lowercased_word, -1 * strlen($_uncountable)) === $_uncountable) { + if (substr($lowercased_word, -1 * strlen((string) $_uncountable)) === $_uncountable) { return $word; } } @@ -134,7 +134,7 @@ class Inflector if (is_array(static::$singular)) { foreach (static::$singular as $rule => $replacement) { if (preg_match($rule, $word)) { - return preg_replace($rule, $replacement, $word); + return preg_replace($rule, (string) $replacement, $word); } } } @@ -186,7 +186,7 @@ class Inflector */ public static function camelize($word) { - return str_replace(' ', '', ucwords(preg_replace('/[^\p{L}^0-9]+/', ' ', $word))); + return str_replace(' ', '', ucwords((string) preg_replace('/[^\p{L}^0-9]+/', ' ', $word))); } /** @@ -203,10 +203,10 @@ class Inflector public static function underscorize($word) { $regex1 = preg_replace('/([A-Z]+)([A-Z][a-z])/', '\1_\2', $word); - $regex2 = preg_replace('/([a-zd])([A-Z])/', '\1_\2', $regex1); - $regex3 = preg_replace('/[^\p{L}^0-9]+/u', '_', $regex2); + $regex2 = preg_replace('/([a-zd])([A-Z])/', '\1_\2', (string) $regex1); + $regex3 = preg_replace('/[^\p{L}^0-9]+/u', '_', (string) $regex2); - return strtolower($regex3); + return strtolower((string) $regex3); } /** @@ -223,11 +223,11 @@ class Inflector public static function hyphenize($word) { $regex1 = preg_replace('/([A-Z]+)([A-Z][a-z])/', '\1-\2', $word); - $regex2 = preg_replace('/([a-z])([A-Z])/', '\1-\2', $regex1); - $regex3 = preg_replace('/([0-9])([A-Z])/', '\1-\2', $regex2); - $regex4 = preg_replace('/[^\p{L}^0-9]+/', '-', $regex3); + $regex2 = preg_replace('/([a-z])([A-Z])/', '\1-\2', (string) $regex1); + $regex3 = preg_replace('/([0-9])([A-Z])/', '\1-\2', (string) $regex2); + $regex4 = preg_replace('/[^\p{L}^0-9]+/', '-', (string) $regex3); - $regex4 = trim($regex4, '-'); + $regex4 = trim((string) $regex4, '-'); return strtolower($regex4); } @@ -326,16 +326,12 @@ class Inflector return $number . static::$ordinals['default']; } - switch ($number % 10) { - case 1: - return $number . static::$ordinals['first']; - case 2: - return $number . static::$ordinals['second']; - case 3: - return $number . static::$ordinals['third']; - default: - return $number . static::$ordinals['default']; - } + return match ($number % 10) { + 1 => $number . static::$ordinals['first'], + 2 => $number . static::$ordinals['second'], + 3 => $number . static::$ordinals['third'], + default => $number . static::$ordinals['default'], + }; } /** diff --git a/system/src/Grav/Common/Iterator.php b/system/src/Grav/Common/Iterator.php index 51ed5d185..5c18fc253 100644 --- a/system/src/Grav/Common/Iterator.php +++ b/system/src/Grav/Common/Iterator.php @@ -24,7 +24,7 @@ use function is_object; * Class Iterator * @package Grav\Common */ -class Iterator implements \ArrayAccess, \Iterator, \Countable, \Serializable +class Iterator implements \ArrayAccess, \Iterator, \Countable, \Serializable, \Stringable { use Constructor, ArrayAccessWithGetters, ArrayIterator, Countable, Serializable, Export; @@ -35,11 +35,10 @@ class Iterator implements \ArrayAccess, \Iterator, \Countable, \Serializable * Convert function calls for the existing keys into their values. * * @param string $key - * @param mixed $args * @return mixed */ #[\ReturnTypeWillChange] - public function __call($key, $args) + public function __call($key, mixed $args) { return $this->items[$key] ?? null; } @@ -63,7 +62,7 @@ class Iterator implements \ArrayAccess, \Iterator, \Countable, \Serializable * @return string */ #[\ReturnTypeWillChange] - public function __toString() + public function __toString(): string { return implode(',', $this->items); } @@ -143,7 +142,7 @@ class Iterator implements \ArrayAccess, \Iterator, \Countable, \Serializable * * @return string|int|false Key if found, otherwise false. */ - public function indexOf($needle) + public function indexOf(mixed $needle) { foreach (array_values($this->items) as $key => $value) { if ($value === $needle) { diff --git a/system/src/Grav/Common/Language/Language.php b/system/src/Grav/Common/Language/Language.php index 0e6096c69..baf0b8a77 100644 --- a/system/src/Grav/Common/Language/Language.php +++ b/system/src/Grav/Common/Language/Language.php @@ -149,9 +149,7 @@ class Language { $languagesArray = $this->languages; //Make local copy - $languagesArray = array_map(static function ($value) use ($delimiter) { - return preg_quote($value, $delimiter); - }, $languagesArray); + $languagesArray = array_map(static fn($value) => preg_quote((string) $value, $delimiter), $languagesArray); sort($languagesArray); @@ -593,7 +591,7 @@ class Language */ public function getBrowserLanguages($accept_langs = []) { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, no longer used', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, no longer used', E_USER_DEPRECATED); if (empty($this->http_accept_language)) { if (empty($accept_langs) && isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { @@ -604,7 +602,7 @@ class Language $langs = []; - foreach (explode(',', $accept_langs) as $k => $pref) { + foreach (explode(',', (string) $accept_langs) as $k => $pref) { // split $pref again by ';q=' // and decorate the language entries by inverted position if (false !== ($i = strpos($pref, ';q='))) { diff --git a/system/src/Grav/Common/Markdown/Parsedown.php b/system/src/Grav/Common/Markdown/Parsedown.php index bd2ab9039..85db41666 100644 --- a/system/src/Grav/Common/Markdown/Parsedown.php +++ b/system/src/Grav/Common/Markdown/Parsedown.php @@ -35,7 +35,7 @@ class Parsedown extends \Parsedown $defaults = ['markdown' => $defaults]; } $excerpts = new Excerpts($excerpts, $defaults); - user_error(__CLASS__ . '::' . __FUNCTION__ . '($page, $defaults) is deprecated since Grav 1.6.10, use new ' . __CLASS__ . '(new ' . Excerpts::class . '($page, [\'markdown\' => $defaults])) instead.', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '($page, $defaults) is deprecated since Grav 1.6.10, use new ' . self::class . '(new ' . Excerpts::class . '($page, [\'markdown\' => $defaults])) instead.', E_USER_DEPRECATED); } $this->init($excerpts, $defaults); diff --git a/system/src/Grav/Common/Markdown/ParsedownExtra.php b/system/src/Grav/Common/Markdown/ParsedownExtra.php index 3ec808001..616b84bd6 100644 --- a/system/src/Grav/Common/Markdown/ParsedownExtra.php +++ b/system/src/Grav/Common/Markdown/ParsedownExtra.php @@ -36,7 +36,7 @@ class ParsedownExtra extends \ParsedownExtra $defaults = ['markdown' => $defaults]; } $excerpts = new Excerpts($excerpts, $defaults); - user_error(__CLASS__ . '::' . __FUNCTION__ . '($page, $defaults) is deprecated since Grav 1.6.10, use new ' . __CLASS__ . '(new ' . Excerpts::class . '($page, [\'markdown\' => $defaults])) instead.', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '($page, $defaults) is deprecated since Grav 1.6.10, use new ' . self::class . '(new ' . Excerpts::class . '($page, [\'markdown\' => $defaults])) instead.', E_USER_DEPRECATED); } parent::__construct(); diff --git a/system/src/Grav/Common/Markdown/ParsedownGravTrait.php b/system/src/Grav/Common/Markdown/ParsedownGravTrait.php index 3a6ceb498..adb0a0fdc 100644 --- a/system/src/Grav/Common/Markdown/ParsedownGravTrait.php +++ b/system/src/Grav/Common/Markdown/ParsedownGravTrait.php @@ -49,7 +49,7 @@ trait ParsedownGravTrait $defaults = ['markdown' => $defaults]; } $this->excerpts = new Excerpts($excerpts, $defaults); - user_error(__CLASS__ . '::' . __FUNCTION__ . '($page, $defaults) is deprecated since Grav 1.6.10, use ->init(new ' . Excerpts::class . '($page, [\'markdown\' => $defaults])) instead.', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '($page, $defaults) is deprecated since Grav 1.6.10, use ->init(new ' . Excerpts::class . '($page, [\'markdown\' => $defaults])) instead.', E_USER_DEPRECATED); } else { $this->excerpts = $excerpts; } @@ -133,7 +133,7 @@ trait ParsedownGravTrait array_splice($this->InlineTypes[$type], $index, 0, [$tag]); } - if (strpos($this->inlineMarkerList, $type) === false) { + if (!str_contains($this->inlineMarkerList, $type)) { $this->inlineMarkerList .= $type; } } @@ -199,7 +199,7 @@ trait ParsedownGravTrait */ protected function blockTwigTag($line) { - if (preg_match('/(?:{{|{%|{#)(.*)(?:}}|%}|#})/', $line['body'], $matches)) { + if (preg_match('/(?:{{|{%|{#)(.*)(?:}}|%}|#})/', (string) $line['body'], $matches)) { return ['markup' => $line['body']]; } @@ -212,7 +212,7 @@ trait ParsedownGravTrait */ protected function inlineSpecialCharacter($excerpt) { - if ($excerpt['text'][0] === '&' && !preg_match('/^&#?\w+;/', $excerpt['text'])) { + if ($excerpt['text'][0] === '&' && !preg_match('/^&#?\w+;/', (string) $excerpt['text'])) { return [ 'markup' => '&', 'extent' => 1, @@ -235,7 +235,7 @@ trait ParsedownGravTrait */ protected function inlineImage($excerpt) { - if (preg_match($this->twig_link_regex, $excerpt['text'], $matches)) { + if (preg_match($this->twig_link_regex, (string) $excerpt['text'], $matches)) { $excerpt['text'] = str_replace($matches[1], '/', $excerpt['text']); $excerpt = parent::inlineImage($excerpt); $excerpt['element']['attributes']['src'] = $matches[1]; @@ -264,7 +264,7 @@ trait ParsedownGravTrait $type = $excerpt['type'] ?? 'link'; // do some trickery to get around Parsedown requirement for valid URL if its Twig in there - if (preg_match($this->twig_link_regex, $excerpt['text'], $matches)) { + if (preg_match($this->twig_link_regex, (string) $excerpt['text'], $matches)) { $excerpt['text'] = str_replace($matches[1], '/', $excerpt['text']); $excerpt = parent::inlineLink($excerpt); $excerpt['element']['attributes']['href'] = $matches[1]; diff --git a/system/src/Grav/Common/Media/Interfaces/MediaObjectInterface.php b/system/src/Grav/Common/Media/Interfaces/MediaObjectInterface.php index e967702a5..613be5bc1 100644 --- a/system/src/Grav/Common/Media/Interfaces/MediaObjectInterface.php +++ b/system/src/Grav/Common/Media/Interfaces/MediaObjectInterface.php @@ -207,11 +207,10 @@ interface MediaObjectInterface extends \Grav\Framework\Media\Interfaces\MediaObj * Allow any action to be called on this medium from twig or markdown * * @param string $method - * @param mixed $args * @return $this */ #[\ReturnTypeWillChange] - public function __call($method, $args); + public function __call($method, mixed $args); /** * Set value by using dot notation for nested arrays/objects. @@ -223,5 +222,5 @@ interface MediaObjectInterface extends \Grav\Framework\Media\Interfaces\MediaObj * @param string|null $separator Separator, defaults to '.' * @return $this */ - public function set($name, $value, $separator = null); + public function set($name, mixed $value, $separator = null); } diff --git a/system/src/Grav/Common/Media/Traits/ImageMediaTrait.php b/system/src/Grav/Common/Media/Traits/ImageMediaTrait.php index 83b2d268a..fb7bff76b 100644 --- a/system/src/Grav/Common/Media/Traits/ImageMediaTrait.php +++ b/system/src/Grav/Common/Media/Traits/ImageMediaTrait.php @@ -97,7 +97,7 @@ trait ImageMediaTrait } $basename = $this->get('basename'); - if (preg_match('/[a-z0-9]{40}-(.*)/', $basename, $matches)) { + if (preg_match('/[a-z0-9]{40}-(.*)/', (string) $basename, $matches)) { $basename = $matches[1]; } return $basename; diff --git a/system/src/Grav/Common/Media/Traits/MediaFileTrait.php b/system/src/Grav/Common/Media/Traits/MediaFileTrait.php index 9e3f8704b..04ed9f794 100644 --- a/system/src/Grav/Common/Media/Traits/MediaFileTrait.php +++ b/system/src/Grav/Common/Media/Traits/MediaFileTrait.php @@ -88,7 +88,7 @@ trait MediaFileTrait } $path = $this->path(false); - $output = preg_replace('|^' . preg_quote(GRAV_ROOT, '|') . '|', '', $path) ?: $path; + $output = preg_replace('|^' . preg_quote(GRAV_ROOT, '|') . '|', '', (string) $path) ?: $path; /** @var UniformResourceLocator $locator */ $locator = $this->getGrav()['locator']; diff --git a/system/src/Grav/Common/Media/Traits/MediaObjectTrait.php b/system/src/Grav/Common/Media/Traits/MediaObjectTrait.php index f872dd1aa..7fda705cf 100644 --- a/system/src/Grav/Common/Media/Traits/MediaObjectTrait.php +++ b/system/src/Grav/Common/Media/Traits/MediaObjectTrait.php @@ -182,7 +182,7 @@ trait MediaObjectTrait // join the strings $querystring = implode('&', $this->medium_querystring); // explode all strings - $query_parts = explode('&', $querystring); + $query_parts = explode('&', (string) $querystring); // Join them again now ensure the elements are unique $querystring = implode('&', array_unique($query_parts)); @@ -598,7 +598,7 @@ trait MediaObjectTrait * @param string|null $separator Separator, defaults to '.' * @return mixed Value. */ - abstract public function get($name, $default = null, $separator = null); + abstract public function get($name, mixed $default = null, $separator = null); /** * Set value by using dot notation for nested arrays/objects. @@ -610,7 +610,7 @@ trait MediaObjectTrait * @param string|null $separator Separator, defaults to '.' * @return $this */ - abstract public function set($name, $value, $separator = null); + abstract public function set($name, mixed $value, $separator = null); /** * @param string $thumb diff --git a/system/src/Grav/Common/Media/Traits/MediaTrait.php b/system/src/Grav/Common/Media/Traits/MediaTrait.php index 93c4fdbcb..61f6f53b5 100644 --- a/system/src/Grav/Common/Media/Traits/MediaTrait.php +++ b/system/src/Grav/Common/Media/Traits/MediaTrait.php @@ -57,15 +57,15 @@ trait MediaTrait return null; } - if (strpos($folder, '://')) { + if (strpos((string) $folder, '://')) { return $folder; } /** @var UniformResourceLocator $locator */ $locator = Grav::instance()['locator']; $user = $locator->findResource('user://'); - if (strpos($folder, $user) === 0) { - return 'user://' . substr($folder, strlen($user)+1); + if (str_starts_with((string) $folder, $user)) { + return 'user://' . substr((string) $folder, strlen($user)+1); } return null; diff --git a/system/src/Grav/Common/Media/Traits/MediaUploadTrait.php b/system/src/Grav/Common/Media/Traits/MediaUploadTrait.php index 45d5208af..281bc373f 100644 --- a/system/src/Grav/Common/Media/Traits/MediaUploadTrait.php +++ b/system/src/Grav/Common/Media/Traits/MediaUploadTrait.php @@ -206,11 +206,11 @@ trait MediaUploadTrait break; } - $isMime = strstr($type, '/'); + $isMime = strstr((string) $type, '/'); $find = str_replace(['.', '*', '+'], ['\.', '.*', '\+'], $type); if ($isMime) { - $match = preg_match('#' . $find . '$#', $mime); + $match = preg_match('#' . $find . '$#', (string) $mime); if (!$match) { // TODO: translate $errors[] = 'The MIME type "' . $mime . '" for the file "' . $filepath . '" is not an accepted.'; @@ -219,7 +219,7 @@ trait MediaUploadTrait break; } } else { - $match = preg_match('#' . $find . '$#', $filename); + $match = preg_match('#' . $find . '$#', (string) $filename); if (!$match) { // TODO: translate $errors[] = 'The File Extension for the file "' . $filepath . '" is not an accepted.'; @@ -286,7 +286,7 @@ trait MediaUploadTrait if ($uploadedFile->getError() === \UPLOAD_ERR_OK) { // Move uploaded file. $this->doMoveUploadedFile($uploadedFile, $filename, $path); - } elseif (strpos($filename, 'original/') === 0 && !$this->fileExists($filename, $path) && $this->fileExists($basename, $path)) { + } elseif (str_starts_with($filename, 'original/') && !$this->fileExists($filename, $path) && $this->fileExists($basename, $path)) { // Original image support: override original image if it's the same as the uploaded image. $this->doCopy($basename, $filename, $path); } @@ -558,7 +558,7 @@ trait MediaUploadTrait $fileParts = (array)$filesystem->pathinfo($filename); foreach ($dir as $file) { - $preg_name = preg_quote($fileParts['filename'], '`'); + $preg_name = preg_quote((string) $fileParts['filename'], '`'); $preg_ext = preg_quote($fileParts['extension'] ?? '.', '`'); $preg_filename = preg_quote($basename, '`'); diff --git a/system/src/Grav/Common/Media/Traits/ThumbnailMediaTrait.php b/system/src/Grav/Common/Media/Traits/ThumbnailMediaTrait.php index e0c5d813d..59b4b51dc 100644 --- a/system/src/Grav/Common/Media/Traits/ThumbnailMediaTrait.php +++ b/system/src/Grav/Common/Media/Traits/ThumbnailMediaTrait.php @@ -138,7 +138,7 @@ trait ThumbnailMediaTrait $closure = [$parent, $method]; if (!is_callable($closure)) { - throw new BadMethodCallException(get_class($parent) . '::' . $method . '() not found.'); + throw new BadMethodCallException($parent::class . '::' . $method . '() not found.'); } return $closure(...$arguments); diff --git a/system/src/Grav/Common/Page/Collection.php b/system/src/Grav/Common/Page/Collection.php index 90d3346fd..041fb6055 100644 --- a/system/src/Grav/Common/Page/Collection.php +++ b/system/src/Grav/Common/Page/Collection.php @@ -139,9 +139,7 @@ class Collection extends Iterator implements PageCollectionInterface $array1 = $this->items; $array2 = $collection->toArray(); - $this->items = array_uintersect($array1, $array2, function ($val1, $val2) { - return strcmp($val1['slug'], $val2['slug']); - }); + $this->items = array_uintersect($array1, $array2, fn($val1, $val2) => strcmp((string) $val1['slug'], (string) $val2['slug'])); return $this; } @@ -357,7 +355,7 @@ class Collection extends Iterator implements PageCollectionInterface continue; } - $date = $field ? strtotime($page->value($field)) : $page->date(); + $date = $field ? strtotime((string) $page->value($field)) : $page->date(); if ((!$start || $date >= $start) && (!$end || $date <= $end)) { $date_range[$path] = $slug; diff --git a/system/src/Grav/Common/Page/Interfaces/PageLegacyInterface.php b/system/src/Grav/Common/Page/Interfaces/PageLegacyInterface.php index 0d38c7d3a..c58fb6c26 100644 --- a/system/src/Grav/Common/Page/Interfaces/PageLegacyInterface.php +++ b/system/src/Grav/Common/Page/Interfaces/PageLegacyInterface.php @@ -43,9 +43,8 @@ interface PageLegacyInterface * Modify a header value directly * * @param string $key - * @param mixed $value */ - public function modifyHeader($key, $value); + public function modifyHeader($key, mixed $value); /** * @return int @@ -68,9 +67,8 @@ interface PageLegacyInterface * Add an entry to the page's contentMeta array * * @param string $name - * @param mixed $value */ - public function addContentMeta($name, $value); + public function addContentMeta($name, mixed $value); /** * Return the whole contentMeta array as it currently stands diff --git a/system/src/Grav/Common/Page/Markdown/Excerpts.php b/system/src/Grav/Common/Page/Markdown/Excerpts.php index 406b4a479..367561505 100644 --- a/system/src/Grav/Common/Page/Markdown/Excerpts.php +++ b/system/src/Grav/Common/Page/Markdown/Excerpts.php @@ -49,7 +49,7 @@ class Excerpts // Add defaults to the configuration. if (null === $config || !isset($config['markdown'], $config['images'])) { $c = Grav::instance()['config']; - $config = $config ?? []; + $config ??= []; $config += [ 'markdown' => $c->get('system.pages.markdown', []), 'images' => $c->get('system.images', []) @@ -96,13 +96,13 @@ class Excerpts public function processLinkExcerpt(array $excerpt, string $type = 'link'): array { $grav = Grav::instance(); - $url = htmlspecialchars_decode(rawurldecode($excerpt['element']['attributes']['href'])); + $url = htmlspecialchars_decode(rawurldecode((string) $excerpt['element']['attributes']['href'])); $url_parts = $this->parseUrl($url); // If there is a query, then parse it and build action calls. if (isset($url_parts['query'])) { $actions = array_reduce( - explode('&', $url_parts['query']), + explode('&', (string) $url_parts['query']), static function ($carry, $item) { $parts = explode('=', $item, 2); $value = isset($parts[1]) ? rawurldecode($parts[1]) : true; @@ -119,7 +119,7 @@ class Excerpts $skip = []; // Unless told to not process, go through actions. if (array_key_exists('noprocess', $actions)) { - $skip = is_bool($actions['noprocess']) ? $actions : explode(',', $actions['noprocess']); + $skip = is_bool($actions['noprocess']) ? $actions : explode(',', (string) $actions['noprocess']); unset($actions['noprocess']); } @@ -185,7 +185,7 @@ class Excerpts */ public function processImageExcerpt(array $excerpt): array { - $url = htmlspecialchars_decode(urldecode($excerpt['element']['attributes']['src'])); + $url = htmlspecialchars_decode(urldecode((string) $excerpt['element']['attributes']['src'])); $url_parts = $this->parseUrl($url); $media = null; @@ -207,7 +207,7 @@ class Excerpts if ($local_file) { $filename = Utils::basename($url_parts['path']); - $folder = dirname($url_parts['path']); + $folder = dirname((string) $url_parts['path']); // Get the local path to page media if possible. if ($this->page && $folder === $this->page->url(false, false, false)) { @@ -268,7 +268,7 @@ class Excerpts // if there is a query, then parse it and build action calls if (isset($url_parts['query'])) { $actions = array_reduce( - explode('&', $url_parts['query']), + explode('&', (string) $url_parts['query']), static function ($carry, $item) { $parts = explode('=', $item, 2); $value = $parts[1] ?? null; @@ -296,10 +296,10 @@ class Excerpts foreach ($actions as $action) { $matches = []; - if (preg_match('/\[(.*)\]/', $action['params'], $matches)) { + if (preg_match('/\[(.*)\]/', (string) $action['params'], $matches)) { $args = [explode(',', $matches[1])]; } else { - $args = explode(',', $action['params']); + $args = explode(',', (string) $action['params']); } $medium = call_user_func_array([$medium, $action['method']], $args); diff --git a/system/src/Grav/Common/Page/Media.php b/system/src/Grav/Common/Page/Media.php index 6478528e5..2a27cb624 100644 --- a/system/src/Grav/Common/Page/Media.php +++ b/system/src/Grav/Common/Page/Media.php @@ -152,14 +152,14 @@ class Media extends AbstractMedia foreach ($iterator as $file => $info) { // Ignore folders and Markdown files. $filename = $info->getFilename(); - if (!$info->isFile() || $info->getExtension() === 'md' || $filename === 'frontmatter.yaml' || $filename === 'media.json' || strpos($filename, '.') === 0) { + if (!$info->isFile() || $info->getExtension() === 'md' || $filename === 'frontmatter.yaml' || $filename === 'media.json' || str_starts_with($filename, '.')) { continue; } // Find out what type we're dealing with [$basename, $ext, $type, $extra] = $this->getFileParts($filename); - if (!in_array(strtolower($ext), $media_types, true)) { + if (!in_array(strtolower((string) $ext), $media_types, true)) { continue; } diff --git a/system/src/Grav/Common/Page/Medium/ImageFile.php b/system/src/Grav/Common/Page/Medium/ImageFile.php index 554382a8a..636b00b5b 100644 --- a/system/src/Grav/Common/Page/Medium/ImageFile.php +++ b/system/src/Grav/Common/Page/Medium/ImageFile.php @@ -95,9 +95,7 @@ class ImageFile extends Image // Target file should be younger than all the current image // dependencies - $conditions = array( - 'younger-than' => $this->getDependencies() - ); + $conditions = ['younger-than' => $this->getDependencies()]; // The generating function $generate = function ($target) use ($image, $type, $quality) { @@ -113,7 +111,7 @@ class ImageFile extends Image // Asking the cache for the cacheFile try { $perms = $config->get('system.images.cache_perms', '0755'); - $perms = octdec($perms); + $perms = octdec((string) $perms); $file = $this->getCacheSystem()->setDirectoryMode($perms)->getOrCreateFile($cacheFile, $conditions, $generate, $actual); } catch (GenerationError $e) { $file = $e->getNewFile(); diff --git a/system/src/Grav/Common/Page/Medium/ImageMedium.php b/system/src/Grav/Common/Page/Medium/ImageMedium.php index 5539d9fb0..6db4a783e 100644 --- a/system/src/Grav/Common/Page/Medium/ImageMedium.php +++ b/system/src/Grav/Common/Page/Medium/ImageMedium.php @@ -370,7 +370,7 @@ class ImageMedium extends Medium implements ImageMediaInterface, ImageManipulate $watermark->resize($wwidth, $wheight); // Position operations - $position = !empty($args[1]) ? explode('-', $args[1]) : ['center', 'center']; // todo change to config + $position = !empty($args[1]) ? explode('-', (string) $args[1]) : ['center', 'center']; // todo change to config $positionY = $position[0] ?? $config->get('system.images.watermark.position_y', 'center'); $positionX = $position[1] ?? $config->get('system.images.watermark.position_x', 'center'); @@ -491,7 +491,7 @@ class ImageMedium extends Medium implements ImageMediaInterface, ImageManipulate // Do the same call for alternative media. $medium->__call($method, $args_copy); } - } catch (BadFunctionCallException $e) { + } catch (BadFunctionCallException) { } return $this; diff --git a/system/src/Grav/Common/Page/Medium/Link.php b/system/src/Grav/Common/Page/Medium/Link.php index 1abc7efd7..2dd158e5d 100644 --- a/system/src/Grav/Common/Page/Medium/Link.php +++ b/system/src/Grav/Common/Page/Medium/Link.php @@ -76,16 +76,15 @@ class Link implements RenderableInterface, MediaLinkInterface * Forward the call to the source element * * @param string $method - * @param mixed $args * @return mixed */ #[\ReturnTypeWillChange] - public function __call($method, $args) + public function __call($method, mixed $args) { $object = $this->source; $callable = [$object, $method]; if (!is_callable($callable)) { - throw new BadMethodCallException(get_class($object) . '::' . $method . '() not found.'); + throw new BadMethodCallException($object::class . '::' . $method . '() not found.'); } $object = call_user_func_array($callable, $args); diff --git a/system/src/Grav/Common/Page/Medium/Medium.php b/system/src/Grav/Common/Page/Medium/Medium.php index ede2a7441..5143deb3e 100644 --- a/system/src/Grav/Common/Page/Medium/Medium.php +++ b/system/src/Grav/Common/Page/Medium/Medium.php @@ -99,7 +99,7 @@ class Medium extends Data implements RenderableInterface, MediaFileInterface * @return string */ #[\ReturnTypeWillChange] - public function __toString() + public function __toString(): string { return $this->html(); } diff --git a/system/src/Grav/Common/Page/Medium/MediumFactory.php b/system/src/Grav/Common/Page/Medium/MediumFactory.php index 3f555969c..3aa80e77d 100644 --- a/system/src/Grav/Common/Page/Medium/MediumFactory.php +++ b/system/src/Grav/Common/Page/Medium/MediumFactory.php @@ -46,7 +46,7 @@ class MediumFactory $config = Grav::instance()['config']; - $media_params = $ext ? $config->get('media.types.' . strtolower($ext)) : null; + $media_params = $ext ? $config->get('media.types.' . strtolower((string) $ext)) : null; if (!is_array($media_params)) { return null; } @@ -111,7 +111,7 @@ class MediumFactory $config = Grav::instance()['config']; - $media_params = $ext ? $config->get('media.types.' . strtolower($ext)) : null; + $media_params = $ext ? $config->get('media.types.' . strtolower((string) $ext)) : null; if (!is_array($media_params)) { return null; } @@ -154,22 +154,15 @@ class MediumFactory { $type = $items['type'] ?? null; - switch ($type) { - case 'image': - return new ImageMedium($items, $blueprint); - case 'thumbnail': - return new ThumbnailImageMedium($items, $blueprint); - case 'vector': - return new VectorImageMedium($items, $blueprint); - case 'animated': - return new StaticImageMedium($items, $blueprint); - case 'video': - return new VideoMedium($items, $blueprint); - case 'audio': - return new AudioMedium($items, $blueprint); - default: - return new Medium($items, $blueprint); - } + return match ($type) { + 'image' => new ImageMedium($items, $blueprint), + 'thumbnail' => new ThumbnailImageMedium($items, $blueprint), + 'vector' => new VectorImageMedium($items, $blueprint), + 'animated' => new StaticImageMedium($items, $blueprint), + 'video' => new VideoMedium($items, $blueprint), + 'audio' => new AudioMedium($items, $blueprint), + default => new Medium($items, $blueprint), + }; } /** diff --git a/system/src/Grav/Common/Page/Page.php b/system/src/Grav/Common/Page/Page.php index 2883b6ff8..17cc39c37 100644 --- a/system/src/Grav/Common/Page/Page.php +++ b/system/src/Grav/Common/Page/Page.php @@ -203,14 +203,14 @@ class Page implements PageInterface $this->home_route = $this->adjustRouteCase($config->get('system.home.alias')); $this->filePath($file->getPathname()); $this->modified($file->getMTime()); - $this->id($this->modified() . md5($this->filePath())); + $this->id($this->modified() . md5((string) $this->filePath())); $this->routable(true); $this->header(); $this->date(); $this->metadata(); $this->url(); $this->visible(); - $this->modularTwig(strpos($this->slug(), '_') === 0); + $this->modularTwig(str_starts_with($this->slug(), '_')); $this->setPublishState(); $this->published(); $this->urlExtension(); @@ -254,7 +254,7 @@ class Page implements PageInterface } } $text_header = Grav::instance()['twig']->processString(json_encode($process_fields, JSON_UNESCAPED_UNICODE), ['page' => $this]); - $this->header((object)(json_decode($text_header, true) + $ignored_fields)); + $this->header((object)(json_decode((string) $text_header, true) + $ignored_fields)); } } @@ -274,7 +274,7 @@ class Page implements PageInterface $languages = $language->getLanguages(); $defaultCode = $language->getDefault(); - $name = substr($this->name, 0, -strlen($this->extension())); + $name = substr((string) $this->name, 0, -strlen($this->extension())); $translatedLanguages = []; foreach ($languages as $languageCode) { @@ -347,7 +347,7 @@ class Page implements PageInterface // Reset header and content. $this->modified = time(); - $this->id($this->modified() . md5($this->filePath())); + $this->id($this->modified() . md5((string) $this->filePath())); $this->header = null; $this->content = null; $this->summary = null; @@ -375,7 +375,7 @@ class Page implements PageInterface } // Force content re-processing. - $this->id(time() . md5($this->filePath())); + $this->id(time() . md5((string) $this->filePath())); } if (!$this->frontmatter) { $this->header(); @@ -402,7 +402,7 @@ class Page implements PageInterface } // Force content re-processing. - $this->id(time() . md5($this->filePath())); + $this->id(time() . md5((string) $this->filePath())); } if (!$this->header) { $file = $this->file(); @@ -742,7 +742,7 @@ class Page implements PageInterface } // Force re-processing. - $this->id(time() . md5($this->filePath())); + $this->id(time() . md5((string) $this->filePath())); $this->content = null; } // If no content, process it @@ -842,7 +842,7 @@ class Page implements PageInterface // Handle summary divider $delimiter = $config->get('site.summary.delimiter', '==='); - $divider_pos = mb_strpos($this->content, "

{$delimiter}

"); + $divider_pos = mb_strpos((string) $this->content, "

{$delimiter}

"); if ($divider_pos !== false) { $this->summary_size = $divider_pos; $this->content = str_replace("

{$delimiter}

", '', $this->content); @@ -955,8 +955,8 @@ class Page implements PageInterface // Base64 encode any twig. $content = preg_replace_callback( ['/({#.*?#})/mu', '/({{.*?}})/mu', '/({%.*?%})/mu'], - static function ($matches) use ($token) { return $token[0] . base64_encode($matches[1]) . $token[1]; }, - $content + static fn($matches) => $token[0] . base64_encode((string) $matches[1]) . $token[1], + (string) $content ); } @@ -966,8 +966,8 @@ class Page implements PageInterface // Base64 decode the encoded twig. $content = preg_replace_callback( ['`' . $token[0] . '([A-Za-z0-9+/]+={0,2})' . $token[1] . '`mu'], - static function ($matches) { return base64_decode($matches[1]); }, - $content + static fn($matches) => base64_decode((string) $matches[1]), + (string) $content ); } @@ -1202,7 +1202,7 @@ class Page implements PageInterface } $this->parent($parent); - $this->id(time() . md5($this->filePath())); + $this->id(time() . md5((string) $this->filePath())); if ($parent->path()) { $this->path($parent->path() . '/' . $this->folder()); @@ -1288,7 +1288,7 @@ class Page implements PageInterface } $post_value = $_POST['blueprint']; - $sanitized_value = htmlspecialchars(strip_tags($post_value), ENT_QUOTES, 'UTF-8'); + $sanitized_value = htmlspecialchars(strip_tags((string) $post_value), ENT_QUOTES, 'UTF-8'); return $sanitized_value ?: $this->template(); } @@ -1761,7 +1761,7 @@ class Page implements PageInterface $this->metadata[$prop_key] = [ 'name' => $prop_key, 'property' => $prop_key, - 'content' => $escape ? htmlspecialchars($prop_value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $prop_value + 'content' => $escape ? htmlspecialchars((string) $prop_value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $prop_value ]; } } else { @@ -1770,16 +1770,16 @@ class Page implements PageInterface if (in_array($key, $header_tag_http_equivs, true)) { $this->metadata[$key] = [ 'http_equiv' => $key, - 'content' => $escape ? htmlspecialchars($value, ENT_COMPAT, 'UTF-8') : $value + 'content' => $escape ? htmlspecialchars((string) $value, ENT_COMPAT, 'UTF-8') : $value ]; } elseif ($key === 'charset') { - $this->metadata[$key] = ['charset' => $escape ? htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $value]; + $this->metadata[$key] = ['charset' => $escape ? htmlspecialchars((string) $value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $value]; } else { // if it's a social metadata with separator, render as property $separator = strpos($key, ':'); $hasSeparator = $separator && $separator < strlen($key) - 1; $entry = [ - 'content' => $escape ? htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $value + 'content' => $escape ? htmlspecialchars((string) $value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $value ]; if ($hasSeparator && !Utils::startsWith($key, ['twitter', 'flattr','fediverse'])) { @@ -1919,7 +1919,7 @@ class Page implements PageInterface /** @var Uri $uri */ $uri = $grav['uri']; - $url = $uri->rootUrl($include_host) . '/' . trim($route, '/') . $this->urlExtension(); + $url = $uri->rootUrl($include_host) . '/' . trim((string) $route, '/') . $this->urlExtension(); return Uri::filterPath($url); } @@ -2044,7 +2044,7 @@ class Page implements PageInterface { if (null === $this->id) { // We need to set unique id to avoid potential cache conflicts between pages. - $var = time() . md5($this->filePath()); + $var = time() . md5((string) $this->filePath()); } if ($var !== null) { // store unique per language @@ -2536,7 +2536,7 @@ class Page implements PageInterface */ public function active() { - $uri_path = rtrim(urldecode(Grav::instance()['uri']->path()), '/') ?: '/'; + $uri_path = rtrim(urldecode((string) Grav::instance()['uri']->path()), '/') ?: '/'; $routes = Grav::instance()['pages']->routes(); return isset($routes[$uri_path]) && $routes[$uri_path] === $this->path(); @@ -2794,7 +2794,7 @@ class Page implements PageInterface protected function cleanPath($path) { $lastchunk = strrchr($path, DS); - if (strpos($lastchunk, ':') !== false) { + if (str_contains($lastchunk, ':')) { $path = str_replace($lastchunk, '', $path); } @@ -2827,7 +2827,7 @@ class Page implements PageInterface // Reorder all moved pages. foreach ($siblings as $slug => $page) { - $order = (int)trim($page->order(), '.'); + $order = (int)trim((string) $page->order(), '.'); $counter++; if ($order) { diff --git a/system/src/Grav/Common/Page/Pages.php b/system/src/Grav/Common/Page/Pages.php index a0b0506dc..1ecfff4ff 100644 --- a/system/src/Grav/Common/Page/Pages.php +++ b/system/src/Grav/Common/Page/Pages.php @@ -168,7 +168,7 @@ class Pages */ public function baseRoute($lang = null) { - $key = $lang ?: $this->active_lang ?: 'default'; + $key = ($lang ?: $this->active_lang) ?: 'default'; if (!isset($this->baseRoute[$key])) { /** @var Language $language */ @@ -217,7 +217,7 @@ class Pages // Start by checking that referrer came from our site. $root = $this->grav['base_url_absolute']; - if (!is_string($referrer) || !str_starts_with($referrer, $root)) { + if (!is_string($referrer) || !str_starts_with($referrer, (string) $root)) { return null; } @@ -470,7 +470,7 @@ class Pages /** @var Uri $uri */ $uri = $this->grav['uri']; foreach ($context['taxonomies'] as $taxonomy) { - $param = $uri->param(rawurlencode($taxonomy)); + $param = $uri->param(rawurlencode((string) $taxonomy)); $items = is_string($param) ? explode(',', $param) : []; foreach ($items as $item) { $params['taxonomies'][$taxonomy][] = htmlspecialchars_decode(rawurldecode($item), ENT_QUOTES); @@ -534,8 +534,8 @@ class Pages } // Convert non-type to type. - if (str_starts_with($type, 'non-')) { - $type = substr($type, 4); + if (str_starts_with((string) $type, 'non-')) { + $type = substr((string) $type, 4); $filter = !$filter; } @@ -610,9 +610,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, static function ($a, $b) { - return $a | $b; - }, 0); //merge constant values using bit or + $sort_flags = array_reduce($sort_flags, static fn($a, $b) => $a | $b, 0); //merge constant values using bit or } $collection = $collection->order($by, $dir, $custom, $sort_flags); @@ -1013,7 +1011,7 @@ class Pages foreach (array_reverse($site_routes, true) as $pattern => $replace) { $pattern = '#^' . str_replace('/', '\/', ltrim($pattern, '^')) . '#'; try { - $found = preg_replace($pattern, $replace, $route); + $found = preg_replace($pattern, (string) $replace, $route); if ($found && $found !== $route) { $page = $this->find($found); if ($page) { @@ -1095,7 +1093,7 @@ class Pages $pattern = '#^' . str_replace('/', '\/', $pattern) . '#'; try { /** @var string $found */ - $found = preg_replace($pattern, $replace, $source_url); + $found = preg_replace($pattern, (string) $replace, $source_url); if ($found && $found !== $source_url) { $this->grav->redirectLangSafe($found); } @@ -1142,7 +1140,7 @@ class Pages try { $blueprint = $this->blueprints->get($type); - } catch (RuntimeException $e) { + } catch (RuntimeException) { $blueprint = $this->blueprints->get('default'); } @@ -1254,7 +1252,7 @@ class Pages } if ($showFullpath) { - $option = htmlspecialchars($current->route()); + $option = htmlspecialchars((string) $current->route()); } else { $extra = $showSlug ? '(' . $current->slug() . ') ' : ''; $option = str_repeat('—-', $level). '▸ ' . $extra . htmlspecialchars($current->title()); @@ -1337,7 +1335,7 @@ class Pages $locator = $grav['locator']; foreach ($types as $type => $paths) { foreach ($paths as $k => $path) { - if (strpos($path, 'blueprints://') === 0) { + if (str_starts_with((string) $path, 'blueprints://')) { unset($paths[$k]); } } @@ -1393,15 +1391,11 @@ class Pages $type = $page && $page->isModule() ? 'modular' : 'standard'; } - - switch ($type) { - case 'standard': - return static::types(); - case 'modular': - return static::modularTypes(); - } - - return []; + return match ($type) { + 'standard' => static::types(), + 'modular' => static::modularTypes(), + default => [], + }; } /** @@ -1475,13 +1469,13 @@ class Pages } else { $home = $home_aliases[$default]; } - } catch (ErrorException $e) { + } catch (ErrorException) { $home = $home_aliases[$default]; } } } - self::$home_route = trim($home, '/'); + self::$home_route = trim((string) $home, '/'); } return self::$home_route; @@ -1730,20 +1724,12 @@ class Pages $language = $this->grav['language']; // how should we check for last modified? Default is by file - switch ($this->check_method) { - case 'none': - case 'off': - $hash = 0; - break; - case 'folder': - $hash = Folder::lastModifiedFolder($pages_dirs); - break; - case 'hash': - $hash = Folder::hashAllFiles($pages_dirs); - break; - default: - $hash = Folder::lastModifiedFile($pages_dirs); - } + $hash = match ($this->check_method) { + 'none', 'off' => 0, + 'folder' => Folder::lastModifiedFolder($pages_dirs), + 'hash' => Folder::hashAllFiles($pages_dirs), + default => Folder::lastModifiedFile($pages_dirs), + }; $this->simple_pages_hash = json_encode($pages_dirs) . $hash . $config->checksum(); $this->pages_cache_id = md5($this->simple_pages_hash . $language->getActive()); @@ -1861,9 +1847,7 @@ class Pages // Build regular expression for all the allowed page extensions. $page_extensions = $language->getFallbackPageExtensions(); $regex = '/^[^\.]*(' . implode('|', array_map( - static function ($str) { - return preg_quote($str, '/'); - }, + static fn($str) => preg_quote((string) $str, '/'), $page_extensions )) . ')$/'; @@ -1877,7 +1861,7 @@ class Pages $filename = $file->getFilename(); // Ignore all hidden files if set. - if ($this->ignore_hidden && $filename && strpos($filename, '.') === 0) { + if ($this->ignore_hidden && $filename && str_starts_with($filename, '.')) { continue; } @@ -2079,7 +2063,7 @@ class Pages $header_default = null; // do this header query work only once - if (strpos($order_by, 'header.') === 0) { + if (str_starts_with($order_by, 'header.')) { $query = explode('|', str_replace('header.', '', $order_by), 2); $header_query = array_shift($query) ?? ''; $header_default = array_shift($query); @@ -2159,9 +2143,7 @@ class Pages if ($col) { $col->setAttribute(Collator::NUMERIC_COLLATION, Collator::ON); if (($sort_flags & SORT_NATURAL) === SORT_NATURAL) { - $list = preg_replace_callback('~([0-9]+)\.~', static function ($number) { - return sprintf('%032d.', $number[0]); - }, $list); + $list = preg_replace_callback('~([0-9]+)\.~', static fn($number) => sprintf('%032d.', $number[0]), $list); if (!is_array($list)) { throw new RuntimeException('Internal Error'); } diff --git a/system/src/Grav/Common/Page/Traits/PageFormTrait.php b/system/src/Grav/Common/Page/Traits/PageFormTrait.php index b99e7b75c..eab786e10 100644 --- a/system/src/Grav/Common/Page/Traits/PageFormTrait.php +++ b/system/src/Grav/Common/Page/Traits/PageFormTrait.php @@ -111,7 +111,7 @@ trait PageFormTrait $name = null; } - $name = $name ?? $form['name'] ?? $this->slug(); + $name ??= $form['name'] ?? $this->slug(); $formRules = $form['rules'] ?? null; if (!is_array($formRules)) { diff --git a/system/src/Grav/Common/Page/Types.php b/system/src/Grav/Common/Page/Types.php index d9bdc331d..24c0677c2 100644 --- a/system/src/Grav/Common/Page/Types.php +++ b/system/src/Grav/Common/Page/Types.php @@ -142,7 +142,7 @@ class Types implements \ArrayAccess, \Iterator, \Countable { $list = []; foreach ($this->items as $name => $file) { - if (strpos($name, 'modular/') !== 0) { + if (!str_starts_with($name, 'modular/')) { continue; } $list[$name] = ucfirst(trim(str_replace('_', ' ', Utils::basename($name)))); diff --git a/system/src/Grav/Common/Plugin.php b/system/src/Grav/Common/Plugin.php index f6235141d..1e1a8f416 100644 --- a/system/src/Grav/Common/Plugin.php +++ b/system/src/Grav/Common/Plugin.php @@ -30,8 +30,6 @@ use function is_string; */ class Plugin implements EventSubscriberInterface, ArrayAccess { - /** @var string */ - public $name; /** @var array */ public $features = []; @@ -57,7 +55,7 @@ class Plugin implements EventSubscriberInterface, ArrayAccess $list = []; foreach ($methods as $method) { - if (strpos($method, 'on') === 0) { + if (str_starts_with($method, 'on')) { $list[$method] = [$method, 0]; } } @@ -72,9 +70,8 @@ class Plugin implements EventSubscriberInterface, ArrayAccess * @param Grav $grav * @param Config|null $config */ - public function __construct($name, Grav $grav, ?Config $config = null) + public function __construct(public $name, Grav $grav, ?Config $config = null) { - $this->name = $name; $this->grav = $grav; if ($config) { @@ -156,7 +153,7 @@ class Plugin implements EventSubscriberInterface, ArrayAccess /** @var Config $config */ $config = $this->config ?? $this->grav['config']; - if (strpos($uri->path(), $config->get('plugins.admin.route') . '/' . $plugin_route) === false) { + if (!str_contains($uri->path(), $config->get('plugins.admin.route') . '/' . $plugin_route)) { $active = false; } elseif (isset($uri->paths()[1]) && $uri->paths()[1] === $plugin_route) { $active = true; @@ -265,9 +262,9 @@ class Plugin implements EventSubscriberInterface, ArrayAccess * @throws LogicException */ #[\ReturnTypeWillChange] - public function offsetSet($offset, $value) + public function offsetSet($offset, mixed $value) { - throw new LogicException(__CLASS__ . ' blueprints cannot be modified.'); + throw new LogicException(self::class . ' blueprints cannot be modified.'); } /** @@ -279,7 +276,7 @@ class Plugin implements EventSubscriberInterface, ArrayAccess #[\ReturnTypeWillChange] public function offsetUnset($offset) { - throw new LogicException(__CLASS__ . ' blueprints cannot be modified.'); + throw new LogicException(self::class . ' blueprints cannot be modified.'); } /** @@ -330,7 +327,7 @@ class Plugin implements EventSubscriberInterface, ArrayAccess * @param string $type Is this 'plugins' or 'themes' * @return Data */ - protected function mergeConfig(PageInterface $page, $deep = false, $params = [], $type = 'plugins') + protected function mergeConfig(PageInterface $page, mixed $deep = false, $params = [], $type = 'plugins') { /** @var Config $config */ $config = $this->config ?? $this->grav['config']; @@ -419,7 +416,7 @@ class Plugin implements EventSubscriberInterface, ArrayAccess if (Utils::isAdminPlugin()) { $page = Grav::instance()['admin']->page() ?? null; } else { - $page = $page ?? Grav::instance()['page'] ?? null; + $page ??= Grav::instance()['page'] ?? null; } // Try to find var in the page headers diff --git a/system/src/Grav/Common/Plugins.php b/system/src/Grav/Common/Plugins.php index af54ec8a1..47e814482 100644 --- a/system/src/Grav/Common/Plugins.php +++ b/system/src/Grav/Common/Plugins.php @@ -86,7 +86,7 @@ class Plugins extends Iterator $blueprints["plugin://{$plugin->name}/blueprints"] = $plugin->features['blueprints']; } if (method_exists($plugin, 'getFormFieldTypes')) { - $formFields[get_class($plugin)] = $plugin->features['formfields'] ?? 0; + $formFields[$plugin::class] = $plugin->features['formfields'] ?? 0; } } } @@ -168,7 +168,7 @@ class Plugins extends Iterator public function add($plugin) { if (is_object($plugin)) { - $this->items[get_class($plugin)] = $plugin; + $this->items[$plugin::class] = $plugin; } } diff --git a/system/src/Grav/Common/Processors/InitializeProcessor.php b/system/src/Grav/Common/Processors/InitializeProcessor.php index 417f6c543..95bafb84c 100644 --- a/system/src/Grav/Common/Processors/InitializeProcessor.php +++ b/system/src/Grav/Common/Processors/InitializeProcessor.php @@ -126,9 +126,7 @@ class InitializeProcessor extends ProcessorBase // Wrap call to next handler so that debugger can profile it. /** @var Response $response */ - $response = $debugger->profile(static function () use ($handler, $request) { - return $handler->handle($request); - }); + $response = $debugger->profile(static fn() => $handler->handle($request)); // Log both request and response and return the response. return $debugger->logRequest($request, $response); @@ -448,7 +446,7 @@ class InitializeProcessor extends ProcessorBase try { $session->init(); - } catch (SessionException $e) { + } catch (SessionException) { $session->init(); $message = 'Session corruption detected, restarting session...'; $this->addMessage($message); diff --git a/system/src/Grav/Common/Processors/TasksProcessor.php b/system/src/Grav/Common/Processors/TasksProcessor.php index ab5caf9b1..544678e3e 100644 --- a/system/src/Grav/Common/Processors/TasksProcessor.php +++ b/system/src/Grav/Common/Processors/TasksProcessor.php @@ -53,7 +53,7 @@ class TasksProcessor extends ProcessorBase $this->stopTimer(); return $response; - } catch (NotFoundException $e) { + } catch (NotFoundException) { // Task not found: Let it pass through. } } diff --git a/system/src/Grav/Common/Scheduler/Cron.php b/system/src/Grav/Common/Scheduler/Cron.php index d50d1007a..b7f12b65b 100644 --- a/system/src/Grav/Common/Scheduler/Cron.php +++ b/system/src/Grav/Common/Scheduler/Cron.php @@ -224,8 +224,8 @@ class Cron public function getType() { $mask = preg_replace('/[^\* ]/', '-', $this->getCron()); - $mask = preg_replace('/-+/', '-', $mask); - $mask = preg_replace('/[^-\*]/', '', $mask); + $mask = preg_replace('/-+/', '-', (string) $mask); + $mask = preg_replace('/[^-\*]/', '', (string) $mask); if ($mask === '*****') { return self::TYPE_MINUTE; @@ -235,19 +235,19 @@ class Cron return self::TYPE_HOUR; } - if (substr($mask, -3) === '***') { + if (str_ends_with((string) $mask, '***')) { return self::TYPE_DAY; } - if (substr($mask, -3) === '-**') { + if (str_ends_with((string) $mask, '-**')) { return self::TYPE_MONTH; } - if (substr($mask, -3) === '**-') { + if (str_ends_with((string) $mask, '**-')) { return self::TYPE_WEEK; } - if (substr($mask, -2) === '-*') { + if (str_ends_with((string) $mask, '-*')) { return self::TYPE_YEAR; } @@ -264,7 +264,7 @@ class Cron $cron = trim($cron); $cron = preg_replace('/\s+/', ' ', $cron); // explode - $elements = explode(' ', $cron); + $elements = explode(' ', (string) $cron); if (count($elements) !== 5) { throw new RuntimeException('Bad number of elements'); } @@ -415,7 +415,6 @@ class Cron } /** - * @param mixed $date * @param int $min * @param int $hour * @param int $day @@ -423,7 +422,7 @@ class Cron * @param int $weekday * @return DateTime */ - protected function parseDate($date, &$min, &$hour, &$day, &$month, &$weekday) + protected function parseDate(mixed $date, &$min, &$hour, &$day, &$month, &$weekday) { if (is_numeric($date) && (int)$date == $date) { $date = new DateTime('@' . $date); diff --git a/system/src/Grav/Common/Scheduler/Job.php b/system/src/Grav/Common/Scheduler/Job.php index a5a5e6087..a502e5a03 100644 --- a/system/src/Grav/Common/Scheduler/Job.php +++ b/system/src/Grav/Common/Scheduler/Job.php @@ -39,8 +39,6 @@ class Job private $command; /** @var string */ private $at; - /** @var array */ - private $args = []; /** @var bool */ private $runInBackground = true; /** @var DateTime */ @@ -85,7 +83,7 @@ class Job * @param array $args * @param string|null $id */ - public function __construct($command, $args = [], $id = null) + public function __construct($command, private $args = [], $id = null) { if (is_string($id)) { $this->id = Grav::instance()['inflector']->hyphenize($id); @@ -101,7 +99,6 @@ class Job // initialize the directory path for lock files $this->tempDir = sys_get_temp_dir(); $this->command = $command; - $this->args = $args; // Set enabled state $status = Grav::instance()['config']->get('scheduler.status'); $this->enabled = !(isset($status[$id]) && $status[$id] === 'disabled'); @@ -195,7 +192,7 @@ class Job $this->at('* * * * *'); } - $date = $date ?? $this->creationTime; + $date ??= $this->creationTime; return $this->executionTime->isDue($date); } @@ -271,9 +268,7 @@ class Job if ($whenOverlapping) { $this->whenOverlapping = $whenOverlapping; } else { - $this->whenOverlapping = static function () { - return false; - }; + $this->whenOverlapping = static fn() => false; } return $this; @@ -410,10 +405,9 @@ class Job /** * Create the job lock file. * - * @param mixed $content * @return void */ - private function createLockFile($content = null) + private function createLockFile(mixed $content = null) { if ($this->lockFile) { if ($content === null || !is_string($content)) { diff --git a/system/src/Grav/Common/Scheduler/Scheduler.php b/system/src/Grav/Common/Scheduler/Scheduler.php index 8e0f9e1d6..3bb71e580 100644 --- a/system/src/Grav/Common/Scheduler/Scheduler.php +++ b/system/src/Grav/Common/Scheduler/Scheduler.php @@ -244,16 +244,12 @@ class Scheduler */ public function getVerboseOutput($type = 'text') { - switch ($type) { - case 'text': - return implode("\n", $this->output_schedule); - case 'html': - return implode('
', $this->output_schedule); - case 'array': - return $this->output_schedule; - default: - throw new InvalidArgumentException('Invalid output type'); - } + return match ($type) { + 'text' => implode("\n", $this->output_schedule), + 'html' => implode('
', $this->output_schedule), + 'array' => $this->output_schedule, + default => throw new InvalidArgumentException('Invalid output type'), + }; } /** @@ -287,7 +283,7 @@ class Scheduler public function getSchedulerCommand($php = null) { $phpBinaryFinder = new PhpExecutableFinder(); - $php = $php ?? $phpBinaryFinder->find(); + $php ??= $phpBinaryFinder->find(); $command = 'cd ' . str_replace(' ', '\ ', GRAV_ROOT) . ';' . $php . ' bin/grav scheduler'; return $command; @@ -439,7 +435,7 @@ class Scheduler if (is_callable($command)) { $command = is_string($command) ? $command : 'Closure'; } - $output = trim($job->getOutput()); + $output = trim((string) $job->getOutput()); $this->addSchedulerVerboseOutput("Error: {$command}{$output}"); return $job; diff --git a/system/src/Grav/Common/Security.php b/system/src/Grav/Common/Security.php index 491a61c01..bdff7eeca 100644 --- a/system/src/Grav/Common/Security.php +++ b/system/src/Grav/Common/Security.php @@ -129,7 +129,7 @@ class Security $list[$page->rawRoute()] = $results; } } - } catch (Exception $e) { + } catch (Exception) { continue; } } @@ -196,7 +196,7 @@ class Security if (!$invalid_protocols) { $enabled_rules['invalid_protocols'] = false; } - $enabled_rules = array_filter($enabled_rules, static function ($val) { return !empty($val); }); + $enabled_rules = array_filter($enabled_rules, static fn($val) => !empty($val)); if (!$enabled_rules) { return null; } @@ -208,19 +208,17 @@ class Security $string = urldecode($string); // Convert Hexadecimals - $string = (string)preg_replace_callback('!(&#|\\\)[xX]([0-9a-fA-F]+);?!u', static function ($m) { - return chr(hexdec($m[2])); - }, $string); + $string = (string)preg_replace_callback('!(&#|\\\)[xX]([0-9a-fA-F]+);?!u', static fn($m) => chr(hexdec((string) $m[2])), $string); // Clean up entities $string = preg_replace('!(&#[0-9]+);?!u', '$1;', $string); // Decode entities - $string = html_entity_decode($string, ENT_NOQUOTES | ENT_HTML5, 'UTF-8'); + $string = html_entity_decode((string) $string, ENT_NOQUOTES | ENT_HTML5, 'UTF-8'); // Strip whitespace characters $string = preg_replace('!\s!u', ' ', $string); - $stripped = preg_replace('!\s!u', '', $string); + $stripped = preg_replace('!\s!u', '', (string) $string); // Set the patterns we'll test against $patterns = [ @@ -243,7 +241,7 @@ class Security // Iterate over rules and return label if fail foreach ($patterns as $name => $regex) { if (!empty($enabled_rules[$name])) { - if (preg_match($regex, $string) || preg_match($regex, $stripped) || preg_match($regex, $orig)) { + if (preg_match($regex, (string) $string) || preg_match($regex, (string) $stripped) || preg_match($regex, $orig)) { return $name; } } diff --git a/system/src/Grav/Common/Service/AssetsServiceProvider.php b/system/src/Grav/Common/Service/AssetsServiceProvider.php index 54bb2f469..192a8d303 100644 --- a/system/src/Grav/Common/Service/AssetsServiceProvider.php +++ b/system/src/Grav/Common/Service/AssetsServiceProvider.php @@ -25,8 +25,6 @@ class AssetsServiceProvider implements ServiceProviderInterface */ public function register(Container $container) { - $container['assets'] = function () { - return new Assets(); - }; + $container['assets'] = fn() => new Assets(); } } diff --git a/system/src/Grav/Common/Service/ConfigServiceProvider.php b/system/src/Grav/Common/Service/ConfigServiceProvider.php index 6f0ffae72..1fe45a1a1 100644 --- a/system/src/Grav/Common/Service/ConfigServiceProvider.php +++ b/system/src/Grav/Common/Service/ConfigServiceProvider.php @@ -42,9 +42,7 @@ class ConfigServiceProvider implements ServiceProviderInterface return $setup; }; - $container['blueprints'] = function ($c) { - return static::blueprints($c); - }; + $container['blueprints'] = fn($c) => static::blueprints($c); $container['config'] = function ($c) { $config = static::load($c); @@ -70,13 +68,9 @@ class ConfigServiceProvider implements ServiceProviderInterface return MimeTypes::createFromMimes($mimes); }; - $container['languages'] = function ($c) { - return static::languages($c); - }; + $container['languages'] = fn($c) => static::languages($c); - $container['language'] = function ($c) { - return new Language($c); - }; + $container['language'] = fn($c) => new Language($c); } /** @@ -129,9 +123,7 @@ class ConfigServiceProvider implements ServiceProviderInterface $files += (new ConfigFileFinder)->setBase('themes')->locateInFolders($paths); $compiled = new CompiledConfig($cache, $files, GRAV_ROOT); - $compiled->setBlueprints(function () use ($container) { - return $container['blueprints']; - }); + $compiled->setBlueprints(fn() => $container['blueprints']); $config = $compiled->name("master-{$setup->environment}")->load(); $config->environment = $setup->environment; diff --git a/system/src/Grav/Common/Service/FilesystemServiceProvider.php b/system/src/Grav/Common/Service/FilesystemServiceProvider.php index eadcb52ec..0114eab60 100644 --- a/system/src/Grav/Common/Service/FilesystemServiceProvider.php +++ b/system/src/Grav/Common/Service/FilesystemServiceProvider.php @@ -25,8 +25,6 @@ class FilesystemServiceProvider implements ServiceProviderInterface */ public function register(Container $container) { - $container['filesystem'] = function () { - return Filesystem::getInstance(); - }; + $container['filesystem'] = fn() => Filesystem::getInstance(); } } diff --git a/system/src/Grav/Common/Service/InflectorServiceProvider.php b/system/src/Grav/Common/Service/InflectorServiceProvider.php index fcb49aa56..131717bb3 100644 --- a/system/src/Grav/Common/Service/InflectorServiceProvider.php +++ b/system/src/Grav/Common/Service/InflectorServiceProvider.php @@ -25,8 +25,6 @@ class InflectorServiceProvider implements ServiceProviderInterface */ public function register(Container $container) { - $container['inflector'] = function () { - return new Inflector(); - }; + $container['inflector'] = fn() => new Inflector(); } } diff --git a/system/src/Grav/Common/Service/PagesServiceProvider.php b/system/src/Grav/Common/Service/PagesServiceProvider.php index dd1be13c0..5b5233d87 100644 --- a/system/src/Grav/Common/Service/PagesServiceProvider.php +++ b/system/src/Grav/Common/Service/PagesServiceProvider.php @@ -32,9 +32,7 @@ class PagesServiceProvider implements ServiceProviderInterface */ public function register(Container $container) { - $container['pages'] = function (Grav $grav) { - return new Pages($grav); - }; + $container['pages'] = fn(Grav $grav) => new Pages($grav); if (defined('GRAV_CLI')) { $container['page'] = static function (Grav $grav) { diff --git a/system/src/Grav/Common/Service/RequestServiceProvider.php b/system/src/Grav/Common/Service/RequestServiceProvider.php index ad9858f24..071337ff9 100644 --- a/system/src/Grav/Common/Service/RequestServiceProvider.php +++ b/system/src/Grav/Common/Service/RequestServiceProvider.php @@ -73,7 +73,7 @@ class RequestServiceProvider implements ServiceProviderInterface if (!is_array($post)) { $post = null; } - } catch (JsonException $e) { + } catch (JsonException) { $post = null; } break 2; @@ -86,7 +86,7 @@ class RequestServiceProvider implements ServiceProviderInterface unset($get['_url']); if (isset($server['QUERY_STRING'])) { $query = $server['QUERY_STRING']; - if (strpos($query, '_url=') !== false) { + if (str_contains($query, '_url=')) { parse_str($query, $query); unset($query['_url']); $server['QUERY_STRING'] = http_build_query($query); @@ -96,8 +96,6 @@ class RequestServiceProvider implements ServiceProviderInterface return $creator->fromArrays($server, $headers, $_COOKIE, $get, $post, $_FILES, fopen('php://input', 'rb') ?: null); }; - $container['route'] = $container->factory(function () { - return clone Uri::getCurrentRoute(); - }); + $container['route'] = $container->factory(fn() => clone Uri::getCurrentRoute()); } } diff --git a/system/src/Grav/Common/Service/SchedulerServiceProvider.php b/system/src/Grav/Common/Service/SchedulerServiceProvider.php index 2fbe41797..4ba32ea3e 100644 --- a/system/src/Grav/Common/Service/SchedulerServiceProvider.php +++ b/system/src/Grav/Common/Service/SchedulerServiceProvider.php @@ -25,8 +25,6 @@ class SchedulerServiceProvider implements ServiceProviderInterface */ public function register(Container $container) { - $container['scheduler'] = function () { - return new Scheduler(); - }; + $container['scheduler'] = fn() => new Scheduler(); } } diff --git a/system/src/Grav/Common/Service/SessionServiceProvider.php b/system/src/Grav/Common/Service/SessionServiceProvider.php index a2c35f7a8..8e5ea9bd1 100644 --- a/system/src/Grav/Common/Service/SessionServiceProvider.php +++ b/system/src/Grav/Common/Service/SessionServiceProvider.php @@ -64,7 +64,7 @@ class SessionServiceProvider implements ServiceProviderInterface // Activate admin if we're inside the admin path. $is_admin = false; if ($config->get('plugins.admin.enabled')) { - $admin_base = '/' . trim($config->get('plugins.admin.route'), '/'); + $admin_base = '/' . trim((string) $config->get('plugins.admin.route'), '/'); // Uri::route() is not processed yet, let's quickly get what we need. $current_route = str_replace(Uri::filterPath($uri->rootUrl(false)), '', parse_url($uri->url(true), PHP_URL_PATH)); @@ -86,7 +86,7 @@ class SessionServiceProvider implements ServiceProviderInterface } $session_prefix = $c['inflector']->hyphenize($config->get('system.session.name', 'grav-site')); - $session_uniqueness = $config->get('system.session.uniqueness', 'path') === 'path' ? substr(md5(GRAV_ROOT), 0, 7) : md5($config->get('security.salt')); + $session_uniqueness = $config->get('system.session.uniqueness', 'path') === 'path' ? substr(md5(GRAV_ROOT), 0, 7) : md5((string) $config->get('security.salt')); $session_name = $session_prefix . '-' . $session_uniqueness; diff --git a/system/src/Grav/Common/Session.php b/system/src/Grav/Common/Session.php index a75e08367..fc519057c 100644 --- a/system/src/Grav/Common/Session.php +++ b/system/src/Grav/Common/Session.php @@ -31,7 +31,7 @@ class Session extends \Grav\Framework\Session\Session */ public static function instance() { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use ->getInstance() method instead', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use ->getInstance() method instead', E_USER_DEPRECATED); return static::getInstance(); } @@ -71,7 +71,7 @@ class Session extends \Grav\Framework\Session\Session */ public function all() { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use ->getAll() method instead', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use ->getAll() method instead', E_USER_DEPRECATED); return $this->getAll(); } @@ -84,7 +84,7 @@ class Session extends \Grav\Framework\Session\Session */ public function started() { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use ->isStarted() method instead', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use ->isStarted() method instead', E_USER_DEPRECATED); return $this->isStarted(); } @@ -93,10 +93,9 @@ class Session extends \Grav\Framework\Session\Session * Store something in session temporarily. * * @param string $name - * @param mixed $object * @return $this */ - public function setFlashObject($name, $object) + public function setFlashObject($name, mixed $object) { $this->__set($name, serialize($object)); @@ -147,14 +146,13 @@ class Session extends \Grav\Framework\Session\Session * Store something in cookie temporarily. * * @param string $name - * @param mixed $object * @param int $time * @return $this * @throws JsonException */ - public function setFlashCookieObject($name, $object, $time = 60) + public function setFlashCookieObject($name, mixed $object, $time = 60) { - setcookie($name, json_encode($object, JSON_THROW_ON_ERROR), $this->getCookieOptions($time)); + setcookie($name, json_encode($object, JSON_THROW_ON_ERROR), ['expires' => $this->getCookieOptions($time)]); return $this; } @@ -170,9 +168,9 @@ class Session extends \Grav\Framework\Session\Session { if (isset($_COOKIE[$name])) { $cookie = $_COOKIE[$name]; - setcookie($name, '', $this->getCookieOptions(-42000)); + setcookie($name, '', ['expires' => $this->getCookieOptions(-42000)]); - return json_decode($cookie, false, 512, JSON_THROW_ON_ERROR); + return json_decode((string) $cookie, false, 512, JSON_THROW_ON_ERROR); } return null; diff --git a/system/src/Grav/Common/Themes.php b/system/src/Grav/Common/Themes.php index 75bd8b15f..5943d384c 100644 --- a/system/src/Grav/Common/Themes.php +++ b/system/src/Grav/Common/Themes.php @@ -77,7 +77,7 @@ class Themes extends Iterator try { $instance = $themes->load(); - } catch (InvalidArgumentException $e) { + } catch (InvalidArgumentException) { throw new RuntimeException($this->current() . ' theme could not be found'); } @@ -377,7 +377,7 @@ class Themes extends Iterator protected function autoloadTheme($class) { $prefix = 'Grav\\Theme\\'; - if (false !== strpos($class, $prefix)) { + if (str_contains($class, $prefix)) { // Remove prefix from class $class = substr($class, strlen($prefix)); $locator = $this->grav['locator']; diff --git a/system/src/Grav/Common/Twig/Extension/FilesystemExtension.php b/system/src/Grav/Common/Twig/Extension/FilesystemExtension.php index cbafdb246..23bea7543 100644 --- a/system/src/Grav/Common/Twig/Extension/FilesystemExtension.php +++ b/system/src/Grav/Common/Twig/Extension/FilesystemExtension.php @@ -36,29 +36,29 @@ class FilesystemExtension extends AbstractExtension public function getFilters() { return [ - new TwigFilter('file_exists', [$this, 'file_exists']), - new TwigFilter('fileatime', [$this, 'fileatime']), - new TwigFilter('filectime', [$this, 'filectime']), - new TwigFilter('filemtime', [$this, 'filemtime']), - new TwigFilter('filesize', [$this, 'filesize']), - new TwigFilter('filetype', [$this, 'filetype']), - new TwigFilter('is_dir', [$this, 'is_dir']), - new TwigFilter('is_file', [$this, 'is_file']), - new TwigFilter('is_link', [$this, 'is_link']), - new TwigFilter('is_readable', [$this, 'is_readable']), - new TwigFilter('is_writable', [$this, 'is_writable']), - new TwigFilter('is_writeable', [$this, 'is_writable']), - new TwigFilter('lstat', [$this, 'lstat']), - new TwigFilter('getimagesize', [$this, 'getimagesize']), - new TwigFilter('exif_read_data', [$this, 'exif_read_data']), - new TwigFilter('read_exif_data', [$this, 'exif_read_data']), - new TwigFilter('exif_imagetype', [$this, 'exif_imagetype']), - new TwigFilter('hash_file', [$this, 'hash_file']), - new TwigFilter('hash_hmac_file', [$this, 'hash_hmac_file']), - new TwigFilter('md5_file', [$this, 'md5_file']), - new TwigFilter('sha1_file', [$this, 'sha1_file']), - new TwigFilter('get_meta_tags', [$this, 'get_meta_tags']), - new TwigFilter('pathinfo', [$this, 'pathinfo']), + new TwigFilter('file_exists', $this->file_exists(...)), + new TwigFilter('fileatime', $this->fileatime(...)), + new TwigFilter('filectime', $this->filectime(...)), + new TwigFilter('filemtime', $this->filemtime(...)), + new TwigFilter('filesize', $this->filesize(...)), + new TwigFilter('filetype', $this->filetype(...)), + new TwigFilter('is_dir', $this->is_dir(...)), + new TwigFilter('is_file', $this->is_file(...)), + new TwigFilter('is_link', $this->is_link(...)), + new TwigFilter('is_readable', $this->is_readable(...)), + new TwigFilter('is_writable', $this->is_writable(...)), + new TwigFilter('is_writeable', $this->is_writable(...)), + new TwigFilter('lstat', $this->lstat(...)), + new TwigFilter('getimagesize', $this->getimagesize(...)), + new TwigFilter('exif_read_data', $this->exif_read_data(...)), + new TwigFilter('read_exif_data', $this->exif_read_data(...)), + new TwigFilter('exif_imagetype', $this->exif_imagetype(...)), + new TwigFilter('hash_file', $this->hash_file(...)), + new TwigFilter('hash_hmac_file', $this->hash_hmac_file(...)), + new TwigFilter('md5_file', $this->md5_file(...)), + new TwigFilter('sha1_file', $this->sha1_file(...)), + new TwigFilter('get_meta_tags', $this->get_meta_tags(...)), + new TwigFilter('pathinfo', $this->pathinfo(...)), ]; } @@ -70,29 +70,29 @@ class FilesystemExtension extends AbstractExtension public function getFunctions() { return [ - new TwigFunction('file_exists', [$this, 'file_exists']), - new TwigFunction('fileatime', [$this, 'fileatime']), - new TwigFunction('filectime', [$this, 'filectime']), - new TwigFunction('filemtime', [$this, 'filemtime']), - new TwigFunction('filesize', [$this, 'filesize']), - new TwigFunction('filetype', [$this, 'filetype']), - new TwigFunction('is_dir', [$this, 'is_dir']), - new TwigFunction('is_file', [$this, 'is_file']), - new TwigFunction('is_link', [$this, 'is_link']), - new TwigFunction('is_readable', [$this, 'is_readable']), - new TwigFunction('is_writable', [$this, 'is_writable']), - new TwigFunction('is_writeable', [$this, 'is_writable']), - new TwigFunction('lstat', [$this, 'lstat']), - new TwigFunction('getimagesize', [$this, 'getimagesize']), - new TwigFunction('exif_read_data', [$this, 'exif_read_data']), - new TwigFunction('read_exif_data', [$this, 'exif_read_data']), - new TwigFunction('exif_imagetype', [$this, 'exif_imagetype']), - new TwigFunction('hash_file', [$this, 'hash_file']), - new TwigFunction('hash_hmac_file', [$this, 'hash_hmac_file']), - new TwigFunction('md5_file', [$this, 'md5_file']), - new TwigFunction('sha1_file', [$this, 'sha1_file']), - new TwigFunction('get_meta_tags', [$this, 'get_meta_tags']), - new TwigFunction('pathinfo', [$this, 'pathinfo']), + new TwigFunction('file_exists', $this->file_exists(...)), + new TwigFunction('fileatime', $this->fileatime(...)), + new TwigFunction('filectime', $this->filectime(...)), + new TwigFunction('filemtime', $this->filemtime(...)), + new TwigFunction('filesize', $this->filesize(...)), + new TwigFunction('filetype', $this->filetype(...)), + new TwigFunction('is_dir', $this->is_dir(...)), + new TwigFunction('is_file', $this->is_file(...)), + new TwigFunction('is_link', $this->is_link(...)), + new TwigFunction('is_readable', $this->is_readable(...)), + new TwigFunction('is_writable', $this->is_writable(...)), + new TwigFunction('is_writeable', $this->is_writable(...)), + new TwigFunction('lstat', $this->lstat(...)), + new TwigFunction('getimagesize', $this->getimagesize(...)), + new TwigFunction('exif_read_data', $this->exif_read_data(...)), + new TwigFunction('read_exif_data', $this->exif_read_data(...)), + new TwigFunction('exif_imagetype', $this->exif_imagetype(...)), + new TwigFunction('hash_file', $this->hash_file(...)), + new TwigFunction('hash_hmac_file', $this->hash_hmac_file(...)), + new TwigFunction('md5_file', $this->md5_file(...)), + new TwigFunction('sha1_file', $this->sha1_file(...)), + new TwigFunction('get_meta_tags', $this->get_meta_tags(...)), + new TwigFunction('pathinfo', $this->pathinfo(...)), ]; } diff --git a/system/src/Grav/Common/Twig/Extension/GravExtension.php b/system/src/Grav/Common/Twig/Extension/GravExtension.php index 8e159ac86..4fb54a97a 100644 --- a/system/src/Grav/Common/Twig/Extension/GravExtension.php +++ b/system/src/Grav/Common/Twig/Extension/GravExtension.php @@ -109,72 +109,72 @@ class GravExtension extends AbstractExtension implements GlobalsInterface public function getFilters(): array { return [ - new TwigFilter('*ize', [$this, 'inflectorFilter']), - new TwigFilter('absolute_url', [$this, 'absoluteUrlFilter']), - new TwigFilter('contains', [$this, 'containsFilter']), - new TwigFilter('chunk_split', [$this, 'chunkSplitFilter']), - new TwigFilter('nicenumber', [$this, 'niceNumberFunc']), - new TwigFilter('nicefilesize', [$this, 'niceFilesizeFunc']), - new TwigFilter('nicetime', [$this, 'nicetimeFunc']), - new TwigFilter('defined', [$this, 'definedDefaultFilter']), - new TwigFilter('ends_with', [$this, 'endsWithFilter']), - new TwigFilter('fieldName', [$this, 'fieldNameFilter']), - new TwigFilter('parent_field', [$this, 'fieldParentFilter']), - new TwigFilter('ksort', [$this, 'ksortFilter']), - new TwigFilter('ltrim', [$this, 'ltrimFilter']), - new TwigFilter('markdown', [$this, 'markdownFunction'], ['needs_context' => true, 'is_safe' => ['html']]), - new TwigFilter('md5', [$this, 'md5Filter']), - new TwigFilter('base32_encode', [$this, 'base32EncodeFilter']), - new TwigFilter('base32_decode', [$this, 'base32DecodeFilter']), - new TwigFilter('base64_encode', [$this, 'base64EncodeFilter']), - new TwigFilter('base64_decode', [$this, 'base64DecodeFilter']), - new TwigFilter('randomize', [$this, 'randomizeFilter']), - new TwigFilter('modulus', [$this, 'modulusFilter']), - new TwigFilter('rtrim', [$this, 'rtrimFilter']), - new TwigFilter('pad', [$this, 'padFilter']), - new TwigFilter('regex_replace', [$this, 'regexReplace']), - new TwigFilter('safe_email', [$this, 'safeEmailFilter'], ['is_safe' => ['html']]), - new TwigFilter('safe_truncate', [Utils::class, 'safeTruncate']), - new TwigFilter('safe_truncate_html', [Utils::class, 'safeTruncateHTML']), - new TwigFilter('sort_by_key', [$this, 'sortByKeyFilter']), - new TwigFilter('starts_with', [$this, 'startsWithFilter']), - new TwigFilter('truncate', [Utils::class, 'truncate']), - new TwigFilter('truncate_html', [Utils::class, 'truncateHTML']), - new TwigFilter('json_decode', [$this, 'jsonDecodeFilter']), + new TwigFilter('*ize', $this->inflectorFilter(...)), + new TwigFilter('absolute_url', $this->absoluteUrlFilter(...)), + new TwigFilter('contains', $this->containsFilter(...)), + new TwigFilter('chunk_split', $this->chunkSplitFilter(...)), + new TwigFilter('nicenumber', $this->niceNumberFunc(...)), + new TwigFilter('nicefilesize', $this->niceFilesizeFunc(...)), + new TwigFilter('nicetime', $this->nicetimeFunc(...)), + new TwigFilter('defined', $this->definedDefaultFilter(...)), + new TwigFilter('ends_with', $this->endsWithFilter(...)), + new TwigFilter('fieldName', $this->fieldNameFilter(...)), + new TwigFilter('parent_field', $this->fieldParentFilter(...)), + new TwigFilter('ksort', $this->ksortFilter(...)), + new TwigFilter('ltrim', $this->ltrimFilter(...)), + new TwigFilter('markdown', $this->markdownFunction(...), ['needs_context' => true, 'is_safe' => ['html']]), + new TwigFilter('md5', $this->md5Filter(...)), + new TwigFilter('base32_encode', $this->base32EncodeFilter(...)), + new TwigFilter('base32_decode', $this->base32DecodeFilter(...)), + new TwigFilter('base64_encode', $this->base64EncodeFilter(...)), + new TwigFilter('base64_decode', $this->base64DecodeFilter(...)), + new TwigFilter('randomize', $this->randomizeFilter(...)), + new TwigFilter('modulus', $this->modulusFilter(...)), + new TwigFilter('rtrim', $this->rtrimFilter(...)), + new TwigFilter('pad', $this->padFilter(...)), + new TwigFilter('regex_replace', $this->regexReplace(...)), + new TwigFilter('safe_email', $this->safeEmailFilter(...), ['is_safe' => ['html']]), + new TwigFilter('safe_truncate', Utils::safeTruncate(...)), + new TwigFilter('safe_truncate_html', Utils::safeTruncateHTML(...)), + new TwigFilter('sort_by_key', $this->sortByKeyFilter(...)), + new TwigFilter('starts_with', $this->startsWithFilter(...)), + new TwigFilter('truncate', Utils::truncate(...)), + new TwigFilter('truncate_html', Utils::truncateHTML(...)), + new TwigFilter('json_decode', $this->jsonDecodeFilter(...)), new TwigFilter('array_unique', 'array_unique'), new TwigFilter('basename', 'basename'), new TwigFilter('dirname', 'dirname'), - new TwigFilter('print_r', [$this, 'print_r']), - new TwigFilter('yaml_encode', [$this, 'yamlEncodeFilter']), - new TwigFilter('yaml_decode', [$this, 'yamlDecodeFilter']), - new TwigFilter('nicecron', [$this, 'niceCronFilter']), - new TwigFilter('replace_last', [$this, 'replaceLastFilter']), + new TwigFilter('print_r', $this->print_r(...)), + new TwigFilter('yaml_encode', $this->yamlEncodeFilter(...)), + new TwigFilter('yaml_decode', $this->yamlDecodeFilter(...)), + new TwigFilter('nicecron', $this->niceCronFilter(...)), + new TwigFilter('replace_last', $this->replaceLastFilter(...)), // Translations - new TwigFilter('t', [$this, 'translate'], ['needs_environment' => true]), - new TwigFilter('tl', [$this, 'translateLanguage']), - new TwigFilter('ta', [$this, 'translateArray']), + new TwigFilter('t', $this->translate(...), ['needs_environment' => true]), + new TwigFilter('tl', $this->translateLanguage(...)), + new TwigFilter('ta', $this->translateArray(...)), // Casting values - new TwigFilter('string', [$this, 'stringFilter']), - new TwigFilter('int', [$this, 'intFilter'], ['is_safe' => ['all']]), - new TwigFilter('bool', [$this, 'boolFilter']), - new TwigFilter('float', [$this, 'floatFilter'], ['is_safe' => ['all']]), - new TwigFilter('array', [$this, 'arrayFilter']), - new TwigFilter('yaml', [$this, 'yamlFilter']), + new TwigFilter('string', $this->stringFilter(...)), + new TwigFilter('int', $this->intFilter(...), ['is_safe' => ['all']]), + new TwigFilter('bool', $this->boolFilter(...)), + new TwigFilter('float', $this->floatFilter(...), ['is_safe' => ['all']]), + new TwigFilter('array', $this->arrayFilter(...)), + new TwigFilter('yaml', $this->yamlFilter(...)), // Object Types - new TwigFilter('get_type', [$this, 'getTypeFunc']), - new TwigFilter('of_type', [$this, 'ofTypeFunc']), + new TwigFilter('get_type', $this->getTypeFunc(...)), + new TwigFilter('of_type', $this->ofTypeFunc(...)), // PHP methods new TwigFilter('count', 'count'), new TwigFilter('array_diff', 'array_diff'), // Security fixes - new TwigFilter('filter', [$this, 'filterFunc'], ['needs_environment' => true]), - new TwigFilter('map', [$this, 'mapFunc'], ['needs_environment' => true]), - new TwigFilter('reduce', [$this, 'reduceFunc'], ['needs_environment' => true]), + new TwigFilter('filter', $this->filterFunc(...), ['needs_environment' => true]), + new TwigFilter('map', $this->mapFunc(...), ['needs_environment' => true]), + new TwigFilter('reduce', $this->reduceFunc(...), ['needs_environment' => true]), ]; } @@ -186,59 +186,59 @@ class GravExtension extends AbstractExtension implements GlobalsInterface public function getFunctions(): array { return [ - new TwigFunction('array', [$this, 'arrayFilter']), - new TwigFunction('array_key_value', [$this, 'arrayKeyValueFunc']), + new TwigFunction('array', $this->arrayFilter(...)), + new TwigFunction('array_key_value', $this->arrayKeyValueFunc(...)), new TwigFunction('array_key_exists', 'array_key_exists'), new TwigFunction('array_unique', 'array_unique'), - new TwigFunction('array_intersect', [$this, 'arrayIntersectFunc']), + new TwigFunction('array_intersect', $this->arrayIntersectFunc(...)), new TwigFunction('array_diff', 'array_diff'), - new TwigFunction('authorize', [$this, 'authorize']), - new TwigFunction('debug', [$this, 'dump'], ['needs_context' => true, 'needs_environment' => true]), - new TwigFunction('dump', [$this, 'dump'], ['needs_context' => true, 'needs_environment' => true]), - new TwigFunction('vardump', [$this, 'vardumpFunc']), - new TwigFunction('print_r', [$this, 'print_r']), + new TwigFunction('authorize', $this->authorize(...)), + new TwigFunction('debug', $this->dump(...), ['needs_context' => true, 'needs_environment' => true]), + new TwigFunction('dump', $this->dump(...), ['needs_context' => true, 'needs_environment' => true]), + new TwigFunction('vardump', $this->vardumpFunc(...)), + new TwigFunction('print_r', $this->print_r(...)), new TwigFunction('http_response_code', 'http_response_code'), - new TwigFunction('evaluate', [$this, 'evaluateStringFunc'], ['needs_context' => true]), - new TwigFunction('evaluate_twig', [$this, 'evaluateTwigFunc'], ['needs_context' => true]), - new TwigFunction('gist', [$this, 'gistFunc']), - new TwigFunction('nonce_field', [$this, 'nonceFieldFunc']), + new TwigFunction('evaluate', $this->evaluateStringFunc(...), ['needs_context' => true]), + new TwigFunction('evaluate_twig', $this->evaluateTwigFunc(...), ['needs_context' => true]), + new TwigFunction('gist', $this->gistFunc(...)), + new TwigFunction('nonce_field', $this->nonceFieldFunc(...)), new TwigFunction('pathinfo', 'pathinfo'), new TwigFunction('parseurl', 'parse_url'), - new TwigFunction('random_string', [$this, 'randomStringFunc']), - new TwigFunction('repeat', [$this, 'repeatFunc']), - new TwigFunction('regex_replace', [$this, 'regexReplace']), - new TwigFunction('regex_filter', [$this, 'regexFilter']), - new TwigFunction('regex_match', [$this, 'regexMatch']), - new TwigFunction('regex_split', [$this, 'regexSplit']), - new TwigFunction('string', [$this, 'stringFilter']), - new TwigFunction('url', [$this, 'urlFunc']), - new TwigFunction('json_decode', [$this, 'jsonDecodeFilter']), - new TwigFunction('get_cookie', [$this, 'getCookie']), - new TwigFunction('redirect_me', [$this, 'redirectFunc']), - new TwigFunction('range', [$this, 'rangeFunc']), - new TwigFunction('isajaxrequest', [$this, 'isAjaxFunc']), - new TwigFunction('exif', [$this, 'exifFunc']), - new TwigFunction('media_directory', [$this, 'mediaDirFunc']), - new TwigFunction('body_class', [$this, 'bodyClassFunc'], ['needs_context' => true]), - new TwigFunction('theme_var', [$this, 'themeVarFunc'], ['needs_context' => true]), - new TwigFunction('header_var', [$this, 'pageHeaderVarFunc'], ['needs_context' => true]), - new TwigFunction('read_file', [$this, 'readFileFunc']), - new TwigFunction('nicenumber', [$this, 'niceNumberFunc']), - new TwigFunction('nicefilesize', [$this, 'niceFilesizeFunc']), - new TwigFunction('nicetime', [$this, 'nicetimeFunc']), - new TwigFunction('cron', [$this, 'cronFunc']), - new TwigFunction('svg_image', [$this, 'svgImageFunction']), - new TwigFunction('xss', [$this, 'xssFunc']), - new TwigFunction('unique_id', [$this, 'uniqueId']), + new TwigFunction('random_string', $this->randomStringFunc(...)), + new TwigFunction('repeat', $this->repeatFunc(...)), + new TwigFunction('regex_replace', $this->regexReplace(...)), + new TwigFunction('regex_filter', $this->regexFilter(...)), + new TwigFunction('regex_match', $this->regexMatch(...)), + new TwigFunction('regex_split', $this->regexSplit(...)), + new TwigFunction('string', $this->stringFilter(...)), + new TwigFunction('url', $this->urlFunc(...)), + new TwigFunction('json_decode', $this->jsonDecodeFilter(...)), + new TwigFunction('get_cookie', $this->getCookie(...)), + new TwigFunction('redirect_me', $this->redirectFunc(...)), + new TwigFunction('range', $this->rangeFunc(...)), + new TwigFunction('isajaxrequest', $this->isAjaxFunc(...)), + new TwigFunction('exif', $this->exifFunc(...)), + new TwigFunction('media_directory', $this->mediaDirFunc(...)), + new TwigFunction('body_class', $this->bodyClassFunc(...), ['needs_context' => true]), + new TwigFunction('theme_var', $this->themeVarFunc(...), ['needs_context' => true]), + new TwigFunction('header_var', $this->pageHeaderVarFunc(...), ['needs_context' => true]), + new TwigFunction('read_file', $this->readFileFunc(...)), + new TwigFunction('nicenumber', $this->niceNumberFunc(...)), + new TwigFunction('nicefilesize', $this->niceFilesizeFunc(...)), + new TwigFunction('nicetime', $this->nicetimeFunc(...)), + new TwigFunction('cron', $this->cronFunc(...)), + new TwigFunction('svg_image', $this->svgImageFunction(...)), + new TwigFunction('xss', $this->xssFunc(...)), + new TwigFunction('unique_id', $this->uniqueId(...)), // Translations - new TwigFunction('t', [$this, 'translate'], ['needs_environment' => true]), - new TwigFunction('tl', [$this, 'translateLanguage']), - new TwigFunction('ta', [$this, 'translateArray']), + new TwigFunction('t', $this->translate(...), ['needs_environment' => true]), + new TwigFunction('tl', $this->translateLanguage(...)), + new TwigFunction('ta', $this->translateArray(...)), // Object Types - new TwigFunction('get_type', [$this, 'getTypeFunc']), - new TwigFunction('of_type', [$this, 'ofTypeFunc']), + new TwigFunction('get_type', $this->getTypeFunc(...)), + new TwigFunction('of_type', $this->ofTypeFunc(...)), // PHP methods new TwigFunction('is_numeric', 'is_numeric'), @@ -253,9 +253,9 @@ class GravExtension extends AbstractExtension implements GlobalsInterface new TwigFunction('parse_url', 'parse_url'), // Security fixes - new TwigFunction('filter', [$this, 'filterFunc'], ['needs_environment' => true]), - new TwigFunction('map', [$this, 'mapFunc'], ['needs_environment' => true]), - new TwigFunction('reduce', [$this, 'reduceFunc'], ['needs_environment' => true]), + new TwigFunction('filter', $this->filterFunc(...), ['needs_environment' => true]), + new TwigFunction('map', $this->mapFunc(...), ['needs_environment' => true]), + new TwigFunction('reduce', $this->reduceFunc(...), ['needs_environment' => true]), ]; } @@ -278,10 +278,9 @@ class GravExtension extends AbstractExtension implements GlobalsInterface } /** - * @param mixed $var * @return string */ - public function print_r($var) + public function print_r(mixed $var) { return print_r($var, true); } @@ -548,7 +547,7 @@ class GravExtension extends AbstractExtension implements GlobalsInterface return $haystack; } - return (strpos($haystack, (string) $needle) !== false); + return (str_contains($haystack, (string) $needle)); } /** @@ -700,9 +699,7 @@ class GravExtension extends AbstractExtension implements GlobalsInterface } $results = Security::detectXssFromArray($data); - $results_parts = array_map(static function ($value, $key) { - return $key.': \''.$value . '\''; - }, array_values($results), array_keys($results)); + $results_parts = array_map(static fn($value, $key) => $key.': \''.$value . '\'', array_values($results), array_keys($results)); return implode(', ', $results_parts); } @@ -766,11 +763,10 @@ class GravExtension extends AbstractExtension implements GlobalsInterface } /** - * @param mixed $value * @param null $default * @return mixed|null */ - public function definedDefaultFilter($value, $default = null) + public function definedDefaultFilter(mixed $value, $default = null) { return $value ?? $default; } @@ -798,10 +794,9 @@ class GravExtension extends AbstractExtension implements GlobalsInterface /** * Returns a string from a value. If the value is array, return it json encoded * - * @param mixed $value * @return string */ - public function stringFilter($value) + public function stringFilter(mixed $value) { // Format the array as a string if (is_array($value)) { @@ -820,10 +815,9 @@ class GravExtension extends AbstractExtension implements GlobalsInterface /** * Casts input to int. * - * @param mixed $input * @return int */ - public function intFilter($input) + public function intFilter(mixed $input) { return (int) $input; } @@ -831,10 +825,9 @@ class GravExtension extends AbstractExtension implements GlobalsInterface /** * Casts input to bool. * - * @param mixed $input * @return bool */ - public function boolFilter($input) + public function boolFilter(mixed $input) { return (bool) $input; } @@ -842,10 +835,9 @@ class GravExtension extends AbstractExtension implements GlobalsInterface /** * Casts input to float. * - * @param mixed $input * @return float */ - public function floatFilter($input) + public function floatFilter(mixed $input) { return (float) $input; } @@ -853,10 +845,9 @@ class GravExtension extends AbstractExtension implements GlobalsInterface /** * Casts input to array. * - * @param mixed $input * @return array */ - public function arrayFilter($input) + public function arrayFilter(mixed $input) { if (is_array($input)) { return $input; @@ -1034,7 +1025,7 @@ class GravExtension extends AbstractExtension implements GlobalsInterface if (method_exists($value, 'toArray')) { $data[$key] = $value->toArray(); } else { - $data[$key] = 'Object (' . get_class($value) . ')'; + $data[$key] = 'Object (' . $value::class . ')'; } } else { $data[$key] = $value; @@ -1102,7 +1093,7 @@ class GravExtension extends AbstractExtension implements GlobalsInterface public function arrayKeyValueFunc($key, $val, $current_array = null) { if (empty($current_array)) { - return array($key => $val); + return [$key => $val]; } $current_array[$key] = $val; @@ -1337,7 +1328,7 @@ class GravExtension extends AbstractExtension implements GlobalsInterface { return ( !empty($_SERVER['HTTP_X_REQUESTED_WITH']) - && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'); + && strtolower((string) $_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'); } /** @@ -1422,10 +1413,9 @@ class GravExtension extends AbstractExtension implements GlobalsInterface /** * Dump a variable to the browser * - * @param mixed $var * @return void */ - public function vardumpFunc($var) + public function vardumpFunc(mixed $var) { dump($var); } @@ -1497,7 +1487,7 @@ class GravExtension extends AbstractExtension implements GlobalsInterface */ public function themeVarFunc($context, $var, $default = null, $page = null, $exists = false) { - $page = $page ?? $context['page'] ?? Grav::instance()['page'] ?? null; + $page ??= $context['page'] ?? Grav::instance()['page'] ?? null; // Try to find var in the page headers if ($page instanceof PageInterface && $page->exists()) { @@ -1591,7 +1581,7 @@ class GravExtension extends AbstractExtension implements GlobalsInterface //Strip style if needed if ($strip_style) { - $svg = preg_replace('//s', '', $svg); + $svg = preg_replace('//s', '', (string) $svg); } //Look for existing class @@ -1602,7 +1592,7 @@ class GravExtension extends AbstractExtension implements GlobalsInterface return str_replace($matches[1], "class=\"$new_classes\"", $matches[0]); } return $matches[0]; - }, $svg + }, (string) $svg ); // no matches found just add the class @@ -1611,7 +1601,7 @@ class GravExtension extends AbstractExtension implements GlobalsInterface $svg = str_replace(' is_array($var), + 'bool' => is_bool($var), + 'class' => is_object($var) === true && $var::class === $className, + 'float' => is_float($var), + 'int' => is_int($var), + 'numeric' => is_numeric($var), + 'object' => is_object($var), + 'scalar' => is_scalar($var), + 'string' => is_string($var), + default => false, + }; } /** diff --git a/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserCache.php b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserCache.php index 831abf089..d416a2ac7 100644 --- a/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserCache.php +++ b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserCache.php @@ -55,7 +55,7 @@ class TwigTokenParserCache extends AbstractTokenParser $stream->expect(Token::BLOCK_END_TYPE); // Parse the content inside the cache block - $body = $this->parser->subparse([$this, 'decideCacheEnd'], true); + $body = $this->parser->subparse($this->decideCacheEnd(...), true); $stream->expect(Token::BLOCK_END_TYPE); diff --git a/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserMarkdown.php b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserMarkdown.php index 581df504e..420cf23b8 100644 --- a/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserMarkdown.php +++ b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserMarkdown.php @@ -35,7 +35,7 @@ class TwigTokenParserMarkdown extends AbstractTokenParser { $lineno = $token->getLine(); $this->parser->getStream()->expect(Token::BLOCK_END_TYPE); - $body = $this->parser->subparse([$this, 'decideMarkdownEnd'], true); + $body = $this->parser->subparse($this->decideMarkdownEnd(...), true); $this->parser->getStream()->expect(Token::BLOCK_END_TYPE); return new TwigNodeMarkdown($body, $lineno, $this->getTag()); } diff --git a/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserScript.php b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserScript.php index 073d93db5..e5dd8ae56 100644 --- a/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserScript.php +++ b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserScript.php @@ -48,7 +48,7 @@ class TwigTokenParserScript extends AbstractTokenParser $content = null; if ($file === null) { - $content = $this->parser->subparse([$this, 'decideBlockEnd'], true); + $content = $this->parser->subparse($this->decideBlockEnd(...), true); $stream->expect(Token::BLOCK_END_TYPE); } diff --git a/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserStyle.php b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserStyle.php index 590394d54..7f0710cb1 100644 --- a/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserStyle.php +++ b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserStyle.php @@ -41,7 +41,7 @@ class TwigTokenParserStyle extends AbstractTokenParser $content = null; if (!$file) { - $content = $this->parser->subparse([$this, 'decideBlockEnd'], true); + $content = $this->parser->subparse($this->decideBlockEnd(...), true); $stream->expect(Token::BLOCK_END_TYPE); } diff --git a/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserSwitch.php b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserSwitch.php index c2806f8f8..6946d102a 100644 --- a/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserSwitch.php +++ b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserSwitch.php @@ -74,7 +74,7 @@ class TwigTokenParserSwitch extends AbstractTokenParser } $stream->expect(Token::BLOCK_END_TYPE); - $body = $this->parser->subparse([$this, 'decideIfFork']); + $body = $this->parser->subparse($this->decideIfFork(...)); $cases[] = new Node([ 'values' => new Node($values), 'body' => $body @@ -83,7 +83,7 @@ class TwigTokenParserSwitch extends AbstractTokenParser case 'default': $stream->expect(Token::BLOCK_END_TYPE); - $default = $this->parser->subparse([$this, 'decideIfEnd']); + $default = $this->parser->subparse($this->decideIfEnd(...)); break; case 'endswitch': diff --git a/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserTryCatch.php b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserTryCatch.php index dcb183bd0..410745399 100644 --- a/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserTryCatch.php +++ b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserTryCatch.php @@ -41,10 +41,10 @@ class TwigTokenParserTryCatch extends AbstractTokenParser $stream = $this->parser->getStream(); $stream->expect(Token::BLOCK_END_TYPE); - $try = $this->parser->subparse([$this, 'decideCatch']); + $try = $this->parser->subparse($this->decideCatch(...)); $stream->next(); $stream->expect(Token::BLOCK_END_TYPE); - $catch = $this->parser->subparse([$this, 'decideEnd']); + $catch = $this->parser->subparse($this->decideEnd(...)); $stream->next(); $stream->expect(Token::BLOCK_END_TYPE); diff --git a/system/src/Grav/Common/Twig/Twig.php b/system/src/Grav/Common/Twig/Twig.php index 45f54b3a4..1927477a8 100644 --- a/system/src/Grav/Common/Twig/Twig.php +++ b/system/src/Grav/Common/Twig/Twig.php @@ -45,13 +45,13 @@ use function is_array; // Twig3 compatibility if (!class_exists('Twig_SimpleFunction')) { - class_alias('\Twig\TwigFunction', 'Twig_SimpleFunction'); + class_alias(\Twig\TwigFunction::class, 'Twig_SimpleFunction'); } if (!class_exists('Twig_SimpleFilter')) { - class_alias('\Twig\TwigFilter', 'Twig_SimpleFilter'); + class_alias(\Twig\TwigFilter::class, 'Twig_SimpleFilter'); } if (!class_exists('Twig_Extension')) { - class_alias('\Twig\Extension\AbstractExtension', 'Twig_Extension'); + class_alias(\Twig\Extension\AbstractExtension::class, 'Twig_Extension'); } /** @@ -330,7 +330,7 @@ class Twig */ public function processPage(PageInterface $item, $content = null) { - $content = $content ?? $item->content(); + $content ??= $item->content(); $content = Security::cleanDangerousTwig($content); // override the twig header vars for local resolution @@ -580,7 +580,7 @@ class Twig public function setAutoescape($state) { if (!$state) { - user_error(__CLASS__ . '::' . __FUNCTION__ . '(false) is deprecated since Grav 1.5', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '(false) is deprecated since Grav 1.5', E_USER_DEPRECATED); } $this->autoescape = (bool) $state; diff --git a/system/src/Grav/Common/Uri.php b/system/src/Grav/Common/Uri.php index dcd9c27a8..3e8884da7 100644 --- a/system/src/Grav/Common/Uri.php +++ b/system/src/Grav/Common/Uri.php @@ -30,7 +30,7 @@ use function strlen; * Class Uri * @package Grav\Common */ -class Uri +class Uri implements \Stringable { const HOSTNAME_REGEX = '/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/'; @@ -165,7 +165,7 @@ class Uri } // Handle custom base - $custom_base = rtrim($grav['config']->get('system.custom_base_url', ''), '/'); + $custom_base = rtrim((string) $grav['config']->get('system.custom_base_url', ''), '/'); if ($custom_base) { $custom_parts = parse_url($custom_base); if ($custom_parts === false) { @@ -195,7 +195,7 @@ class Uri // remove the setup.php based base if set: $setup_base = $grav['pages']->base(); if ($setup_base) { - $uri = preg_replace('|^' . preg_quote($setup_base, '|') . '|', '', $uri); + $uri = preg_replace('|^' . preg_quote((string) $setup_base, '|') . '|', '', $uri); } $this->setup_base = $setup_base; @@ -345,7 +345,7 @@ class Uri public function param($id, $default = false) { if (isset($this->params[$id])) { - return html_entity_decode(rawurldecode($this->params[$id]), ENT_COMPAT | ENT_HTML401, 'UTF-8'); + return html_entity_decode(rawurldecode((string) $this->params[$id]), ENT_COMPAT | ENT_HTML401, 'UTF-8'); } return $default; @@ -412,10 +412,10 @@ class Uri */ public function method() { - $method = isset($_SERVER['REQUEST_METHOD']) ? strtoupper($_SERVER['REQUEST_METHOD']) : 'GET'; + $method = isset($_SERVER['REQUEST_METHOD']) ? strtoupper((string) $_SERVER['REQUEST_METHOD']) : 'GET'; if ($method === 'POST' && isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) { - $method = strtoupper($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']); + $method = strtoupper((string) $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']); } return $method; @@ -625,7 +625,7 @@ class Uri * @return string */ #[\ReturnTypeWillChange] - public function __toString() + public function __toString(): string { return static::buildUrl($this->toArray()); } @@ -743,7 +743,7 @@ class Uri */ public static function isExternal($url) { - return (0 === strpos($url, 'http://') || 0 === strpos($url, 'https://') || 0 === strpos($url, '//') || 0 === strpos($url, 'mailto:') || 0 === strpos($url, 'tel:') || 0 === strpos($url, 'ftp://') || 0 === strpos($url, 'ftps://') || 0 === strpos($url, 'news:') || 0 === strpos($url, 'irc:') || 0 === strpos($url, 'gopher:') || 0 === strpos($url, 'nntp:') || 0 === strpos($url, 'feed:') || 0 === strpos($url, 'cvs:') || 0 === strpos($url, 'ssh:') || 0 === strpos($url, 'git:') || 0 === strpos($url, 'svn:') || 0 === strpos($url, 'hg:')); + return (str_starts_with($url, 'http://') || str_starts_with($url, 'https://') || str_starts_with($url, '//') || str_starts_with($url, 'mailto:') || str_starts_with($url, 'tel:') || str_starts_with($url, 'ftp://') || str_starts_with($url, 'ftps://') || str_starts_with($url, 'news:') || str_starts_with($url, 'irc:') || str_starts_with($url, 'gopher:') || str_starts_with($url, 'nntp:') || str_starts_with($url, 'feed:') || str_starts_with($url, 'cvs:') || str_starts_with($url, 'ssh:') || str_starts_with($url, 'git:') || str_starts_with($url, 'svn:') || str_starts_with($url, 'hg:')); } /** @@ -762,7 +762,7 @@ class Uri $pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : ''; $pass = ($user || $pass) ? "{$pass}@" : ''; $path = $parsed_url['path'] ?? ''; - $path = !empty($parsed_url['params']) ? rtrim($path, '/') . static::buildParams($parsed_url['params']) : $path; + $path = !empty($parsed_url['params']) ? rtrim((string) $path, '/') . static::buildParams($parsed_url['params']) : $path; $query = !empty($parsed_url['query']) ? '?' . $parsed_url['query'] : ''; $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : ''; @@ -835,7 +835,7 @@ class Uri $normalized_path = Utils::normalizePath($pages_dir . $url_path); } else { $page_route = ($page->home() && !empty($url_path)) ? $page->rawRoute() : $page->route(); - $normalized_url = $base_url . Utils::normalizePath(rtrim($page_route, '/') . '/' . $url_path); + $normalized_url = $base_url . Utils::normalizePath(rtrim((string) $page_route, '/') . '/' . $url_path); $normalized_path = Utils::normalizePath($page->path() . '/' . $url_path); } @@ -846,7 +846,7 @@ class Uri } else { $url_bits = static::parseUrl($normalized_path); $full_path = $url_bits['path']; - $raw_full_path = rawurldecode($full_path); + $raw_full_path = rawurldecode((string) $full_path); if (file_exists($raw_full_path)) { $full_path = $raw_full_path; @@ -877,7 +877,7 @@ class Uri if (isset($instances[$page_path])) { /** @var PageInterface $target */ $target = $instances[$page_path]; - $url_bits['path'] = $base_url . rtrim($target->route(), '/') . $filename; + $url_bits['path'] = $base_url . rtrim((string) $target->route(), '/') . $filename; $url_path = Uri::buildUrl($url_bits); } else { @@ -959,13 +959,11 @@ class Uri $encodedUrl = preg_replace_callback( '%[^:/@?&=#]+%usD', - static function ($matches) { - return rawurlencode($matches[0]); - }, - $url + static fn($matches) => rawurlencode((string) $matches[0]), + (string) $url ); - $parts = parse_url($encodedUrl); + $parts = parse_url((string) $encodedUrl); if (false === $parts) { return false; @@ -998,7 +996,7 @@ class Uri { $params = []; - if (strpos($uri, $delimiter) !== false) { + if (str_contains($uri, $delimiter)) { preg_match_all(static::paramsRegex(), $uri, $matches, PREG_SET_ORDER); foreach ($matches as $match) { @@ -1106,7 +1104,7 @@ class Uri if (isset($instances[$page_path])) { /** @var PageInterface $target */ $target = $instances[$page_path]; - $url_bits['path'] = $base_url . rtrim($target->route(), '/') . $filename; + $url_bits['path'] = $base_url . rtrim((string) $target->route(), '/') . $filename; return static::buildUrl($url_bits); } @@ -1125,7 +1123,7 @@ class Uri */ public static function addNonce($url, $action, $nonceParamName = 'nonce') { - $fake = $url && strpos($url, '/') === 0; + $fake = $url && str_starts_with($url, '/'); if ($fake) { $url = 'http://domain.com' . $url; @@ -1226,7 +1224,7 @@ class Uri $this->scheme = $env['REQUEST_SCHEME']; } else { $https = $env['HTTPS'] ?? ''; - $this->scheme = (empty($https) || strtolower($https) === 'off') ? 'http' : 'https'; + $this->scheme = (empty($https) || strtolower((string) $https) === 'off') ? 'http' : 'https'; } // Build user and password. @@ -1278,8 +1276,8 @@ class Uri } // Support ngnix routes. - if (strpos($this->query, '_url=') === 0) { - parse_str($this->query, $query); + if (str_starts_with((string) $this->query, '_url=')) { + parse_str((string) $this->query, $query); unset($query['_url']); $this->query = http_build_query($query); } @@ -1388,7 +1386,7 @@ class Uri $item = Utils::getDotNotation($this->post, $element); if ($filter_type) { if ($filter_type === FILTER_SANITIZE_STRING || $filter_type === GRAV_SANITIZE_STRING) { - $item = htmlspecialchars(strip_tags($item), ENT_QUOTES, 'UTF-8'); + $item = htmlspecialchars(strip_tags((string) $item), ENT_QUOTES, 'UTF-8'); } else { $item = filter_var($item, $filter_type); } @@ -1455,7 +1453,7 @@ class Uri if (!function_exists('getallheaders')) { $headers = []; foreach ($_SERVER as $name => $value) { - if (substr($name, 0, 5) == 'HTTP_') { + if (str_starts_with($name, 'HTTP_')) { $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value; } } @@ -1510,7 +1508,7 @@ class Uri */ private function processParams(string $uri, string $delimiter = ':'): string { - if (strpos($uri, $delimiter) !== false) { + if (str_contains($uri, $delimiter)) { preg_match_all(static::paramsRegex(), $uri, $matches, PREG_SET_ORDER); foreach ($matches as $match) { diff --git a/system/src/Grav/Common/User/DataUser/User.php b/system/src/Grav/Common/User/DataUser/User.php index 8a4ac2ae4..d4d1dd45f 100644 --- a/system/src/Grav/Common/User/DataUser/User.php +++ b/system/src/Grav/Common/User/DataUser/User.php @@ -122,7 +122,7 @@ class User extends Data implements UserInterface /** @var CompiledYamlFile|null $file */ $file = $this->file(); if (!$file || !$file->filename()) { - user_error(__CLASS__ . ': calling \$user = new ' . __CLASS__ . "() is deprecated since Grav 1.6, use \$grav['accounts']->load(\$username) or \$grav['accounts']->load('') instead", E_USER_DEPRECATED); + user_error(self::class . ': calling \$user = new ' . self::class . "() is deprecated since Grav 1.6, use \$grav['accounts']->load(\$username) or \$grav['accounts']->load('') instead", E_USER_DEPRECATED); } if ($file) { @@ -244,7 +244,7 @@ class User extends Data implements UserInterface */ public function merge(array $data) { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use ->update($data) method instead', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use ->update($data) method instead', E_USER_DEPRECATED); return $this->update($data); } @@ -257,7 +257,7 @@ class User extends Data implements UserInterface */ public function getAvatarMedia() { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use getAvatarImage() method instead', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use getAvatarImage() method instead', E_USER_DEPRECATED); return $this->getAvatarImage(); } @@ -270,7 +270,7 @@ class User extends Data implements UserInterface */ public function avatarUrl() { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use getAvatarUrl() method instead', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use getAvatarUrl() method instead', E_USER_DEPRECATED); return $this->getAvatarUrl(); } @@ -285,7 +285,7 @@ class User extends Data implements UserInterface */ public function authorise($action) { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use authorize() method instead', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use authorize() method instead', E_USER_DEPRECATED); return $this->authorize($action) ?? false; } @@ -299,7 +299,7 @@ class User extends Data implements UserInterface #[\ReturnTypeWillChange] public function count() { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6', E_USER_DEPRECATED); return parent::count(); } diff --git a/system/src/Grav/Common/User/DataUser/UserCollection.php b/system/src/Grav/Common/User/DataUser/UserCollection.php index 3db16d379..b214adf69 100644 --- a/system/src/Grav/Common/User/DataUser/UserCollection.php +++ b/system/src/Grav/Common/User/DataUser/UserCollection.php @@ -27,16 +27,12 @@ use function is_string; */ class UserCollection implements UserCollectionInterface { - /** @var string */ - private $className; - /** * UserCollection constructor. * @param string $className */ - public function __construct(string $className) + public function __construct(private readonly string $className) { - $this->className = $className; } /** @@ -117,7 +113,7 @@ class UserCollection implements UserCollectionInterface if (Utils::endsWith($file, YAML_EXT)) { $find_user = $this->load(trim(Utils::pathinfo($file, PATHINFO_FILENAME))); foreach ($fields as $field) { - if (isset($find_user[$field]) && mb_strtolower($find_user[$field]) === $query) { + if (isset($find_user[$field]) && mb_strtolower((string) $find_user[$field]) === $query) { return $find_user; } } diff --git a/system/src/Grav/Common/User/Interfaces/UserInterface.php b/system/src/Grav/Common/User/Interfaces/UserInterface.php index 6b657bf3f..99844387f 100644 --- a/system/src/Grav/Common/User/Interfaces/UserInterface.php +++ b/system/src/Grav/Common/User/Interfaces/UserInterface.php @@ -48,7 +48,7 @@ interface UserInterface extends AuthorizeInterface, DataInterface, MediaInterfac * @param string|null $separator Separator, defaults to '.' * @return mixed Value. */ - public function get($name, $default = null, $separator = null); + public function get($name, mixed $default = null, $separator = null); /** * Set value by using dot notation for nested arrays/objects. @@ -60,7 +60,7 @@ interface UserInterface extends AuthorizeInterface, DataInterface, MediaInterfac * @param string|null $separator Separator, defaults to '.' * @return $this */ - public function set($name, $value, $separator = null); + public function set($name, mixed $value, $separator = null); /** * Unset value by using dot notation for nested arrays/objects. @@ -83,7 +83,7 @@ interface UserInterface extends AuthorizeInterface, DataInterface, MediaInterfac * @param string|null $separator Separator, defaults to '.' * @return $this */ - public function def($name, $default = null, $separator = null); + public function def($name, mixed $default = null, $separator = null); /** * Join nested values together by using blueprints. @@ -94,7 +94,7 @@ interface UserInterface extends AuthorizeInterface, DataInterface, MediaInterfac * @return $this * @throws RuntimeException */ - public function join($name, $value, $separator = '.'); + public function join($name, mixed $value, $separator = '.'); /** * Get nested structure containing default values defined in the blueprints. @@ -113,7 +113,7 @@ interface UserInterface extends AuthorizeInterface, DataInterface, MediaInterfac * @param string $separator Separator, defaults to '.' * @return $this */ - public function joinDefaults($name, $value, $separator = '.'); + public function joinDefaults($name, mixed $value, $separator = '.'); /** * Get value from the configuration and join it with given data. diff --git a/system/src/Grav/Common/User/Traits/UserTrait.php b/system/src/Grav/Common/User/Traits/UserTrait.php index 085de03eb..8b943d880 100644 --- a/system/src/Grav/Common/User/Traits/UserTrait.php +++ b/system/src/Grav/Common/User/Traits/UserTrait.php @@ -89,7 +89,7 @@ trait UserTrait } // User needs to be authorized (2FA). - if (strpos($action, 'login') === false && !$this->get('authorized', true)) { + if (!str_contains($action, 'login') && !$this->get('authorized', true)) { return false; } @@ -184,7 +184,7 @@ trait UserTrait return ''; } - $hash = md5(strtolower(trim($email))); + $hash = md5(strtolower(trim((string) $email))); return 'https://www.gravatar.com/avatar/' . $hash; } diff --git a/system/src/Grav/Common/User/User.php b/system/src/Grav/Common/User/User.php index e87302edb..156783cff 100644 --- a/system/src/Grav/Common/User/User.php +++ b/system/src/Grav/Common/User/User.php @@ -36,7 +36,7 @@ if (defined('GRAV_USER_INSTANCE') && GRAV_USER_INSTANCE === 'FLEX') { */ public static function load($username) { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use $grav[\'accounts\']->' . __FUNCTION__ . '() instead', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use $grav[\'accounts\']->' . __FUNCTION__ . '() instead', E_USER_DEPRECATED); return static::getCollection()->load($username); } @@ -53,7 +53,7 @@ if (defined('GRAV_USER_INSTANCE') && GRAV_USER_INSTANCE === 'FLEX') { */ public static function find($query, $fields = ['username', 'email']) { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use $grav[\'accounts\']->' . __FUNCTION__ . '() instead', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use $grav[\'accounts\']->' . __FUNCTION__ . '() instead', E_USER_DEPRECATED); return static::getCollection()->find($query, $fields); } @@ -67,7 +67,7 @@ if (defined('GRAV_USER_INSTANCE') && GRAV_USER_INSTANCE === 'FLEX') { */ public static function remove($username) { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use $grav[\'accounts\']->delete() instead', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use $grav[\'accounts\']->delete() instead', E_USER_DEPRECATED); return static::getCollection()->delete($username); } @@ -97,7 +97,7 @@ if (defined('GRAV_USER_INSTANCE') && GRAV_USER_INSTANCE === 'FLEX') { */ public static function load($username) { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use $grav[\'accounts\']->' . __FUNCTION__ . '() instead', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use $grav[\'accounts\']->' . __FUNCTION__ . '() instead', E_USER_DEPRECATED); return static::getCollection()->load($username); } @@ -114,7 +114,7 @@ if (defined('GRAV_USER_INSTANCE') && GRAV_USER_INSTANCE === 'FLEX') { */ public static function find($query, $fields = ['username', 'email']) { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use $grav[\'accounts\']->' . __FUNCTION__ . '() instead', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use $grav[\'accounts\']->' . __FUNCTION__ . '() instead', E_USER_DEPRECATED); return static::getCollection()->find($query, $fields); } @@ -128,7 +128,7 @@ if (defined('GRAV_USER_INSTANCE') && GRAV_USER_INSTANCE === 'FLEX') { */ public static function remove($username) { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use $grav[\'accounts\']->delete() instead', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use $grav[\'accounts\']->delete() instead', E_USER_DEPRECATED); return static::getCollection()->delete($username); } diff --git a/system/src/Grav/Common/Utils.php b/system/src/Grav/Common/Utils.php index f106a64e7..d5c9b1abb 100644 --- a/system/src/Grav/Common/Utils.php +++ b/system/src/Grav/Common/Utils.php @@ -276,8 +276,8 @@ abstract class Utils public static function matchWildcard($wildcard_pattern, $haystack) { $regex = str_replace( - array("\*", "\?"), // wildcard chars - array('.*', '.'), // regexp chars + ["\*", "\?"], // wildcard chars + ['.*', '.'], // regexp chars preg_quote($wildcard_pattern, '/') ); @@ -296,10 +296,8 @@ abstract class Utils { $opening = $brackets[0] ?? '{'; $closing = $brackets[1] ?? '}'; - $expression = '/' . preg_quote($opening, '/') . '(.*?)' . preg_quote($closing, '/') . '/'; - $callback = static function ($match) use ($variables) { - return $variables[$match[1]] ?? $match[0]; - }; + $expression = '/' . preg_quote((string) $opening, '/') . '(.*?)' . preg_quote((string) $closing, '/') . '/'; + $callback = static fn($match) => $variables[$match[1]] ?? $match[0]; return preg_replace_callback($expression, $callback, $template); } @@ -468,7 +466,7 @@ abstract class Utils */ public static function arrayDiffMultidimensional($array1, $array2) { - $result = array(); + $result = []; foreach ($array1 as $key => $value) { if (!is_array($array2) || !array_key_exists($key, $array2)) { $result[$key] = $value; @@ -695,7 +693,7 @@ abstract class Utils // multipart-download and download resuming support if (isset($_SERVER['HTTP_RANGE'])) { - [$a, $range] = explode('=', $_SERVER['HTTP_RANGE'], 2); + [$a, $range] = explode('=', (string) $_SERVER['HTTP_RANGE'], 2); [$range] = explode(',', $range, 2); [$range, $range_end] = explode('-', $range); $range = (int)$range; @@ -725,7 +723,7 @@ abstract class Utils // Return 304 Not Modified if the file is already cached in the browser if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && - strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= filemtime($file)) { + strtotime((string) $_SERVER['HTTP_IF_MODIFIED_SINCE']) >= filemtime($file)) { header('HTTP/1.1 304 Not Modified'); exit(); } @@ -1233,7 +1231,7 @@ abstract class Utils */ public static function arrayFlattenDotNotation($array, $prepend = '') { - $results = array(); + $results = []; foreach ($array as $key => $value) { if (is_array($value)) { $results = array_merge($results, static::arrayFlattenDotNotation($value, $prepend . $key . '.')); @@ -1334,7 +1332,7 @@ abstract class Utils } else { try { $datetime = new DateTime($date); - } catch (Exception $e) { + } catch (Exception) { $datetime = false; } } @@ -1357,7 +1355,7 @@ abstract class Utils */ public static function resolve(array $array, $path, $default = null) { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use ->getDotNotation() method instead', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use ->getDotNotation() method instead', E_USER_DEPRECATED); return static::getDotNotation($array, $path, $default); } @@ -1511,12 +1509,10 @@ abstract class Utils * * @param array $array * @param string|int|null $key - * @param mixed $value * @param bool $merge - * * @return mixed */ - public static function setDotNotation(&$array, $key, $value, $merge = false) + public static function setDotNotation(&$array, $key, mixed $value, $merge = false) { if (null === $key) { return $array = $value; @@ -1528,7 +1524,7 @@ abstract class Utils $key = array_shift($keys); if (!isset($array[$key]) || !is_array($array[$key])) { - $array[$key] = array(); + $array[$key] = []; } $array =& $array[$key]; @@ -1562,7 +1558,7 @@ abstract class Utils */ public static function isApache() { - return isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') !== false; + return isset($_SERVER['SERVER_SOFTWARE']) && str_contains((string) $_SERVER['SERVER_SOFTWARE'], 'Apache'); } /** @@ -1587,13 +1583,12 @@ abstract class Utils /** * Sort an array by a key value in the array * - * @param mixed $array * @param string|int $array_key * @param int $direction * @param int $sort_flags * @return array */ - public static function sortArrayByKey($array, $array_key, $direction = SORT_DESC, $sort_flags = SORT_REGULAR) + public static function sortArrayByKey(mixed $array, $array_key, $direction = SORT_DESC, $sort_flags = SORT_REGULAR) { $output = []; @@ -1724,7 +1719,7 @@ abstract class Utils */ protected static function resolveTokenPath(string $path): ?array { - if (strpos($path, '@') !== false) { + if (str_contains($path, '@')) { $regex = '/^(@\w+|\w+@|@\w+@)([^:]*)(.*)$/u'; if (preg_match($regex, $path, $matches)) { return [ @@ -1773,11 +1768,7 @@ abstract class Utils */ public static function convertSize($bytes, $to, $decimal_places = 1) { - $formulas = array( - 'K' => number_format($bytes / 1024, $decimal_places), - 'M' => number_format($bytes / 1048576, $decimal_places), - 'G' => number_format($bytes / 1073741824, $decimal_places) - ); + $formulas = ['K' => number_format($bytes / 1024, $decimal_places), 'M' => number_format($bytes / 1048576, $decimal_places), 'G' => number_format($bytes / 1073741824, $decimal_places)]; return $formulas[$to] ?? 0; } @@ -1790,7 +1781,7 @@ abstract class Utils */ public static function prettySize($bytes, $precision = 2) { - $units = array('B', 'KB', 'MB', 'GB', 'TB'); + $units = ['B', 'KB', 'MB', 'GB', 'TB']; $bytes = max($bytes, 0); $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); @@ -1832,13 +1823,11 @@ abstract class Utils { $enc_url = preg_replace_callback( '%[^:/@?&=#]+%usD', - static function ($matches) { - return urlencode($matches[0]); - }, + static fn($matches) => urlencode((string) $matches[0]), $url ); - $parts = parse_url($enc_url); + $parts = parse_url((string) $enc_url); if ($parts === false) { $parts = []; @@ -1863,7 +1852,7 @@ abstract class Utils public static function processMarkdown($string, $block = true, $page = null) { $grav = Grav::instance(); - $page = $page ?? $grav['page'] ?? null; + $page ??= $grav['page'] ?? null; $defaults = [ 'markdown' => $grav['config']->get('system.pages.markdown', []), 'images' => $grav['config']->get('system.images', []) @@ -1890,9 +1879,9 @@ abstract class Utils public static function toAscii(String $string): String { - return strtr(utf8_decode($string), - utf8_decode( - 'ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ'), + return strtr(mb_convert_encoding($string, 'ISO-8859-1'), + mb_convert_encoding( + 'ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ', 'ISO-8859-1'), 'SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy'); } @@ -2078,11 +2067,11 @@ abstract class Utils return false; } - if (is_array($name) || strpos($name, ":") !== false) { + if (is_array($name) || str_contains($name, ":")) { return true; } - if (strpos($name, "\\") !== false) { + if (str_contains($name, "\\")) { return true; } diff --git a/system/src/Grav/Console/Application/Application.php b/system/src/Grav/Console/Application/Application.php index d2fa0cdc4..00185f1c6 100644 --- a/system/src/Grav/Console/Application/Application.php +++ b/system/src/Grav/Console/Application/Application.php @@ -43,7 +43,7 @@ class Application extends \Symfony\Component\Console\Application // Add listener to prepare environment. $dispatcher = new EventDispatcher(); - $dispatcher->addListener(ConsoleEvents::COMMAND, [$this, 'prepareEnvironment']); + $dispatcher->addListener(ConsoleEvents::COMMAND, $this->prepareEnvironment(...)); $this->setDispatcher($dispatcher); } diff --git a/system/src/Grav/Console/Application/CommandLoader/PluginCommandLoader.php b/system/src/Grav/Console/Application/CommandLoader/PluginCommandLoader.php index 210250c64..ac6085944 100644 --- a/system/src/Grav/Console/Application/CommandLoader/PluginCommandLoader.php +++ b/system/src/Grav/Console/Application/CommandLoader/PluginCommandLoader.php @@ -52,7 +52,7 @@ class PluginCommandLoader implements CommandLoaderInterface $full_path = $locator->findResource("plugins://{$name}/cli/{$command_path}"); require_once $full_path; - $command_class = 'Grav\Plugin\Console\\' . preg_replace('/.php$/', '', $command_path); + $command_class = 'Grav\Plugin\Console\\' . preg_replace('/.php$/', '', (string) $command_path); if (class_exists($command_class)) { $command = new $command_class(); if ($command instanceof Command) { diff --git a/system/src/Grav/Console/Cli/InstallCommand.php b/system/src/Grav/Console/Cli/InstallCommand.php index fce40a10e..ea3168e13 100644 --- a/system/src/Grav/Console/Cli/InstallCommand.php +++ b/system/src/Grav/Console/Cli/InstallCommand.php @@ -76,7 +76,7 @@ class InstallCommand extends GravCommand $this->destination = $input->getArgument('destination') ?: GRAV_WEBROOT; // fix trailing slash - $this->destination = rtrim($this->destination, DS) . DS; + $this->destination = rtrim((string) $this->destination, DS) . DS; $this->user_path = $this->destination . GRAV_USER_PATH . DS; if ($local_config_file = $this->loadLocalConfig()) { $io->writeln('Read local config from ' . $local_config_file . ''); @@ -222,7 +222,7 @@ class InstallCommand extends GravCommand $from = null; foreach ($locations as $location) { - $test = rtrim($location, '\\/') . DS . $src; + $test = rtrim((string) $location, '\\/') . DS . $src; if (file_exists($test)) { $from = $test; continue; @@ -264,8 +264,8 @@ class InstallCommand extends GravCommand $io->writeln("Processing {$name}"); foreach ($hebe as $section => $symlinks) { foreach ($symlinks as $symlink) { - $src = trim($symlink['source'], '/'); - $dst = trim($symlink['destination'], '/'); + $src = trim((string) $symlink['source'], '/'); + $dst = trim((string) $symlink['destination'], '/'); $s = "{$from}/{$src}"; $d = "{$to}/{$dst}"; diff --git a/system/src/Grav/Console/Cli/PageSystemValidatorCommand.php b/system/src/Grav/Console/Cli/PageSystemValidatorCommand.php index 1e8302d23..f682b6ca5 100644 --- a/system/src/Grav/Console/Cli/PageSystemValidatorCommand.php +++ b/system/src/Grav/Console/Cli/PageSystemValidatorCommand.php @@ -240,7 +240,7 @@ class PageSystemValidatorCommand extends GravCommand $result = $page->$method(...$p); if (in_array($method, ['summary', 'content', 'getRawContent'], true)) { $result = preg_replace('/name="(form-nonce|__unique_form_id__)" value="[^"]+"/', - 'name="\\1" value="DYNAMIC"', $result); + 'name="\\1" value="DYNAMIC"', (string) $result); $result = preg_replace('`src=("|\'|")/images/./././././[^"]+\\1`', 'src="\\1images/GENERATED\\1', $result); $result = preg_replace('/\?\d{10}/', '?1234567890', $result); diff --git a/system/src/Grav/Console/Cli/SchedulerCommand.php b/system/src/Grav/Console/Cli/SchedulerCommand.php index fb302440a..bc7e4d326 100644 --- a/system/src/Grav/Console/Cli/SchedulerCommand.php +++ b/system/src/Grav/Console/Cli/SchedulerCommand.php @@ -137,7 +137,7 @@ class SchedulerCommand extends GravCommand foreach ($jobs as $job) { $job_state = $job_states[$job->getId()]; - $error = isset($job_state['error']) ? trim($job_state['error']) : false; + $error = isset($job_state['error']) ? trim((string) $job_state['error']) : false; /** @var CronExpression $expression */ $expression = $job->getCronExpression(); diff --git a/system/src/Grav/Console/Cli/SecurityCommand.php b/system/src/Grav/Console/Cli/SecurityCommand.php index d75a4a6cf..ee8caa1b2 100644 --- a/system/src/Grav/Console/Cli/SecurityCommand.php +++ b/system/src/Grav/Console/Cli/SecurityCommand.php @@ -53,15 +53,13 @@ class SecurityCommand extends GravCommand $io->title('Grav Security Check'); $io->newline(2); - $output = Security::detectXssFromPages($grav['pages'], false, [$this, 'outputProgress']); + $output = Security::detectXssFromPages($grav['pages'], false, $this->outputProgress(...)); $error = 0; if (!empty($output)) { $counter = 1; foreach ($output as $route => $results) { - $results_parts = array_map(static function ($value, $key) { - return $key.': \''.$value . '\''; - }, array_values($results), array_keys($results)); + $results_parts = array_map(static fn($value, $key) => $key.': \''.$value . '\'', array_values($results), array_keys($results)); $io->writeln($counter++ .' - ' . $route . '' . implode(', ', $results_parts) . ''); } diff --git a/system/src/Grav/Console/ConsoleTrait.php b/system/src/Grav/Console/ConsoleTrait.php index a514e88a2..1ab9d2ccf 100644 --- a/system/src/Grav/Console/ConsoleTrait.php +++ b/system/src/Grav/Console/ConsoleTrait.php @@ -106,7 +106,7 @@ trait ConsoleTrait // Set used language. $this->setLanguage($language); } - } catch (InvalidArgumentException $e) {} + } catch (InvalidArgumentException) {} // Initialize cache with CLI compatibility $grav = Grav::instance(); diff --git a/system/src/Grav/Console/Gpm/IndexCommand.php b/system/src/Grav/Console/Gpm/IndexCommand.php index d9b544878..512efcaa7 100644 --- a/system/src/Grav/Console/Gpm/IndexCommand.php +++ b/system/src/Grav/Console/Gpm/IndexCommand.php @@ -134,7 +134,7 @@ class IndexCommand extends GpmCommand } foreach ($data as $type => $packages) { - $io->writeln('' . strtoupper($type) . ' [ ' . count($packages) . ' ]'); + $io->writeln('' . strtoupper((string) $type) . ' [ ' . count($packages) . ' ]'); $packages = $this->sort($packages); @@ -321,13 +321,9 @@ class IndexCommand extends GpmCommand // Sorting only works once. return $packages->sort( - function ($a, $b) use ($key) { - switch ($key) { - case 'author': - return strcmp($a->{$key}['name'], $b->{$key}['name']); - default: - return strcmp($a->$key, $b->$key); - } + fn($a, $b) => match ($key) { + 'author' => strcmp((string) $a->{$key}['name'], (string) $b->{$key}['name']), + default => strcmp((string) $a->$key, (string) $b->$key), }, $this->options['desc'] ? true : false ); diff --git a/system/src/Grav/Console/Gpm/InfoCommand.php b/system/src/Grav/Console/Gpm/InfoCommand.php index d343cfd36..55582f839 100644 --- a/system/src/Grav/Console/Gpm/InfoCommand.php +++ b/system/src/Grav/Console/Gpm/InfoCommand.php @@ -123,7 +123,7 @@ class InfoCommand extends GpmCommand if ($info === 'date') { $name = 'Last Update'; - $data = date('D, j M Y, H:i:s, P ', strtotime($data)); + $data = date('D, j M Y, H:i:s, P ', strtotime((string) $data)); } $name = str_pad($name, 12); @@ -156,9 +156,7 @@ class InfoCommand extends GpmCommand $io->newLine(); foreach ($changelog as $version => $log) { $title = $version . ' [' . $log['date'] . ']'; - $content = preg_replace_callback('/\d\.\s\[\]\(#(.*)\)/', static function ($match) { - return "\n" . ucfirst($match[1]) . ':'; - }, $log['content']); + $content = preg_replace_callback('/\d\.\s\[\]\(#(.*)\)/', static fn($match) => "\n" . ucfirst((string) $match[1]) . ':', (string) $log['content']); $io->writeln("{$title}"); $io->writeln(str_repeat('-', strlen($title))); diff --git a/system/src/Grav/Console/Gpm/InstallCommand.php b/system/src/Grav/Console/Gpm/InstallCommand.php index adbfea9de..2c9eaf1a7 100644 --- a/system/src/Grav/Console/Gpm/InstallCommand.php +++ b/system/src/Grav/Console/Gpm/InstallCommand.php @@ -179,7 +179,7 @@ class InstallCommand extends GpmCommand $this->installDependencies($dependencies, 'install', 'The following dependencies need to be installed...'); $this->installDependencies($dependencies, 'update', 'The following dependencies need to be updated...'); $this->installDependencies($dependencies, 'ignore', "The following dependencies can be updated as there is a newer version, but it's not mandatory...", false); - } catch (Exception $e) { + } catch (Exception) { $io->writeln('Installation aborted'); return 1; @@ -287,9 +287,7 @@ class InstallCommand extends GpmCommand public function installDependencies(array $dependencies, string $type, string $message, bool $required = true): void { $io = $this->getIO(); - $packages = array_filter($dependencies, static function ($action) use ($type) { - return $action === $type; - }); + $packages = array_filter($dependencies, static fn($action) => $action === $type); if (count($packages) > 0) { $io->writeln($message); @@ -460,14 +458,14 @@ class InstallCommand extends GpmCommand foreach ($this->local_config as $paths) { if (Utils::endsWith($matches[2], '.git')) { - $repo_dir = preg_replace('/\.git$/', '', $matches[2]); + $repo_dir = preg_replace('/\.git$/', '', (string) $matches[2]); } else { $repo_dir = $matches[2]; } $paths = (array) $paths; foreach ($paths as $repo) { - $path = rtrim($repo, '/') . '/' . $repo_dir; + $path = rtrim((string) $repo, '/') . '/' . $repo_dir; if (file_exists($path)) { return $path; } @@ -598,7 +596,7 @@ class InstallCommand extends GpmCommand } try { - $output = Response::get($package->zipball_url . $query, [], [$this, 'progress']); + $output = Response::get($package->zipball_url . $query, [], $this->progress(...)); } catch (Exception $e) { if (!empty($package->premium) && $e->getCode() === 401) { $message = 'Unauthorized Premium License Key'; @@ -717,7 +715,7 @@ class InstallCommand extends GpmCommand $io->write("\x0D"); $io->write(' |- Downloading package... ' . str_pad( - $progress['percent'], + (string) $progress['percent'], 5, ' ', STR_PAD_LEFT diff --git a/system/src/Grav/Console/Gpm/SelfupgradeCommand.php b/system/src/Grav/Console/Gpm/SelfupgradeCommand.php index 2b164d029..79dd440bd 100644 --- a/system/src/Grav/Console/Gpm/SelfupgradeCommand.php +++ b/system/src/Grav/Console/Gpm/SelfupgradeCommand.php @@ -186,9 +186,7 @@ class SelfupgradeCommand extends GpmCommand $io->newLine(); foreach ($changelog as $version => $log) { $title = $version . ' [' . $log['date'] . ']'; - $content = preg_replace_callback('/\d\.\s\[\]\(#(.*)\)/', static function ($match) { - return "\n" . ucfirst($match[1]) . ':'; - }, $log['content']); + $content = preg_replace_callback('/\d\.\s\[\]\(#(.*)\)/', static fn($match) => "\n" . ucfirst((string) $match[1]) . ':', (string) $log['content']); $io->writeln($title); $io->writeln(str_repeat('-', strlen($title))); @@ -250,7 +248,7 @@ class SelfupgradeCommand extends GpmCommand 'timeout' => $this->timeout, ]; - $output = Response::get($package['download'], $options, [$this, 'progress']); + $output = Response::get($package['download'], $options, $this->progress(...)); Folder::create($this->tmp); @@ -299,7 +297,7 @@ class SelfupgradeCommand extends GpmCommand $io->write("\x0D"); $io->write(" |- Downloading upgrade [{$this->formatBytes($progress['filesize']) }]... " . str_pad( - $progress['percent'], + (string) $progress['percent'], 5, ' ', STR_PAD_LEFT @@ -314,7 +312,7 @@ class SelfupgradeCommand extends GpmCommand public function formatBytes($size, int $precision = 2): string { $base = log($size) / log(1024); - $suffixes = array('', 'k', 'M', 'G', 'T'); + $suffixes = ['', 'k', 'M', 'G', 'T']; return round(1024 ** ($base - floor($base)), $precision) . $suffixes[(int)floor($base)]; } diff --git a/system/src/Grav/Console/Gpm/VersionCommand.php b/system/src/Grav/Console/Gpm/VersionCommand.php index 3e16adbfb..74b8e51a8 100644 --- a/system/src/Grav/Console/Gpm/VersionCommand.php +++ b/system/src/Grav/Console/Gpm/VersionCommand.php @@ -67,7 +67,7 @@ class VersionCommand extends GpmCommand } foreach ($packages as $package) { - $package = strtolower($package); + $package = strtolower((string) $package); $name = null; $version = null; $updatable = false; diff --git a/system/src/Grav/Console/GpmCommand.php b/system/src/Grav/Console/GpmCommand.php index f89d565e6..8be004a95 100644 --- a/system/src/Grav/Console/GpmCommand.php +++ b/system/src/Grav/Console/GpmCommand.php @@ -62,7 +62,7 @@ class GpmCommand extends Command $io = $this->getIO(); $io->newLine(); - $io->writeln('GPM Releases Configuration: ' . ucfirst($config->get('system.gpm.releases')) . ''); + $io->writeln('GPM Releases Configuration: ' . ucfirst((string) $config->get('system.gpm.releases')) . ''); $io->newLine(); } } diff --git a/system/src/Grav/Framework/Acl/Access.php b/system/src/Grav/Framework/Acl/Access.php index 408fa046e..6c34baf50 100644 --- a/system/src/Grav/Framework/Acl/Access.php +++ b/system/src/Grav/Framework/Acl/Access.php @@ -28,8 +28,6 @@ use function strlen; */ class Access implements JsonSerializable, IteratorAggregate, Countable { - /** @var string */ - private $name; /** @var array */ private $rules; /** @var array */ @@ -45,9 +43,8 @@ class Access implements JsonSerializable, IteratorAggregate, Countable * @param array|null $rules * @param string $name */ - public function __construct($acl = null, ?array $rules = null, string $name = '') + public function __construct($acl = null, ?array $rules = null, private readonly string $name = '') { - $this->name = $name; $this->rules = $rules ?? []; $this->ops = ['+' => true, '-' => false]; if (is_string($acl)) { @@ -110,7 +107,7 @@ class Access implements JsonSerializable, IteratorAggregate, Countable */ public function getAllActions(): array { - return array_filter($this->acl, static function($val) { return $val !== null; }); + return array_filter($this->acl, static fn($val) => $val !== null); } /** diff --git a/system/src/Grav/Framework/Acl/Permissions.php b/system/src/Grav/Framework/Acl/Permissions.php index 63c0141c7..778576aa5 100644 --- a/system/src/Grav/Framework/Acl/Permissions.php +++ b/system/src/Grav/Framework/Acl/Permissions.php @@ -181,10 +181,9 @@ class Permissions implements ArrayAccess, Countable, IteratorAggregate /** * @param int|string $offset - * @param mixed $value * @return void */ - public function offsetSet($offset, $value): void + public function offsetSet($offset, mixed $value): void { throw new RuntimeException(__METHOD__ . '(): Not Supported'); } diff --git a/system/src/Grav/Framework/Cache/Adapter/ChainCache.php b/system/src/Grav/Framework/Cache/Adapter/ChainCache.php index 295784146..6c3ca8121 100644 --- a/system/src/Grav/Framework/Cache/Adapter/ChainCache.php +++ b/system/src/Grav/Framework/Cache/Adapter/ChainCache.php @@ -52,7 +52,7 @@ class ChainCache extends AbstractCache throw new InvalidArgumentException( sprintf( "The class '%s' does not implement the '%s' interface", - get_class($cache), + $cache::class, CacheInterface::class ) ); diff --git a/system/src/Grav/Framework/Cache/Adapter/FileCache.php b/system/src/Grav/Framework/Cache/Adapter/FileCache.php index d2058d5f7..6a049f114 100644 --- a/system/src/Grav/Framework/Cache/Adapter/FileCache.php +++ b/system/src/Grav/Framework/Cache/Adapter/FileCache.php @@ -197,7 +197,7 @@ class FileCache extends AbstractCache */ private function write($file, $data, $expiresAt = null) { - set_error_handler(__CLASS__.'::throwError'); + set_error_handler(self::class.'::throwError'); try { if ($this->tmp === null) { @@ -248,7 +248,7 @@ class FileCache extends AbstractCache * @internal * @throws ErrorException */ - public static function throwError($type, $message, $file, $line) + public static function throwError($type, $message, $file, $line): never { throw new ErrorException($message, 0, $type, $file, $line); } diff --git a/system/src/Grav/Framework/Cache/CacheInterface.php b/system/src/Grav/Framework/Cache/CacheInterface.php index c095f3d09..73248b03f 100644 --- a/system/src/Grav/Framework/Cache/CacheInterface.php +++ b/system/src/Grav/Framework/Cache/CacheInterface.php @@ -19,18 +19,16 @@ interface CacheInterface extends SimpleCacheInterface { /** * @param string $key - * @param mixed $miss * @return mixed */ - public function doGet($key, $miss); + public function doGet($key, mixed $miss); /** * @param string $key - * @param mixed $value * @param int|null $ttl * @return mixed */ - public function doSet($key, $value, $ttl); + public function doSet($key, mixed $value, $ttl); /** * @param string $key @@ -45,10 +43,9 @@ interface CacheInterface extends SimpleCacheInterface /** * @param string[] $keys - * @param mixed $miss * @return mixed */ - public function doGetMultiple($keys, $miss); + public function doGetMultiple($keys, mixed $miss); /** * @param array $values diff --git a/system/src/Grav/Framework/Cache/CacheTrait.php b/system/src/Grav/Framework/Cache/CacheTrait.php index f7eeb0488..5c4f19cf4 100644 --- a/system/src/Grav/Framework/Cache/CacheTrait.php +++ b/system/src/Grav/Framework/Cache/CacheTrait.php @@ -95,12 +95,11 @@ trait CacheTrait /** * @param string $key - * @param mixed $value * @param null|int|DateInterval $ttl * @return bool * @throws InvalidArgumentException */ - public function set($key, $value, $ttl = null) + public function set($key, mixed $value, $ttl = null) { $this->validateKey($key); @@ -145,7 +144,7 @@ trait CacheTrait throw new InvalidArgumentException( sprintf( 'Cache keys must be array or Traversable, "%s" given', - $isObject ? get_class($keys) : gettype($keys) + $isObject ? $keys::class : gettype($keys) ) ); } @@ -188,7 +187,7 @@ trait CacheTrait throw new InvalidArgumentException( sprintf( 'Cache values must be array or Traversable, "%s" given', - $isObject ? get_class($values) : gettype($values) + $isObject ? $values::class : gettype($values) ) ); } @@ -221,7 +220,7 @@ trait CacheTrait throw new InvalidArgumentException( sprintf( 'Cache keys must be array or Traversable, "%s" given', - $isObject ? get_class($keys) : gettype($keys) + $isObject ? $keys::class : gettype($keys) ) ); } @@ -249,10 +248,9 @@ trait CacheTrait /** * @param array $keys - * @param mixed $miss * @return array */ - public function doGetMultiple($keys, $miss) + public function doGetMultiple($keys, mixed $miss) { $results = []; @@ -308,7 +306,7 @@ trait CacheTrait throw new InvalidArgumentException( sprintf( 'Cache key must be string, "%s" given', - is_object($key) ? get_class($key) : gettype($key) + get_debug_type($key) ) ); } @@ -366,7 +364,7 @@ trait CacheTrait throw new InvalidArgumentException( sprintf( 'Expiration date must be an integer, a DateInterval or null, "%s" given', - is_object($ttl) ? get_class($ttl) : gettype($ttl) + get_debug_type($ttl) ) ); } diff --git a/system/src/Grav/Framework/Collection/AbstractFileCollection.php b/system/src/Grav/Framework/Collection/AbstractFileCollection.php index 88682733f..8a7647841 100644 --- a/system/src/Grav/Framework/Collection/AbstractFileCollection.php +++ b/system/src/Grav/Framework/Collection/AbstractFileCollection.php @@ -31,8 +31,6 @@ use function array_slice; */ class AbstractFileCollection extends AbstractLazyCollection implements FileCollectionInterface { - /** @var string */ - protected $path; /** @var RecursiveDirectoryIterator|RecursiveUniformResourceIterator */ protected $iterator; /** @var callable */ @@ -47,9 +45,8 @@ class AbstractFileCollection extends AbstractLazyCollection implements FileColle /** * @param string $path */ - protected function __construct($path) + protected function __construct(protected $path) { - $this->path = $path; $this->flags = self::INCLUDE_FILES | self::INCLUDE_FOLDERS; $this->nestingLimit = 0; $this->createObjectFunction = [$this, 'createObject']; @@ -139,9 +136,7 @@ class AbstractFileCollection extends AbstractLazyCollection implements FileColle { if ($this->filterFunction) { $oldFilterFunction = $this->filterFunction; - $this->filterFunction = function ($expr) use ($oldFilterFunction, $filterFunction) { - return $oldFilterFunction($expr) && $filterFunction($expr); - }; + $this->filterFunction = fn($expr) => $oldFilterFunction($expr) && $filterFunction($expr); } else { $this->filterFunction = $filterFunction; } diff --git a/system/src/Grav/Framework/Collection/AbstractIndexCollection.php b/system/src/Grav/Framework/Collection/AbstractIndexCollection.php index be5d5c5c6..c4f1d8c09 100644 --- a/system/src/Grav/Framework/Collection/AbstractIndexCollection.php +++ b/system/src/Grav/Framework/Collection/AbstractIndexCollection.php @@ -26,25 +26,23 @@ use function count; * @template C of CollectionInterface * @implements CollectionInterface */ -abstract class AbstractIndexCollection implements CollectionInterface +abstract class AbstractIndexCollection implements CollectionInterface, \Stringable { use Serializable; - /** - * @var array - * @phpstan-var array - */ - private $entries; - /** * Initializes a new IndexCollection. * * @param array $entries * @phpstan-param array $entries */ - public function __construct(array $entries = []) + public function __construct( + /** + * @phpstan-var array + */ + private array $entries = [] + ) { - $this->entries = $entries; } /** @@ -174,12 +172,11 @@ abstract class AbstractIndexCollection implements CollectionInterface * Required by interface ArrayAccess. * * @param string|int|null $offset - * @param mixed $value * @return void * @phpstan-param TKey|null $offset */ #[\ReturnTypeWillChange] - public function offsetSet($offset, $value) + public function offsetSet($offset, mixed $value) { if (null === $offset) { $this->add($value); @@ -362,9 +359,9 @@ abstract class AbstractIndexCollection implements CollectionInterface * @return string */ #[\ReturnTypeWillChange] - public function __toString() + public function __toString(): string { - return __CLASS__ . '@' . spl_object_hash($this); + return self::class . '@' . spl_object_hash($this); } /** @@ -541,10 +538,9 @@ abstract class AbstractIndexCollection implements CollectionInterface /** * @param string $key - * @param mixed $value * @return mixed|null */ - abstract protected function loadElement($key, $value); + abstract protected function loadElement($key, mixed $value); /** * @param array|null $entries @@ -561,14 +557,12 @@ abstract class AbstractIndexCollection implements CollectionInterface abstract protected function loadCollection(?array $entries = null): CollectionInterface; /** - * @param mixed $value * @return bool */ - abstract protected function isAllowedElement($value): bool; + abstract protected function isAllowedElement(mixed $value): bool; /** - * @param mixed $element * @return mixed */ - abstract protected function getElementMeta($element); + abstract protected function getElementMeta(mixed $element); } diff --git a/system/src/Grav/Framework/Collection/AbstractLazyCollection.php b/system/src/Grav/Framework/Collection/AbstractLazyCollection.php index 6d98bc889..60807de18 100644 --- a/system/src/Grav/Framework/Collection/AbstractLazyCollection.php +++ b/system/src/Grav/Framework/Collection/AbstractLazyCollection.php @@ -26,7 +26,7 @@ abstract class AbstractLazyCollection extends BaseAbstractLazyCollection impleme * @par ArrayCollection * @phpstan-var ArrayCollection */ - protected ?\Doctrine\Common\Collections\Collection $collection; + protected ?\Doctrine\Common\Collections\Collection $collection = null; /** * {@inheritDoc} diff --git a/system/src/Grav/Framework/ContentBlock/ContentBlock.php b/system/src/Grav/Framework/ContentBlock/ContentBlock.php index 3ba8abe2d..fe78096ef 100644 --- a/system/src/Grav/Framework/ContentBlock/ContentBlock.php +++ b/system/src/Grav/Framework/ContentBlock/ContentBlock.php @@ -118,7 +118,7 @@ class ContentBlock implements ContentBlockInterface } $array = [ - '_type' => get_class($this), + '_type' => static::class, '_version' => $this->version, 'id' => $this->id, 'cached' => $this->cached @@ -162,7 +162,7 @@ class ContentBlock implements ContentBlockInterface * @return string */ #[\ReturnTypeWillChange] - public function __toString() + public function __toString(): string { try { return $this->toString(); diff --git a/system/src/Grav/Framework/ContentBlock/HtmlBlock.php b/system/src/Grav/Framework/ContentBlock/HtmlBlock.php index 5d6bf6235..be8126b4e 100644 --- a/system/src/Grav/Framework/ContentBlock/HtmlBlock.php +++ b/system/src/Grav/Framework/ContentBlock/HtmlBlock.php @@ -182,7 +182,7 @@ class HtmlBlock extends ContentBlock implements HtmlBlockInterface $element['media'] ); - $this->styles[$location][md5($href) . sha1($href)] = [ + $this->styles[$location][md5((string) $href) . sha1((string) $href)] = [ ':type' => 'file', ':priority' => (int) $priority, 'href' => $href, @@ -255,7 +255,7 @@ class HtmlBlock extends ContentBlock implements HtmlBlockInterface unset($element['src'], $element['type'], $element['loading'], $element['defer'], $element['async'], $element['handle']); - $this->scripts[$location][md5($src) . sha1($src)] = [ + $this->scripts[$location][md5((string) $src) . sha1((string) $src)] = [ ':type' => 'file', ':priority' => (int) $priority, 'src' => $src, @@ -483,9 +483,7 @@ class HtmlBlock extends ContentBlock implements HtmlBlockInterface uasort( $items, - static function ($a, $b) { - return $a[':priority'] <=> $b[':priority'] ?: $a[':order'] <=> $b[':order']; - } + static fn($a, $b) => $a[':priority'] <=> $b[':priority'] ?: $a[':order'] <=> $b[':order'] ); } diff --git a/system/src/Grav/Framework/Controller/Traits/ControllerResponseTrait.php b/system/src/Grav/Framework/Controller/Traits/ControllerResponseTrait.php index a50c6d18b..5b818bf35 100644 --- a/system/src/Grav/Framework/Controller/Traits/ControllerResponseTrait.php +++ b/system/src/Grav/Framework/Controller/Traits/ControllerResponseTrait.php @@ -51,11 +51,11 @@ trait ControllerResponseTrait */ protected function createHtmlResponse(string $content, ?int $code = null, ?array $headers = null): ResponseInterface { - $code = $code ?? 200; + $code ??= 200; if ($code < 100 || $code > 599) { $code = 500; } - $headers = $headers ?? []; + $headers ??= []; return new Response($code, $headers, $content); } @@ -68,7 +68,7 @@ trait ControllerResponseTrait */ protected function createJsonResponse(array $content, ?int $code = null, ?array $headers = null): ResponseInterface { - $code = $code ?? $content['code'] ?? 200; + $code ??= $content['code'] ?? 200; if (null === $code || $code < 100 || $code > 599) { $code = 200; } @@ -94,8 +94,8 @@ trait ControllerResponseTrait @ini_set('zlib.output_compression', 'Off'); } - $headers = $headers ?? []; - $options = $options ?? ['force_download' => true]; + $headers ??= []; + $options ??= ['force_download' => true]; $file_parts = Utils::pathinfo($filename); @@ -228,7 +228,7 @@ trait ControllerResponseTrait $debugger = Grav::instance()['debugger']; if ($debugger->enabled()) { $response['error'] += [ - 'type' => get_class($e), + 'type' => $e::class, 'file' => $e->getFile(), 'line' => $e->getLine(), 'trace' => explode("\n", $e->getTraceAsString()) @@ -264,7 +264,7 @@ trait ControllerResponseTrait { $accepted = []; foreach ($this->getRequest()->getHeader('Accept') as $accept) { - foreach (explode(',', $accept) as $item) { + foreach (explode(',', (string) $accept) as $item) { if (!$item) { continue; } diff --git a/system/src/Grav/Framework/File/AbstractFile.php b/system/src/Grav/Framework/File/AbstractFile.php index f49112b03..2b704c977 100644 --- a/system/src/Grav/Framework/File/AbstractFile.php +++ b/system/src/Grav/Framework/File/AbstractFile.php @@ -285,7 +285,7 @@ class AbstractFile implements FileInterface if ($this->handle) { $tmp = true; // As we are using non-truncating locking, make sure that the file is empty before writing. - if (@ftruncate($this->handle, 0) === false || @fwrite($this->handle, $data) === false) { + if (@ftruncate($this->handle, 0) === false || @fwrite($this->handle, (string) $data) === false) { // Writing file failed, throw an error. $tmp = false; } @@ -305,7 +305,7 @@ class AbstractFile implements FileInterface $tmp = false; } } - } catch (Exception $e) { + } catch (Exception) { $tmp = false; } diff --git a/system/src/Grav/Framework/File/Formatter/AbstractFormatter.php b/system/src/Grav/Framework/File/Formatter/AbstractFormatter.php index 83a444dce..0789f763a 100644 --- a/system/src/Grav/Framework/File/Formatter/AbstractFormatter.php +++ b/system/src/Grav/Framework/File/Formatter/AbstractFormatter.php @@ -24,16 +24,12 @@ abstract class AbstractFormatter implements FileFormatterInterface { use Serializable; - /** @var array */ - private $config; - /** * IniFormatter constructor. * @param array $config */ - public function __construct(array $config = []) + public function __construct(private array $config = []) { - $this->config = $config; } /** diff --git a/system/src/Grav/Framework/File/Formatter/CsvFormatter.php b/system/src/Grav/Framework/File/Formatter/CsvFormatter.php index 9bdd6628d..960b0aa94 100644 --- a/system/src/Grav/Framework/File/Formatter/CsvFormatter.php +++ b/system/src/Grav/Framework/File/Formatter/CsvFormatter.php @@ -64,7 +64,7 @@ class CsvFormatter extends AbstractFormatter if (count($data) === 0) { return ''; } - $delimiter = $delimiter ?? $this->getDelimiter(); + $delimiter ??= $this->getDelimiter(); $header = array_keys(reset($data)); // Encode the field names @@ -86,7 +86,7 @@ class CsvFormatter extends AbstractFormatter */ public function decode($data, $delimiter = null): array { - $delimiter = $delimiter ?? $this->getDelimiter(); + $delimiter ??= $this->getDelimiter(); $lines = preg_split('/\r\n|\r|\n/', $data); if ($lines === false) { throw new RuntimeException('Decoding CSV failed'); @@ -120,7 +120,7 @@ class CsvFormatter extends AbstractFormatter $list[] = array_combine($header, $csv_line); } } - } catch (Exception $e) { + } catch (Exception) { throw new RuntimeException('Badly formatted CSV line: ' . $line); } diff --git a/system/src/Grav/Framework/File/Formatter/IniFormatter.php b/system/src/Grav/Framework/File/Formatter/IniFormatter.php index 809de1cbe..5bdfda3b3 100644 --- a/system/src/Grav/Framework/File/Formatter/IniFormatter.php +++ b/system/src/Grav/Framework/File/Formatter/IniFormatter.php @@ -44,7 +44,7 @@ class IniFormatter extends AbstractFormatter $string .= $key . '="' . preg_replace( ['/"/', '/\\\/', "/\t/", "/\n/", "/\r/"], ['\"', '\\\\', '\t', '\n', '\r'], - $value + (string) $value ) . "\"\n"; } diff --git a/system/src/Grav/Framework/File/Formatter/SerializeFormatter.php b/system/src/Grav/Framework/File/Formatter/SerializeFormatter.php index 2ed8b93bf..5c4bf695f 100644 --- a/system/src/Grav/Framework/File/Formatter/SerializeFormatter.php +++ b/system/src/Grav/Framework/File/Formatter/SerializeFormatter.php @@ -77,12 +77,11 @@ class SerializeFormatter extends AbstractFormatter /** * Preserve new lines, recursive function. * - * @param mixed $data * @param array $search * @param array $replace * @return mixed */ - protected function preserveLines($data, array $search, array $replace) + protected function preserveLines(mixed $data, array $search, array $replace) { if (is_string($data)) { $data = str_replace($search, $replace, $data); diff --git a/system/src/Grav/Framework/File/Interfaces/FileFormatterInterface.php b/system/src/Grav/Framework/File/Interfaces/FileFormatterInterface.php index e76ba10b6..97095cac6 100644 --- a/system/src/Grav/Framework/File/Interfaces/FileFormatterInterface.php +++ b/system/src/Grav/Framework/File/Interfaces/FileFormatterInterface.php @@ -59,7 +59,7 @@ interface FileFormatterInterface extends Serializable * @return string Returns encoded data as a string. * @api */ - public function encode($data): string; + public function encode(mixed $data): string; /** * Decode a string into data. diff --git a/system/src/Grav/Framework/File/Interfaces/FileInterface.php b/system/src/Grav/Framework/File/Interfaces/FileInterface.php index 0abb46adc..ec917490b 100644 --- a/system/src/Grav/Framework/File/Interfaces/FileInterface.php +++ b/system/src/Grav/Framework/File/Interfaces/FileInterface.php @@ -156,7 +156,7 @@ interface FileInterface extends Serializable * @throws RuntimeException * @api */ - public function save($data): void; + public function save(mixed $data): void; /** * Rename file in the filesystem if it exists. diff --git a/system/src/Grav/Framework/Filesystem/Filesystem.php b/system/src/Grav/Framework/Filesystem/Filesystem.php index 20b42c8d0..cc80df41c 100644 --- a/system/src/Grav/Framework/Filesystem/Filesystem.php +++ b/system/src/Grav/Framework/Filesystem/Filesystem.php @@ -24,9 +24,6 @@ use function pathinfo; */ class Filesystem implements FilesystemInterface { - /** @var bool|null */ - private $normalize; - /** @var static|null */ protected static $default; @@ -63,9 +60,8 @@ class Filesystem implements FilesystemInterface * @param bool|null $normalize * @internal */ - protected function __construct(?bool $normalize = null) + protected function __construct(private readonly ?bool $normalize = null) { - $this->normalize = $normalize; } /** diff --git a/system/src/Grav/Framework/Flex/Flex.php b/system/src/Grav/Framework/Flex/Flex.php index f51a4c84c..c16d3ed69 100644 --- a/system/src/Grav/Framework/Flex/Flex.php +++ b/system/src/Grav/Framework/Flex/Flex.php @@ -306,7 +306,7 @@ class Flex implements FlexInterface protected function resolveKeyAndType(string $flexKey, ?string $type = null): array { $guess = false; - if (strpos($flexKey, ':') !== false) { + if (str_contains($flexKey, ':')) { [$type, $key] = explode(':', $flexKey, 2); $type = $this->resolveType($type); @@ -325,7 +325,7 @@ class Flex implements FlexInterface */ protected function resolveType(?string $type = null): string { - if (null !== $type && strpos($type, '.') !== false) { + if (null !== $type && str_contains($type, '.')) { return preg_replace('|\.obj$|', '', $type) ?? $type; } diff --git a/system/src/Grav/Framework/Flex/FlexCollection.php b/system/src/Grav/Framework/Flex/FlexCollection.php index 7984719fc..5e3d63d1b 100644 --- a/system/src/Grav/Framework/Flex/FlexCollection.php +++ b/system/src/Grav/Framework/Flex/FlexCollection.php @@ -99,8 +99,8 @@ class FlexCollection extends ObjectCollection implements FlexCollectionInterface public function __construct(array $entries = [], ?FlexDirectory $directory = null) { // @phpstan-ignore-next-line - if (get_class($this) === __CLASS__) { - user_error('Using ' . __CLASS__ . ' directly is deprecated since Grav 1.7, use \Grav\Common\Flex\Types\Generic\GenericCollection or your own class instead', E_USER_DEPRECATED); + if (static::class === self::class) { + user_error('Using ' . self::class . ' directly is deprecated since Grav 1.7, use \Grav\Common\Flex\Types\Generic\GenericCollection or your own class instead', E_USER_DEPRECATED); } parent::__construct($entries); @@ -130,8 +130,8 @@ class FlexCollection extends ObjectCollection implements FlexCollectionInterface $list = []; foreach ($implements as $interface) { - if ($pos = strrpos($interface, '\\')) { - $interface = substr($interface, $pos+1); + if ($pos = strrpos((string) $interface, '\\')) { + $interface = substr((string) $interface, $pos+1); } $list[] = Inflector::hyphenize(str_replace('Interface', '', $interface)); @@ -400,10 +400,7 @@ class FlexCollection extends ObjectCollection implements FlexCollectionInterface $data = $cache && $key ? $cache->get($key) : null; $block = $data ? HtmlBlock::fromArray($data) : null; - } catch (InvalidArgumentException $e) { - $debugger->addException($e); - $block = null; - } catch (\InvalidArgumentException $e) { + } catch (InvalidArgumentException|\InvalidArgumentException $e) { $debugger->addException($e); $block = null; } @@ -527,7 +524,7 @@ class FlexCollection extends ObjectCollection implements FlexCollectionInterface { if ($value) { foreach ($this as $element) { - if (mb_strtolower($element->getProperty($field)) === mb_strtolower($value)) { + if (mb_strtolower((string) $element->getProperty($field)) === mb_strtolower($value)) { return $element; } } @@ -692,7 +689,7 @@ class FlexCollection extends ObjectCollection implements FlexCollectionInterface */ public function getType($prefix = false) { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use ->getFlexType() method instead', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use ->getFlexType() method instead', E_USER_DEPRECATED); $type = $prefix ? $this->getTypePrefix() : ''; @@ -716,7 +713,7 @@ class FlexCollection extends ObjectCollection implements FlexCollectionInterface 'collection' => $this ]); } - if (strpos($name, 'onFlexCollection') !== 0 && strpos($name, 'on') === 0) { + if (!str_starts_with($name, 'onFlexCollection') && str_starts_with($name, 'on')) { $name = 'onFlexCollection' . substr($name, 2); } diff --git a/system/src/Grav/Framework/Flex/FlexDirectory.php b/system/src/Grav/Framework/Flex/FlexDirectory.php index 3fb2f30bb..8928f8cc5 100644 --- a/system/src/Grav/Framework/Flex/FlexDirectory.php +++ b/system/src/Grav/Framework/Flex/FlexDirectory.php @@ -402,7 +402,7 @@ class FlexDirectory implements FlexDirectoryInterface */ public function getIndex(?array $keys = null, ?string $keyField = null): FlexIndexInterface { - $keyField = $keyField ?? ''; + $keyField ??= ''; $index = $this->indexes[$keyField] ?? $this->loadIndex($keyField); $index = clone $index; @@ -429,7 +429,7 @@ class FlexDirectory implements FlexDirectoryInterface return $this->createObject([], ''); } - $keyField = $keyField ?? ''; + $keyField ??= ''; $index = $this->indexes[$keyField] ?? $this->loadIndex($keyField); return $index->get($key); @@ -908,14 +908,14 @@ class FlexDirectory implements FlexDirectoryInterface $object = $call['object'] ?? null; $method = array_shift($params); $not = false; - if (str_starts_with($method, '!')) { - $method = substr($method, 1); + if (str_starts_with((string) $method, '!')) { + $method = substr((string) $method, 1); $not = true; - } elseif (str_starts_with($method, 'not ')) { - $method = substr($method, 4); + } elseif (str_starts_with((string) $method, 'not ')) { + $method = substr((string) $method, 4); $not = true; } - $method = trim($method); + $method = trim((string) $method); if ($object && method_exists($object, $method)) { $value = $object->{$method}(...$params); @@ -944,14 +944,14 @@ class FlexDirectory implements FlexDirectoryInterface $object = $call['object'] ?? null; $permission = array_shift($params); $not = false; - if (str_starts_with($permission, '!')) { - $permission = substr($permission, 1); + if (str_starts_with((string) $permission, '!')) { + $permission = substr((string) $permission, 1); $not = true; - } elseif (str_starts_with($permission, 'not ')) { - $permission = substr($permission, 4); + } elseif (str_starts_with((string) $permission, 'not ')) { + $permission = substr((string) $permission, 4); $not = true; } - $permission = trim($permission); + $permission = trim((string) $permission); if ($object) { $value = $object->isAuthorized($permission) ?? false; @@ -1111,7 +1111,7 @@ class FlexDirectory implements FlexDirectoryInterface */ public function getType(): string { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use ->getFlexType() method instead', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use ->getFlexType() method instead', E_USER_DEPRECATED); return $this->type; } @@ -1124,7 +1124,7 @@ class FlexDirectory implements FlexDirectoryInterface */ public function update(array $data, ?string $key = null): FlexObjectInterface { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() should not be used anymore: use $object->update()->save() instead.', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() should not be used anymore: use $object->update()->save() instead.', E_USER_DEPRECATED); $object = null !== $key ? $this->getIndex()->get($key): null; @@ -1175,7 +1175,7 @@ class FlexDirectory implements FlexDirectoryInterface */ public function remove(string $key): ?FlexObjectInterface { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() should not be used anymore: use $object->delete() instead.', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() should not be used anymore: use $object->delete() instead.', E_USER_DEPRECATED); $object = $this->getIndex()->get($key); if (!$object) { diff --git a/system/src/Grav/Framework/Flex/FlexDirectoryForm.php b/system/src/Grav/Framework/Flex/FlexDirectoryForm.php index 01041f711..aea03d317 100644 --- a/system/src/Grav/Framework/Flex/FlexDirectoryForm.php +++ b/system/src/Grav/Framework/Flex/FlexDirectoryForm.php @@ -148,11 +148,10 @@ class FlexDirectoryForm implements FlexDirectoryFormInterface, JsonSerializable /** * @param string $name - * @param mixed $default * @param string|null $separator * @return mixed */ - public function get($name, $default = null, $separator = null) + public function get($name, mixed $default = null, $separator = null) { switch (strtolower($name)) { case 'id': @@ -176,11 +175,10 @@ class FlexDirectoryForm implements FlexDirectoryFormInterface, JsonSerializable /** * @param string $name - * @param mixed $value * @param string|null $separator * @return $this */ - public function set($name, $value, $separator = null) + public function set($name, mixed $value, $separator = null) { switch (strtolower($name)) { case 'id': @@ -374,11 +372,10 @@ class FlexDirectoryForm implements FlexDirectoryFormInterface, JsonSerializable /** * @param string $name - * @param mixed $value * @return void */ #[\ReturnTypeWillChange] - public function __set($name, $value) + public function __set($name, mixed $value) { $method = "set{$name}"; if (method_exists($this, $method)) { diff --git a/system/src/Grav/Framework/Flex/FlexForm.php b/system/src/Grav/Framework/Flex/FlexForm.php index 2d00b9d67..f08456bc5 100644 --- a/system/src/Grav/Framework/Flex/FlexForm.php +++ b/system/src/Grav/Framework/Flex/FlexForm.php @@ -191,11 +191,10 @@ class FlexForm implements FlexObjectFormInterface, JsonSerializable /** * @param string $name - * @param mixed $default * @param string|null $separator * @return mixed */ - public function get($name, $default = null, $separator = null) + public function get($name, mixed $default = null, $separator = null) { switch (strtolower($name)) { case 'id': @@ -219,11 +218,10 @@ class FlexForm implements FlexObjectFormInterface, JsonSerializable /** * @param string $name - * @param mixed $value * @param string|null $separator * @return FlexForm */ - public function set($name, $value, $separator = null) + public function set($name, mixed $value, $separator = null) { switch (strtolower($name)) { case 'id': @@ -460,11 +458,10 @@ class FlexForm implements FlexObjectFormInterface, JsonSerializable /** * @param string $name - * @param mixed $value * @return void */ #[\ReturnTypeWillChange] - public function __set($name, $value) + public function __set($name, mixed $value) { $method = "set{$name}"; if (method_exists($this, $method)) { diff --git a/system/src/Grav/Framework/Flex/FlexFormFlash.php b/system/src/Grav/Framework/Flex/FlexFormFlash.php index 084c346b9..2e04cc895 100644 --- a/system/src/Grav/Framework/Flex/FlexFormFlash.php +++ b/system/src/Grav/Framework/Flex/FlexFormFlash.php @@ -103,7 +103,7 @@ class FlexFormFlash extends FormFlash { parent::init($data, $config); - $data = $data ?? []; + $data ??= []; /** @var FlexObjectInterface|null $object */ $object = $config['object'] ?? null; $create = true; diff --git a/system/src/Grav/Framework/Flex/FlexIdentifier.php b/system/src/Grav/Framework/Flex/FlexIdentifier.php index ec47ed8c9..aaa03d82f 100644 --- a/system/src/Grav/Framework/Flex/FlexIdentifier.php +++ b/system/src/Grav/Framework/Flex/FlexIdentifier.php @@ -15,8 +15,6 @@ use RuntimeException; */ class FlexIdentifier extends Identifier { - /** @var string */ - private $keyField; /** @var FlexObjectInterface|null */ private $object = null; @@ -38,11 +36,9 @@ class FlexIdentifier extends Identifier * @param string $type * @param string $keyField */ - public function __construct(string $id, string $type, string $keyField = 'key') + public function __construct(string $id, string $type, private readonly string $keyField = 'key') { parent::__construct($id, $type); - - $this->keyField = $keyField; } /** diff --git a/system/src/Grav/Framework/Flex/FlexIndex.php b/system/src/Grav/Framework/Flex/FlexIndex.php index 4f73a3e35..bbfbebac2 100644 --- a/system/src/Grav/Framework/Flex/FlexIndex.php +++ b/system/src/Grav/Framework/Flex/FlexIndex.php @@ -44,9 +44,6 @@ use function in_array; class FlexIndex extends ObjectIndex implements FlexIndexInterface { const VERSION = 1; - - /** @var FlexDirectory|null */ - private $_flexDirectory; /** @var string */ private $_keyField = 'storage_key'; /** @var array */ @@ -104,18 +101,16 @@ class FlexIndex extends ObjectIndex implements FlexIndexInterface * Initializes a new FlexIndex. * * @param array $entries - * @param FlexDirectory|null $directory + * @param FlexDirectory|null $_flexDirectory */ - public function __construct(array $entries = [], ?FlexDirectory $directory = null) + public function __construct(array $entries = [], private ?FlexDirectory $_flexDirectory = null) { // @phpstan-ignore-next-line - if (get_class($this) === __CLASS__) { - user_error('Using ' . __CLASS__ . ' directly is deprecated since Grav 1.7, use \Grav\Common\Flex\Types\Generic\GenericIndex or your own class instead', E_USER_DEPRECATED); + if (static::class === self::class) { + user_error('Using ' . self::class . ' directly is deprecated since Grav 1.7, use \Grav\Common\Flex\Types\Generic\GenericIndex or your own class instead', E_USER_DEPRECATED); } parent::__construct($entries); - - $this->_flexDirectory = $directory; $this->setKeyField(null); } @@ -147,8 +142,8 @@ class FlexIndex extends ObjectIndex implements FlexIndexInterface $list = []; foreach ($implements as $interface) { - if ($pos = strrpos($interface, '\\')) { - $interface = substr($interface, $pos+1); + if ($pos = strrpos((string) $interface, '\\')) { + $interface = substr((string) $interface, $pos+1); } $list[] = Inflector::hyphenize(str_replace('Interface', '', $interface)); @@ -421,7 +416,7 @@ class FlexIndex extends ObjectIndex implements FlexIndexInterface } // Order by current field. - if (strtoupper($ordering) === 'DESC') { + if (strtoupper((string) $ordering) === 'DESC') { arsort($search, SORT_NATURAL | SORT_FLAG_CASE); } else { asort($search, SORT_NATURAL | SORT_FLAG_CASE); @@ -922,7 +917,7 @@ class FlexIndex extends ObjectIndex implements FlexIndexInterface */ public function getType($prefix = false) { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use ->getFlexType() method instead', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use ->getFlexType() method instead', E_USER_DEPRECATED); $type = $prefix ? $this->getTypePrefix() : ''; diff --git a/system/src/Grav/Framework/Flex/FlexObject.php b/system/src/Grav/Framework/Flex/FlexObject.php index 8be308189..676302042 100644 --- a/system/src/Grav/Framework/Flex/FlexObject.php +++ b/system/src/Grav/Framework/Flex/FlexObject.php @@ -51,7 +51,7 @@ use function json_encode; * Class FlexObject * @package Grav\Framework\Flex */ -class FlexObject implements FlexObjectInterface, FlexAuthorizeInterface +class FlexObject implements FlexObjectInterface, FlexAuthorizeInterface, \Stringable { use ObjectTrait; use LazyPropertyTrait { @@ -62,9 +62,6 @@ class FlexObject implements FlexObjectInterface, FlexAuthorizeInterface use NestedArrayAccessTrait; use FlexAuthorizeTrait; use FlexRelatedDirectoryTrait; - - /** @var FlexDirectory */ - private $_flexDirectory; /** @var FlexFormInterface[] */ private $_forms = []; /** @var Blueprint[] */ @@ -122,14 +119,12 @@ class FlexObject implements FlexObjectInterface, FlexAuthorizeInterface * {@inheritdoc} * @see FlexObjectInterface::__construct() */ - public function __construct(array $elements, $key, FlexDirectory $directory, bool $validate = false) + public function __construct(array $elements, $key, private FlexDirectory $_flexDirectory, bool $validate = false) { - if (get_class($this) === __CLASS__) { - user_error('Using ' . __CLASS__ . ' directly is deprecated since Grav 1.7, use \Grav\Common\Flex\Types\Generic\GenericObject or your own class instead', E_USER_DEPRECATED); + if (static::class === self::class) { + user_error('Using ' . self::class . ' directly is deprecated since Grav 1.7, use \Grav\Common\Flex\Types\Generic\GenericObject or your own class instead', E_USER_DEPRECATED); } - $this->_flexDirectory = $directory; - if (isset($elements['__META'])) { $this->setMetaData($elements['__META']); unset($elements['__META']); @@ -168,8 +163,8 @@ class FlexObject implements FlexObjectInterface, FlexAuthorizeInterface $list = []; foreach ($implements as $interface) { - if ($pos = strrpos($interface, '\\')) { - $interface = substr($interface, $pos+1); + if ($pos = strrpos((string) $interface, '\\')) { + $interface = substr((string) $interface, $pos+1); } $list[] = Inflector::hyphenize(str_replace('Interface', '', $interface)); @@ -238,7 +233,7 @@ class FlexObject implements FlexObjectInterface, FlexAuthorizeInterface // Inject back elements which are missing in the filesystem. $data = $this->getBlueprint()->flattenData($current); foreach ($data as $property => $value) { - if (strpos($property, '.') === false) { + if (!str_contains($property, '.')) { $this->defProperty($property, $value); } else { $this->defNestedProperty($property, $value); @@ -293,7 +288,7 @@ class FlexObject implements FlexObjectInterface, FlexAuthorizeInterface $weight = 0; foreach ($properties as $property) { - if (strpos($property, '.')) { + if (strpos((string) $property, '.')) { $weight += $this->searchNestedProperty($property, $search, $options); } else { $weight += $this->searchProperty($property, $search, $options); @@ -364,7 +359,7 @@ class FlexObject implements FlexObjectInterface, FlexAuthorizeInterface */ public function searchProperty(string $property, string $search, ?array $options = null): float { - $options = $options ?? (array)$this->getFlexDirectory()->getConfig('data.search.options'); + $options ??= (array)$this->getFlexDirectory()->getConfig('data.search.options'); $value = $this->getProperty($property); return $this->searchValue($property, $value, $search, $options); @@ -378,7 +373,7 @@ class FlexObject implements FlexObjectInterface, FlexAuthorizeInterface */ public function searchNestedProperty(string $property, string $search, ?array $options = null): float { - $options = $options ?? (array)$this->getFlexDirectory()->getConfig('data.search.options'); + $options ??= (array)$this->getFlexDirectory()->getConfig('data.search.options'); if ($property === 'key') { $value = $this->getKey(); } else { @@ -390,14 +385,13 @@ class FlexObject implements FlexObjectInterface, FlexAuthorizeInterface /** * @param string $name - * @param mixed $value * @param string $search * @param array|null $options * @return float */ - protected function searchValue(string $name, $value, string $search, ?array $options = null): float + protected function searchValue(string $name, mixed $value, string $search, ?array $options = null): float { - $options = $options ?? []; + $options ??= []; // Ignore empty search strings. $search = trim($search); @@ -585,11 +579,7 @@ class FlexObject implements FlexObjectInterface, FlexAuthorizeInterface $data = $cache ? $cache->get($key) : null; $block = $data ? HtmlBlock::fromArray($data) : null; - } catch (InvalidArgumentException $e) { - $debugger->addException($e); - - $block = null; - } catch (\InvalidArgumentException $e) { + } catch (InvalidArgumentException|\InvalidArgumentException $e) { $debugger->addException($e); $block = null; @@ -946,7 +936,7 @@ class FlexObject implements FlexObjectInterface, FlexAuthorizeInterface * @return string */ #[\ReturnTypeWillChange] - public function __toString() + public function __toString(): string { return $this->getFlexKey(); } @@ -1090,7 +1080,7 @@ class FlexObject implements FlexObjectInterface, FlexAuthorizeInterface protected function filterElements(array &$elements): void { if (isset($elements['storage_key'])) { - $elements['storage_key'] = trim($elements['storage_key']); + $elements['storage_key'] = trim((string) $elements['storage_key']); } if (isset($elements['storage_timestamp'])) { $elements['storage_timestamp'] = (int)$elements['storage_timestamp']; @@ -1184,7 +1174,7 @@ class FlexObject implements FlexObjectInterface, FlexAuthorizeInterface 'object' => $this ]); } - if (strpos($name, 'onFlexObject') !== 0 && strpos($name, 'on') === 0) { + if (!str_starts_with($name, 'onFlexObject') && str_starts_with($name, 'on')) { $name = 'onFlexObject' . substr($name, 2); } diff --git a/system/src/Grav/Framework/Flex/Interfaces/FlexDirectoryInterface.php b/system/src/Grav/Framework/Flex/Interfaces/FlexDirectoryInterface.php index bea37ee8d..9ad0fa62a 100644 --- a/system/src/Grav/Framework/Flex/Interfaces/FlexDirectoryInterface.php +++ b/system/src/Grav/Framework/Flex/Interfaces/FlexDirectoryInterface.php @@ -46,10 +46,9 @@ interface FlexDirectoryInterface extends FlexAuthorizeInterface /** * @param string|null $name - * @param mixed $default * @return mixed */ - public function getConfig(?string $name = null, $default = null); + public function getConfig(?string $name = null, mixed $default = null); /** * @param string|null $name diff --git a/system/src/Grav/Framework/Flex/Interfaces/FlexObjectInterface.php b/system/src/Grav/Framework/Flex/Interfaces/FlexObjectInterface.php index 5893c23de..84cd2fa6d 100644 --- a/system/src/Grav/Framework/Flex/Interfaces/FlexObjectInterface.php +++ b/system/src/Grav/Framework/Flex/Interfaces/FlexObjectInterface.php @@ -207,5 +207,5 @@ interface FlexObjectInterface extends FlexCommonInterface, NestedObjectInterface * @param string|null $separator Optional nested property separator. * @return mixed Returns value of the field. */ - public function getFormValue(string $name, $default = null, ?string $separator = null); + public function getFormValue(string $name, mixed $default = null, ?string $separator = null); } diff --git a/system/src/Grav/Framework/Flex/Pages/FlexPageObject.php b/system/src/Grav/Framework/Flex/Pages/FlexPageObject.php index 1e49734f8..3d9fddbc9 100644 --- a/system/src/Grav/Framework/Flex/Pages/FlexPageObject.php +++ b/system/src/Grav/Framework/Flex/Pages/FlexPageObject.php @@ -300,20 +300,18 @@ class FlexPageObject extends FlexObject implements PageInterface, FlexTranslateI return []; } - return array_map('trim', explode(',', $order)); + return array_map('trim', explode(',', (string) $order)); } // Overrides for header properties. - /** * Common logic to load header properties. * * @param string $property - * @param mixed $var * @param callable $filter * @return mixed|null */ - protected function loadHeaderProperty(string $property, $var, callable $filter) + protected function loadHeaderProperty(string $property, mixed $var, callable $filter) { // We have to use parent methods in order to avoid loops. $value = null === $var ? parent::getProperty($property) : null; @@ -333,11 +331,10 @@ class FlexPageObject extends FlexObject implements PageInterface, FlexTranslateI * Common logic to load header properties. * * @param string $property - * @param mixed $var * @param callable $filter * @return mixed|null */ - protected function loadProperty(string $property, $var, callable $filter) + protected function loadProperty(string $property, mixed $var, callable $filter) { // We have to use parent methods in order to avoid loops. $value = null === $var ? parent::getProperty($property) : null; @@ -396,7 +393,7 @@ class FlexPageObject extends FlexObject implements PageInterface, FlexTranslateI public function setNestedProperty($property, $value, $separator = null) { $separator = $separator ?: '.'; - if (strpos($property, 'header' . $separator) === 0) { + if (str_starts_with($property, 'header' . $separator)) { $this->getProperty('header')->set(str_replace('header' . $separator, '', $property), $value, $separator); return $this; @@ -415,7 +412,7 @@ class FlexPageObject extends FlexObject implements PageInterface, FlexTranslateI public function unsetNestedProperty($property, $separator = null) { $separator = $separator ?: '.'; - if (strpos($property, 'header' . $separator) === 0) { + if (str_starts_with($property, 'header' . $separator)) { $this->getProperty('header')->undef(str_replace('header' . $separator, '', $property), $separator); return $this; @@ -440,7 +437,7 @@ class FlexPageObject extends FlexObject implements PageInterface, FlexTranslateI } if (!$extended) { - $folder = !empty($elements['folder']) ? trim($elements['folder']) : ''; + $folder = !empty($elements['folder']) ? trim((string) $elements['folder']) : ''; if ($folder) { $order = !empty($elements['order']) ? (int)$elements['order'] : null; diff --git a/system/src/Grav/Framework/Flex/Pages/Traits/PageAuthorsTrait.php b/system/src/Grav/Framework/Flex/Pages/Traits/PageAuthorsTrait.php index 878c5cba6..7b0f8f201 100644 --- a/system/src/Grav/Framework/Flex/Pages/Traits/PageAuthorsTrait.php +++ b/system/src/Grav/Framework/Flex/Pages/Traits/PageAuthorsTrait.php @@ -118,7 +118,7 @@ trait PageAuthorsTrait */ public function isParentAuthorized(string $action, ?string $scope = null, ?UserInterface $user = null, bool $isAuthor = false): ?bool { - $scope = $scope ?? $this->getAuthorizeScope(); + $scope ??= $this->getAuthorizeScope(); $isMe = null === $user; if ($isMe) { diff --git a/system/src/Grav/Framework/Flex/Pages/Traits/PageContentTrait.php b/system/src/Grav/Framework/Flex/Pages/Traits/PageContentTrait.php index 99c5dfde1..4d58e981a 100644 --- a/system/src/Grav/Framework/Flex/Pages/Traits/PageContentTrait.php +++ b/system/src/Grav/Framework/Flex/Pages/Traits/PageContentTrait.php @@ -202,9 +202,7 @@ trait PageContentTrait return $this->loadHeaderProperty( 'title', $var, - function ($value) { - return trim($value ?? ($this->root() ? '' : ucfirst($this->slug()))); - } + fn($value) => trim((string) ($value ?? ($this->root() ? '' : ucfirst($this->slug())))) ); } @@ -216,9 +214,7 @@ trait PageContentTrait return $this->loadHeaderProperty( 'menu', $var, - function ($value) { - return trim($value ?: $this->title()); - } + fn($value) => trim((string) ($value ?: $this->title())) ); } @@ -230,9 +226,7 @@ trait PageContentTrait $value = $this->loadHeaderProperty( 'visible', $var, - function ($value) { - return ($value ?? $this->order() !== false) && !$this->isModule(); - } + fn($value) => ($value ?? $this->order() !== false) && !$this->isModule() ); return $value && $this->published(); @@ -246,9 +240,7 @@ trait PageContentTrait return $this->loadHeaderProperty( 'published', $var, - static function ($value) { - return (bool)($value ?? true); - } + static fn($value) => (bool)($value ?? true) ); } @@ -260,9 +252,7 @@ trait PageContentTrait return $this->loadHeaderProperty( 'publish_date', $var, - function ($value) { - return $value ? Utils::date2timestamp($value, $this->getProperty('dateformat')) : null; - } + fn($value) => $value ? Utils::date2timestamp($value, $this->getProperty('dateformat')) : null ); } @@ -274,9 +264,7 @@ trait PageContentTrait return $this->loadHeaderProperty( 'unpublish_date', $var, - function ($value) { - return $value ? Utils::date2timestamp($value, $this->getProperty('dateformat')) : null; - } + fn($value) => $value ? Utils::date2timestamp($value, $this->getProperty('dateformat')) : null ); } @@ -405,9 +393,7 @@ trait PageContentTrait return $this->loadHeaderProperty( 'last_modified', $var, - static function ($value) { - return (bool)($value ?? Grav::instance()['config']->get('system.pages.last_modified')); - } + static fn($value) => (bool)($value ?? Grav::instance()['config']->get('system.pages.last_modified')) ); } @@ -435,9 +421,7 @@ trait PageContentTrait return $this->loadHeaderProperty( 'dateformat', $var, - static function ($value) { - return $value; - } + static fn($value) => $value ); } @@ -568,7 +552,7 @@ trait PageContentTrait case 'folder': $folder = $this->folder(); - return null !== $folder ? preg_replace(static::PAGE_ORDER_PREFIX_REGEX, '', $folder) : ''; + return null !== $folder ? preg_replace(static::PAGE_ORDER_PREFIX_REGEX, '', (string) $folder) : ''; case 'slug': return $this->slug(); case 'published': @@ -610,9 +594,9 @@ trait PageContentTrait $content = $this->_summary ?? $this->content(); if ($textOnly) { - $content = strip_tags($content); + $content = strip_tags((string) $content); } - $content_size = mb_strwidth($content, 'utf-8'); + $content_size = mb_strwidth((string) $content, 'utf-8'); $summary_size = $this->_summary !== null ? $content_size : $this->getProperty('summary_size'); // Return calculated summary based on summary divider's position. @@ -626,14 +610,14 @@ trait PageContentTrait if ($format === 'short' && null !== $summary_size) { // Slice the string on breakpoint. if ($content_size > $summary_size) { - return mb_substr($content, 0, $summary_size); + return mb_substr((string) $content, 0, $summary_size); } return $content; } // If needed, get summary size from the config. - $size = $size ?? $config['size'] ?? null; + $size ??= $config['size'] ?? null; // Return calculated summary based on defaults. $size = is_numeric($size) ? (int)$size : -1; @@ -648,7 +632,7 @@ trait PageContentTrait // Only return string but not html, wrap whatever html tag you want when using. if ($textOnly) { - return mb_strimwidth($content, 0, $size, '...', 'UTF-8'); + return mb_strimwidth((string) $content, 0, $size, '...', 'UTF-8'); } $summary = Utils::truncateHTML($content, $size); @@ -819,7 +803,7 @@ trait PageContentTrait // Base64 encode any twig. $content = preg_replace_callback( ['/({#.*?#})/mu', '/({{.*?}})/mu', '/({%.*?%})/mu'], - static function ($matches) use ($token) { return $token[0] . base64_encode($matches[1]) . $token[1]; }, + static fn($matches) => $token[0] . base64_encode((string) $matches[1]) . $token[1], $content ); } @@ -830,8 +814,8 @@ trait PageContentTrait // Base64 decode the encoded twig. $content = preg_replace_callback( ['`' . $token[0] . '([A-Za-z0-9+/]+={0,2})' . $token[1] . '`mu'], - static function ($matches) { return base64_decode($matches[1]); }, - $content + static fn($matches) => base64_decode((string) $matches[1]), + (string) $content ); } diff --git a/system/src/Grav/Framework/Flex/Pages/Traits/PageLegacyTrait.php b/system/src/Grav/Framework/Flex/Pages/Traits/PageLegacyTrait.php index 37bca5e5a..581e4f2f2 100644 --- a/system/src/Grav/Framework/Flex/Pages/Traits/PageLegacyTrait.php +++ b/system/src/Grav/Framework/Flex/Pages/Traits/PageLegacyTrait.php @@ -55,7 +55,7 @@ trait PageLegacyTrait * @param string|null $extension * @return $this */ - public function init(SplFileInfo $file, $extension = null) + public function init(SplFileInfo $file, $extension = null): never { // TODO: throw new RuntimeException(__METHOD__ . '(): Not Implemented'); @@ -159,7 +159,7 @@ trait PageLegacyTrait // Set Cache-Control header. if ($cache_control) { - $headers['Cache-Control'] = strtolower($cache_control); + $headers['Cache-Control'] = strtolower((string) $cache_control); } // Set Last-Modified header. @@ -374,7 +374,7 @@ trait PageLegacyTrait } $post_value = $_POST['blueprint']; - $sanitized_value = htmlspecialchars(strip_tags($post_value), ENT_QUOTES, 'UTF-8'); + $sanitized_value = htmlspecialchars(strip_tags((string) $post_value), ENT_QUOTES, 'UTF-8'); return $sanitized_value ?: $this->template(); } @@ -467,7 +467,7 @@ trait PageLegacyTrait 'name', $var, function ($value) { - $value = $value ?? $this->getMetaData()['template'] ?? 'default'; + $value ??= $this->getMetaData()['template'] ?? 'default'; if (!preg_match('/\.md$/', $value)) { $language = $this->language(); if ($language) { @@ -507,9 +507,7 @@ trait PageLegacyTrait return $this->loadHeaderProperty( 'template', $var, - function ($value) { - return trim($value ?? (($this->isModule() ? 'modular/' : '') . str_replace($this->extension(), '', $this->name()))); - } + fn($value) => trim($value ?? (($this->isModule() ? 'modular/' : '') . str_replace($this->extension(), '', $this->name()))) ); } @@ -525,9 +523,7 @@ trait PageLegacyTrait return $this->loadHeaderProperty( 'template_format', $var, - function ($value) { - return ltrim($value ?? $this->getNestedProperty('header.append_url_extension') ?: Utils::getPageFormat(), '.'); - } + fn($value) => ltrim((string) ($value ?? $this->getNestedProperty('header.append_url_extension') ?: Utils::getPageFormat()), '.') ); } @@ -563,9 +559,7 @@ trait PageLegacyTrait return $this->loadHeaderProperty( 'expires', $var, - static function ($value) { - return (int)($value ?? Grav::instance()['config']->get('system.pages.expires')); - } + static fn($value) => (int)($value ?? Grav::instance()['config']->get('system.pages.expires')) ); } @@ -581,9 +575,7 @@ trait PageLegacyTrait return $this->loadHeaderProperty( 'cache_control', $var, - static function ($value) { - return ((string)($value ?? Grav::instance()['config']->get('system.pages.cache_control'))) ?: null; - } + static fn($value) => ((string)($value ?? Grav::instance()['config']->get('system.pages.cache_control'))) ?: null ); } @@ -596,9 +588,7 @@ trait PageLegacyTrait return $this->loadHeaderProperty( 'ssl', $var, - static function ($value) { - return $value ? (bool)$value : null; - } + static fn($value) => $value ? (bool)$value : null ); } @@ -655,7 +645,7 @@ trait PageLegacyTrait $this->_metadata[$prop_key] = [ 'name' => $prop_key, 'property' => $prop_key, - 'content' => $escape ? htmlspecialchars($prop_value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $prop_value + 'content' => $escape ? htmlspecialchars((string) $prop_value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $prop_value ]; } } elseif ($value) { @@ -663,16 +653,16 @@ trait PageLegacyTrait if (in_array($key, $header_tag_http_equivs, true)) { $this->_metadata[$key] = [ 'http_equiv' => $key, - 'content' => $escape ? htmlspecialchars($value, ENT_COMPAT, 'UTF-8') : $value + 'content' => $escape ? htmlspecialchars((string) $value, ENT_COMPAT, 'UTF-8') : $value ]; } elseif ($key === 'charset') { - $this->_metadata[$key] = ['charset' => $escape ? htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $value]; + $this->_metadata[$key] = ['charset' => $escape ? htmlspecialchars((string) $value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $value]; } else { // if it's a social metadata with separator, render as property $separator = strpos($key, ':'); $hasSeparator = $separator && $separator < strlen($key) - 1; $entry = [ - 'content' => $escape ? htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $value + 'content' => $escape ? htmlspecialchars((string) $value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $value ]; if ($hasSeparator && !Utils::startsWith($key, 'twitter')) { @@ -709,9 +699,7 @@ trait PageLegacyTrait return $this->loadHeaderProperty( 'etag', $var, - static function ($value) { - return (bool)($value ?? Grav::instance()['config']->get('system.pages.etag')); - } + static fn($value) => (bool)($value ?? Grav::instance()['config']->get('system.pages.etag')) ); } @@ -770,9 +758,7 @@ trait PageLegacyTrait return $this->loadHeaderProperty( 'order_dir', $var, - static function ($value) { - return strtolower(trim($value) ?: Grav::instance()['config']->get('system.pages.order.dir')) === 'desc' ? 'desc' : 'asc'; - } + static fn($value) => strtolower((string) (trim((string) $value) ?: Grav::instance()['config']->get('system.pages.order.dir'))) === 'desc' ? 'desc' : 'asc' ); } @@ -792,9 +778,7 @@ trait PageLegacyTrait return $this->loadHeaderProperty( 'order_by', $var, - static function ($value) { - return trim($value) ?: Grav::instance()['config']->get('system.pages.order.by'); - } + static fn($value) => trim((string) $value) ?: Grav::instance()['config']->get('system.pages.order.by') ); } @@ -809,9 +793,7 @@ trait PageLegacyTrait return $this->loadHeaderProperty( 'order_manual', $var, - static function ($value) { - return (array)$value; - } + static fn($value) => (array)$value ); } @@ -827,9 +809,7 @@ trait PageLegacyTrait return $this->loadHeaderProperty( 'max_count', $var, - static function ($value) { - return (int)($value ?? Grav::instance()['config']->get('system.pages.list.count')); - } + static fn($value) => (int)($value ?? Grav::instance()['config']->get('system.pages.list.count')) ); } @@ -863,7 +843,7 @@ trait PageLegacyTrait } } - return (bool)($this->getProperty('modular_twig') ?? strpos($this->slug(), '_') === 0); + return (bool)($this->getProperty('modular_twig') ?? str_starts_with($this->slug(), '_')); } /** diff --git a/system/src/Grav/Framework/Flex/Pages/Traits/PageRoutableTrait.php b/system/src/Grav/Framework/Flex/Pages/Traits/PageRoutableTrait.php index b5b3f899e..6892d9922 100644 --- a/system/src/Grav/Framework/Flex/Pages/Traits/PageRoutableTrait.php +++ b/system/src/Grav/Framework/Flex/Pages/Traits/PageRoutableTrait.php @@ -69,9 +69,7 @@ trait PageRoutableTrait $value = $this->loadHeaderProperty( 'routable', $var, - static function ($value) { - return $value ?? true; - } + static fn($value) => $value ?? true ); return $value && $this->published() && !$this->isModule() && !$this->root() && $this->getLanguages(true); @@ -300,9 +298,7 @@ trait PageRoutableTrait return $this->loadHeaderProperty( 'redirect', $var, - static function ($value) { - return trim($value) ?: null; - } + static fn($value) => trim((string) $value) ?: null ); } diff --git a/system/src/Grav/Framework/Flex/Pages/Traits/PageTranslateTrait.php b/system/src/Grav/Framework/Flex/Pages/Traits/PageTranslateTrait.php index 6fc09fb0e..1a0c6e588 100644 --- a/system/src/Grav/Framework/Flex/Pages/Traits/PageTranslateTrait.php +++ b/system/src/Grav/Framework/Flex/Pages/Traits/PageTranslateTrait.php @@ -232,7 +232,7 @@ trait PageTranslateTrait 'lang', $var, function ($value) { - $value = $value ?? $this->getMetaData()['lang'] ?? ''; + $value ??= $this->getMetaData()['lang'] ?? ''; return trim($value) ?: null; } @@ -272,7 +272,7 @@ trait PageTranslateTrait */ protected function getFallbackLanguages(?string $languageCode = null, ?bool $fallback = null): array { - $fallback = $fallback ?? true; + $fallback ??= true; if (!$fallback && null !== $languageCode) { return [$languageCode]; } @@ -281,7 +281,7 @@ trait PageTranslateTrait /** @var Language $language */ $language = $grav['language']; - $languageCode = $languageCode ?? ($language->getLanguage() ?: ''); + $languageCode ??= $language->getLanguage() ?: ''; if ($languageCode === '' && $fallback) { return $language->getFallbackLanguages(null, true); } diff --git a/system/src/Grav/Framework/Flex/Storage/AbstractFilesystemStorage.php b/system/src/Grav/Framework/Flex/Storage/AbstractFilesystemStorage.php index d919f3a4b..ccb164f10 100644 --- a/system/src/Grav/Framework/Flex/Storage/AbstractFilesystemStorage.php +++ b/system/src/Grav/Framework/Flex/Storage/AbstractFilesystemStorage.php @@ -163,19 +163,12 @@ abstract class AbstractFilesystemStorage implements FlexStorageInterface $filename = $this->resolvePath($filename); // TODO: start using the new file classes. - switch ($this->dataFormatter->getDefaultFileExtension()) { - case '.json': - $file = CompiledJsonFile::instance($filename); - break; - case '.yaml': - $file = CompiledYamlFile::instance($filename); - break; - case '.md': - $file = CompiledMarkdownFile::instance($filename); - break; - default: - throw new RuntimeException('Unknown extension type ' . $this->dataFormatter->getDefaultFileExtension()); - } + $file = match ($this->dataFormatter->getDefaultFileExtension()) { + '.json' => CompiledJsonFile::instance($filename), + '.yaml' => CompiledYamlFile::instance($filename), + '.md' => CompiledMarkdownFile::instance($filename), + default => throw new RuntimeException('Unknown extension type ' . $this->dataFormatter->getDefaultFileExtension()), + }; return $file; } diff --git a/system/src/Grav/Framework/Flex/Storage/FileStorage.php b/system/src/Grav/Framework/Flex/Storage/FileStorage.php index 4ed0660fd..fabe798d8 100644 --- a/system/src/Grav/Framework/Flex/Storage/FileStorage.php +++ b/system/src/Grav/Framework/Flex/Storage/FileStorage.php @@ -146,7 +146,7 @@ class FileStorage extends FolderStorage $list = []; /** @var SplFileInfo $info */ foreach ($iterator as $filename => $info) { - if (!$info->isFile() || !($key = $this->getKeyFromPath($filename)) || strpos($info->getFilename(), '.') === 0) { + if (!$info->isFile() || !($key = $this->getKeyFromPath($filename)) || str_starts_with($info->getFilename(), '.')) { continue; } diff --git a/system/src/Grav/Framework/Flex/Storage/FolderStorage.php b/system/src/Grav/Framework/Flex/Storage/FolderStorage.php index 790eafdc4..0f0a95a16 100644 --- a/system/src/Grav/Framework/Flex/Storage/FolderStorage.php +++ b/system/src/Grav/Framework/Flex/Storage/FolderStorage.php @@ -413,7 +413,7 @@ class FolderStorage extends AbstractFilesystemStorage if (isset($row[$this->keyField])) { $key = $row[$this->keyField]; } - if (strpos($key, '@@') !== false) { + if (str_contains((string) $key, '@@')) { $key = $this->getNewKey(); } @@ -584,7 +584,7 @@ class FolderStorage extends AbstractFilesystemStorage return $this->meta[$key]; } - if ($key && strpos($key, '@@') === false) { + if ($key && !str_contains($key, '@@')) { $filename = $this->getPathFromKey($key); $modified = is_file($filename) ? filemtime($filename) : 0; } else { @@ -613,7 +613,7 @@ class FolderStorage extends AbstractFilesystemStorage $list = []; /** @var SplFileInfo $info */ foreach ($iterator as $filename => $info) { - if (!$info->isDir() || strpos($info->getFilename(), '.') === 0) { + if (!$info->isDir() || str_starts_with($info->getFilename(), '.')) { continue; } @@ -639,7 +639,7 @@ class FolderStorage extends AbstractFilesystemStorage $list = [[]]; /** @var SplFileInfo $info */ foreach ($iterator as $filename => $info) { - if (!$info->isDir() || strpos($info->getFilename(), '.') === 0) { + if (!$info->isDir() || str_starts_with($info->getFilename(), '.')) { continue; } diff --git a/system/src/Grav/Framework/Flex/Storage/SimpleStorage.php b/system/src/Grav/Framework/Flex/Storage/SimpleStorage.php index 4ffddd3b2..6e27f4497 100644 --- a/system/src/Grav/Framework/Flex/Storage/SimpleStorage.php +++ b/system/src/Grav/Framework/Flex/Storage/SimpleStorage.php @@ -119,7 +119,7 @@ class SimpleStorage extends AbstractFilesystemStorage $this->buildIndex(); } - return $key && strpos($key, '@@') === false && isset($this->data[$key]); + return $key && !str_contains($key, '@@') && isset($this->data[$key]); } /** @@ -355,7 +355,7 @@ class SimpleStorage extends AbstractFilesystemStorage if (isset($row[$this->keyField])) { $key = $row[$this->keyField]; } - if (strpos($key, '@@') !== false) { + if (str_contains((string) $key, '@@')) { $key = $this->getNewKey(); } diff --git a/system/src/Grav/Framework/Flex/Traits/FlexAuthorizeTrait.php b/system/src/Grav/Framework/Flex/Traits/FlexAuthorizeTrait.php index 17b3212b5..48f8ab1cb 100644 --- a/system/src/Grav/Framework/Flex/Traits/FlexAuthorizeTrait.php +++ b/system/src/Grav/Framework/Flex/Traits/FlexAuthorizeTrait.php @@ -37,7 +37,7 @@ trait FlexAuthorizeTrait public function isAuthorized(string $action, ?string $scope = null, ?UserInterface $user = null): ?bool { $action = $this->getAuthorizeAction($action); - $scope = $scope ?? $this->getAuthorizeScope(); + $scope ??= $this->getAuthorizeScope(); $isMe = null === $user; if ($isMe) { diff --git a/system/src/Grav/Framework/Flex/Traits/FlexMediaTrait.php b/system/src/Grav/Framework/Flex/Traits/FlexMediaTrait.php index e87b87886..ecf1a13aa 100644 --- a/system/src/Grav/Framework/Flex/Traits/FlexMediaTrait.php +++ b/system/src/Grav/Framework/Flex/Traits/FlexMediaTrait.php @@ -143,7 +143,7 @@ trait FlexMediaTrait // Set media folder for media fields. if (isset($var)) { $folder = $settings[$var] ?? ''; - if (in_array(rtrim($folder, '/'), ['', '@self', 'self@', '@self@'], true)) { + if (in_array(rtrim((string) $folder, '/'), ['', '@self', 'self@', '@self@'], true)) { $settings[$var] = $this->getMediaFolder(); $settings['self'] = true; } else { diff --git a/system/src/Grav/Framework/Flex/Traits/FlexRelatedDirectoryTrait.php b/system/src/Grav/Framework/Flex/Traits/FlexRelatedDirectoryTrait.php index 2922f030c..2e7aa65f0 100644 --- a/system/src/Grav/Framework/Flex/Traits/FlexRelatedDirectoryTrait.php +++ b/system/src/Grav/Framework/Flex/Traits/FlexRelatedDirectoryTrait.php @@ -35,9 +35,7 @@ trait FlexRelatedDirectoryTrait $list = $this->getNestedProperty($property) ?: []; /** @var FlexCollectionInterface $collection */ - $collection = $collection->filter(static function ($object) use ($list) { - return in_array($object->getKey(), $list, true); - }); + $collection = $collection->filter(static fn($object) => in_array($object->getKey(), $list, true)); return $collection; } diff --git a/system/src/Grav/Framework/Form/FormFlash.php b/system/src/Grav/Framework/Form/FormFlash.php index 8de758890..0a0ae1741 100644 --- a/system/src/Grav/Framework/Form/FormFlash.php +++ b/system/src/Grav/Framework/Form/FormFlash.php @@ -64,7 +64,7 @@ class FormFlash implements FormFlashInterface { // Backwards compatibility with Grav 1.6 plugins. if (!is_array($config)) { - user_error(__CLASS__ . '::' . __FUNCTION__ . '($sessionId, $uniqueId, $formName) is deprecated since Grav 1.6.11, use $config parameter instead', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '($sessionId, $uniqueId, $formName) is deprecated since Grav 1.6.11, use $config parameter instead', E_USER_DEPRECATED); $args = func_get_args(); $config = [ @@ -72,9 +72,7 @@ class FormFlash implements FormFlashInterface 'unique_id' => $args[1] ?? null, 'form_name' => $args[2] ?? null, ]; - $config = array_filter($config, static function ($val) { - return $val !== null; - }); + $config = array_filter($config, static fn($val) => $val !== null); } $this->id = $config['id'] ?? ''; @@ -131,7 +129,7 @@ class FormFlash implements FormFlashInterface if ($exists) { try { $data = (array)$file->content(); - } catch (Exception $e) { + } catch (Exception) { } } @@ -168,7 +166,7 @@ class FormFlash implements FormFlashInterface */ public function getUniqieId(): string { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6.11, use ->getUniqueId() method instead', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6.11, use ->getUniqueId() method instead', E_USER_DEPRECATED); return $this->getUniqueId(); } diff --git a/system/src/Grav/Framework/Form/FormFlashFile.php b/system/src/Grav/Framework/Form/FormFlashFile.php index 3dcf59e2a..bbe312d45 100644 --- a/system/src/Grav/Framework/Form/FormFlashFile.php +++ b/system/src/Grav/Framework/Form/FormFlashFile.php @@ -30,12 +30,8 @@ class FormFlashFile implements UploadedFileInterface, JsonSerializable { /** @var string */ private $id; - /** @var string */ - private $field; /** @var bool */ private $moved = false; - /** @var array */ - private $upload; /** @var FormFlash */ private $flash; @@ -45,11 +41,9 @@ class FormFlashFile implements UploadedFileInterface, JsonSerializable * @param array $upload * @param FormFlash $flash */ - public function __construct(string $field, array $upload, FormFlash $flash) + public function __construct(private readonly string $field, private array $upload, FormFlash $flash) { $this->id = $flash->getId() ?: $flash->getUniqueId(); - $this->field = $field; - $this->upload = $upload; $this->flash = $flash; $tmpFile = $this->getTmpFile(); diff --git a/system/src/Grav/Framework/Form/Traits/FormTrait.php b/system/src/Grav/Framework/Form/Traits/FormTrait.php index b64dd9a9b..4c07468f6 100644 --- a/system/src/Grav/Framework/Form/Traits/FormTrait.php +++ b/system/src/Grav/Framework/Form/Traits/FormTrait.php @@ -612,7 +612,7 @@ trait FormTrait $path = str_replace(array_keys($dataMap), array_values($dataMap), $flashLookupFolder); // Make sure we only return valid paths. - return strpos($path, '!!') === false ? rtrim($path, '/') : null; + return !str_contains($path, '!!') ? rtrim($path, '/') : null; } /** @@ -634,7 +634,7 @@ trait FormTrait $path = str_replace(array_keys($dataMap), array_values($dataMap), $flashLookupFolder); // Make sure we only return valid paths. - return strpos($path, '!!') === false ? rtrim($path, '/') : null; + return !str_contains($path, '!!') ? rtrim($path, '/') : null; } /** @@ -844,10 +844,10 @@ trait FormTrait foreach ($data as $key => &$value) { if (is_array($value)) { $value = $this->jsonDecode($value); - } elseif (trim($value) === '') { + } elseif (trim((string) $value) === '') { unset($data[$key]); } else { - $value = json_decode($value, true); + $value = json_decode((string) $value, true); if ($value === null && json_last_error() !== JSON_ERROR_NONE) { unset($data[$key]); $this->setError("Badly encoded JSON data (for {$key}) was sent to the form"); diff --git a/system/src/Grav/Framework/Media/Interfaces/MediaObjectInterface.php b/system/src/Grav/Framework/Media/Interfaces/MediaObjectInterface.php index e177c9f0b..773b53aa2 100644 --- a/system/src/Grav/Framework/Media/Interfaces/MediaObjectInterface.php +++ b/system/src/Grav/Framework/Media/Interfaces/MediaObjectInterface.php @@ -43,5 +43,5 @@ interface MediaObjectInterface * @param string|null $separator Separator, defaults to '.' * @return mixed Value. */ - public function get($name, $default = null, $separator = null); + public function get($name, mixed $default = null, $separator = null); } diff --git a/system/src/Grav/Framework/Media/MediaIdentifier.php b/system/src/Grav/Framework/Media/MediaIdentifier.php index 986e997c7..a8ed764e5 100644 --- a/system/src/Grav/Framework/Media/MediaIdentifier.php +++ b/system/src/Grav/Framework/Media/MediaIdentifier.php @@ -121,7 +121,7 @@ class MediaIdentifier extends Identifier do { $part = array_shift($parts); $folder .= "/{$part}"; - } while (!str_starts_with($part, 'flex-')); + } while (!str_starts_with((string) $part, 'flex-')); $uniqueId = array_shift($parts); $field = array_shift($parts); diff --git a/system/src/Grav/Framework/Media/MediaObject.php b/system/src/Grav/Framework/Media/MediaObject.php index 8a438bf93..49fc4381f 100644 --- a/system/src/Grav/Framework/Media/MediaObject.php +++ b/system/src/Grav/Framework/Media/MediaObject.php @@ -23,11 +23,6 @@ class MediaObject implements MediaObjectInterface /** @var GravMediaObjectInterface|null */ public $media; - /** @var string|null */ - private $field; - /** @var string */ - private $filename; - /** * MediaObject constructor. * @param string|null $field @@ -35,10 +30,8 @@ class MediaObject implements MediaObjectInterface * @param GravMediaObjectInterface|null $media * @param FlexObjectInterface $object */ - public function __construct(?string $field, string $filename, ?GravMediaObjectInterface $media, FlexObjectInterface $object) + public function __construct(private readonly ?string $field, private readonly string $filename, ?GravMediaObjectInterface $media, FlexObjectInterface $object) { - $this->field = $field; - $this->filename = $filename; $this->media = $media; $this->object = $object; } @@ -157,15 +150,15 @@ class MediaObject implements MediaObjectInterface foreach ($actions as $method => $params) { $matches = []; - if (preg_match('/\[(.*)]/', $params, $matches)) { + if (preg_match('/\[(.*)]/', (string) $params, $matches)) { $args = [explode(',', $matches[1])]; } else { - $args = explode(',', $params); + $args = explode(',', (string) $params); } try { $medium->{$method}(...$args); - } catch (Throwable $e) { + } catch (Throwable) { // Ignore all errors for now and just skip the action. } } diff --git a/system/src/Grav/Framework/Media/UploadedMediaObject.php b/system/src/Grav/Framework/Media/UploadedMediaObject.php index 0fe12e1cc..5d5d366fc 100644 --- a/system/src/Grav/Framework/Media/UploadedMediaObject.php +++ b/system/src/Grav/Framework/Media/UploadedMediaObject.php @@ -19,17 +19,8 @@ class UploadedMediaObject implements MediaObjectInterface /** @var FormFlashInterface */ public $object; - - /** @var string */ - private $id; - /** @var string|null */ - private $field; - /** @var string */ - private $filename; /** @var array */ private $meta; - /** @var UploadedFileInterface|null */ - private $uploadedFile; /** * @param FlexFormFlash $flash @@ -51,17 +42,13 @@ class UploadedMediaObject implements MediaObjectInterface * @param string $filename * @param UploadedFileInterface|null $uploadedFile */ - public function __construct(string $id, ?string $field, string $filename, ?UploadedFileInterface $uploadedFile = null) + public function __construct(private readonly string $id, private readonly ?string $field, private readonly string $filename, private readonly ?UploadedFileInterface $uploadedFile = null) { - $this->id = $id; - $this->field = $field; - $this->filename = $filename; - $this->uploadedFile = $uploadedFile; - if ($uploadedFile) { + if ($this->uploadedFile) { $this->meta = [ - 'filename' => $uploadedFile->getClientFilename(), - 'mime' => $uploadedFile->getClientMediaType(), - 'size' => $uploadedFile->getSize() + 'filename' => $this->uploadedFile->getClientFilename(), + 'mime' => $this->uploadedFile->getClientMediaType(), + 'size' => $this->uploadedFile->getSize() ]; } else { $this->meta = []; diff --git a/system/src/Grav/Framework/Object/Access/ArrayAccessTrait.php b/system/src/Grav/Framework/Object/Access/ArrayAccessTrait.php index de6c6b9ed..95fca777a 100644 --- a/system/src/Grav/Framework/Object/Access/ArrayAccessTrait.php +++ b/system/src/Grav/Framework/Object/Access/ArrayAccessTrait.php @@ -22,7 +22,7 @@ trait ArrayAccessTrait * @return bool Returns TRUE on success or FALSE on failure. */ #[\ReturnTypeWillChange] - public function offsetExists($offset) + public function offsetExists(mixed $offset) { return $this->hasProperty($offset); } @@ -34,7 +34,7 @@ trait ArrayAccessTrait * @return mixed Can return all value types. */ #[\ReturnTypeWillChange] - public function offsetGet($offset) + public function offsetGet(mixed $offset) { return $this->getProperty($offset); } @@ -47,7 +47,7 @@ trait ArrayAccessTrait * @return void */ #[\ReturnTypeWillChange] - public function offsetSet($offset, $value) + public function offsetSet(mixed $offset, mixed $value) { $this->setProperty($offset, $value); } @@ -59,7 +59,7 @@ trait ArrayAccessTrait * @return void */ #[\ReturnTypeWillChange] - public function offsetUnset($offset) + public function offsetUnset(mixed $offset) { $this->unsetProperty($offset); } diff --git a/system/src/Grav/Framework/Object/Access/NestedArrayAccessTrait.php b/system/src/Grav/Framework/Object/Access/NestedArrayAccessTrait.php index 938ec26b4..f63e2a091 100644 --- a/system/src/Grav/Framework/Object/Access/NestedArrayAccessTrait.php +++ b/system/src/Grav/Framework/Object/Access/NestedArrayAccessTrait.php @@ -22,7 +22,7 @@ trait NestedArrayAccessTrait * @return bool Returns TRUE on success or FALSE on failure. */ #[\ReturnTypeWillChange] - public function offsetExists($offset) + public function offsetExists(mixed $offset) { return $this->hasNestedProperty($offset); } @@ -34,7 +34,7 @@ trait NestedArrayAccessTrait * @return mixed Can return all value types. */ #[\ReturnTypeWillChange] - public function offsetGet($offset) + public function offsetGet(mixed $offset) { return $this->getNestedProperty($offset); } @@ -47,7 +47,7 @@ trait NestedArrayAccessTrait * @return void */ #[\ReturnTypeWillChange] - public function offsetSet($offset, $value) + public function offsetSet(mixed $offset, mixed $value) { $this->setNestedProperty($offset, $value); } @@ -59,7 +59,7 @@ trait NestedArrayAccessTrait * @return void */ #[\ReturnTypeWillChange] - public function offsetUnset($offset) + public function offsetUnset(mixed $offset) { $this->unsetNestedProperty($offset); } diff --git a/system/src/Grav/Framework/Object/Access/NestedPropertyCollectionTrait.php b/system/src/Grav/Framework/Object/Access/NestedPropertyCollectionTrait.php index 1d749e3da..5fb9f993f 100644 --- a/system/src/Grav/Framework/Object/Access/NestedPropertyCollectionTrait.php +++ b/system/src/Grav/Framework/Object/Access/NestedPropertyCollectionTrait.php @@ -40,7 +40,7 @@ trait NestedPropertyCollectionTrait * @param string|null $separator Separator, defaults to '.' * @return array Key/Value pairs of the properties. */ - public function getNestedProperty($property, $default = null, $separator = null) + public function getNestedProperty($property, mixed $default = null, $separator = null) { $list = []; @@ -58,7 +58,7 @@ trait NestedPropertyCollectionTrait * @param string|null $separator Separator, defaults to '.' * @return $this */ - public function setNestedProperty($property, $value, $separator = null) + public function setNestedProperty($property, mixed $value, $separator = null) { /** @var NestedObjectInterface $element */ foreach ($this->getIterator() as $element) { diff --git a/system/src/Grav/Framework/Object/Access/NestedPropertyTrait.php b/system/src/Grav/Framework/Object/Access/NestedPropertyTrait.php index 3bfebe0bd..3feec5f87 100644 --- a/system/src/Grav/Framework/Object/Access/NestedPropertyTrait.php +++ b/system/src/Grav/Framework/Object/Access/NestedPropertyTrait.php @@ -82,7 +82,7 @@ trait NestedPropertyTrait * @return $this * @throws RuntimeException */ - public function setNestedProperty($property, $value, $separator = null) + public function setNestedProperty($property, mixed $value, $separator = null) { $separator = $separator ?: '.'; $path = explode($separator, $property); @@ -169,7 +169,7 @@ trait NestedPropertyTrait * @return $this * @throws RuntimeException */ - public function defNestedProperty($property, $default, $separator = null) + public function defNestedProperty($property, mixed $default, $separator = null) { if (!$this->hasNestedProperty($property, $separator)) { $this->setNestedProperty($property, $default, $separator); diff --git a/system/src/Grav/Framework/Object/Access/OverloadedPropertyTrait.php b/system/src/Grav/Framework/Object/Access/OverloadedPropertyTrait.php index 428473aff..e18bb1539 100644 --- a/system/src/Grav/Framework/Object/Access/OverloadedPropertyTrait.php +++ b/system/src/Grav/Framework/Object/Access/OverloadedPropertyTrait.php @@ -22,7 +22,7 @@ trait OverloadedPropertyTrait * @return bool Returns TRUE on success or FALSE on failure. */ #[\ReturnTypeWillChange] - public function __isset($offset) + public function __isset(mixed $offset) { return $this->hasProperty($offset); } @@ -34,7 +34,7 @@ trait OverloadedPropertyTrait * @return mixed Can return all value types. */ #[\ReturnTypeWillChange] - public function __get($offset) + public function __get(mixed $offset) { return $this->getProperty($offset); } @@ -47,7 +47,7 @@ trait OverloadedPropertyTrait * @return void */ #[\ReturnTypeWillChange] - public function __set($offset, $value) + public function __set(mixed $offset, mixed $value) { $this->setProperty($offset, $value); } @@ -59,7 +59,7 @@ trait OverloadedPropertyTrait * @return void */ #[\ReturnTypeWillChange] - public function __unset($offset) + public function __unset(mixed $offset) { $this->unsetProperty($offset); } diff --git a/system/src/Grav/Framework/Object/Base/ObjectCollectionTrait.php b/system/src/Grav/Framework/Object/Base/ObjectCollectionTrait.php index d9d8e41df..bc1e0391c 100644 --- a/system/src/Grav/Framework/Object/Base/ObjectCollectionTrait.php +++ b/system/src/Grav/Framework/Object/Base/ObjectCollectionTrait.php @@ -54,7 +54,7 @@ trait ObjectCollectionTrait return $type . static::$type; } - $class = get_class($this); + $class = $this::class; return $type . strtolower(substr($class, strrpos($class, '\\') + 1)); } @@ -89,7 +89,7 @@ trait ObjectCollectionTrait * @param mixed $default Default value if property has not been set. * @return mixed[] Property values. */ - public function getProperty($property, $default = null) + public function getProperty($property, mixed $default = null) { return $this->doGetProperty($property, $default); } @@ -99,7 +99,7 @@ trait ObjectCollectionTrait * @param mixed $value New value. * @return $this */ - public function setProperty($property, $value) + public function setProperty($property, mixed $value) { $this->doSetProperty($property, $value); @@ -122,7 +122,7 @@ trait ObjectCollectionTrait * @param mixed $default Default value. * @return $this */ - public function defProperty($property, $default) + public function defProperty($property, mixed $default) { if (!$this->hasProperty($property)) { $this->setProperty($property, $default); @@ -259,7 +259,7 @@ trait ObjectCollectionTrait * @param bool $doCreate Not being used. * @return mixed[] Key/Value pairs of the properties. */ - public function &doGetProperty($property, $default = null, $doCreate = false) + public function &doGetProperty($property, mixed $default = null, $doCreate = false) { $list = []; @@ -276,7 +276,7 @@ trait ObjectCollectionTrait * @param mixed $value New value. * @return $this */ - public function doSetProperty($property, $value) + public function doSetProperty($property, mixed $value) { /** @var ObjectInterface $element */ foreach ($this->getIterator() as $element) { @@ -305,7 +305,7 @@ trait ObjectCollectionTrait * @param mixed $default Default value. * @return $this */ - public function doDefProperty($property, $default) + public function doDefProperty($property, mixed $default) { /** @var ObjectInterface $element */ foreach ($this->getIterator() as $element) { diff --git a/system/src/Grav/Framework/Object/Base/ObjectTrait.php b/system/src/Grav/Framework/Object/Base/ObjectTrait.php index 522e5142e..4bb2d0ba4 100644 --- a/system/src/Grav/Framework/Object/Base/ObjectTrait.php +++ b/system/src/Grav/Framework/Object/Base/ObjectTrait.php @@ -48,7 +48,7 @@ trait ObjectTrait return $type . static::$type; } - $class = get_class($this); + $class = $this::class; return $type . strtolower(substr($class, strrpos($class, '\\') + 1)); } @@ -82,7 +82,7 @@ trait ObjectTrait * @param mixed $default Default value if property has not been set. * @return mixed Property value. */ - public function getProperty($property, $default = null) + public function getProperty($property, mixed $default = null) { return $this->doGetProperty($property, $default); } @@ -92,7 +92,7 @@ trait ObjectTrait * @param mixed $value New value. * @return $this */ - public function setProperty($property, $value) + public function setProperty($property, mixed $value) { $this->doSetProperty($property, $value); @@ -115,7 +115,7 @@ trait ObjectTrait * @param mixed $default Default value. * @return $this */ - public function defProperty($property, $default) + public function defProperty($property, mixed $default) { if (!$this->hasProperty($property)) { $this->setProperty($property, $default); diff --git a/system/src/Grav/Framework/Object/Collection/ObjectExpressionVisitor.php b/system/src/Grav/Framework/Object/Collection/ObjectExpressionVisitor.php index d62253825..844f81140 100644 --- a/system/src/Grav/Framework/Object/Collection/ObjectExpressionVisitor.php +++ b/system/src/Grav/Framework/Object/Collection/ObjectExpressionVisitor.php @@ -46,7 +46,7 @@ class ObjectExpressionVisitor extends ClosureExpressionVisitor if ($object instanceof ArrayAccess && isset($object[$field])) { $value = $object[$field]; } else { - $accessors = array('', 'get', 'is'); + $accessors = ['', 'get', 'is']; foreach ($accessors as $accessor) { $accessor .= $field; @@ -138,9 +138,7 @@ class ObjectExpressionVisitor extends ClosureExpressionVisitor public static function sortByField($name, $orientation = 1, ?Closure $next = null) { if (!$next) { - $next = function ($a, $b) { - return 0; - }; + $next = fn($a, $b) => 0; } return function ($a, $b) use ($name, $next, $orientation) { @@ -168,73 +166,26 @@ class ObjectExpressionVisitor extends ClosureExpressionVisitor $field = $comparison->getField(); $value = $comparison->getValue()->getValue(); // shortcut for walkValue() - switch ($comparison->getOperator()) { - case Comparison::EQ: - return function ($object) use ($field, $value) { - return static::getObjectFieldValue($object, $field) === $value; - }; - - case Comparison::NEQ: - return function ($object) use ($field, $value) { - return static::getObjectFieldValue($object, $field) !== $value; - }; - - case Comparison::LT: - return function ($object) use ($field, $value) { - return static::getObjectFieldValue($object, $field) < $value; - }; - - case Comparison::LTE: - return function ($object) use ($field, $value) { - return static::getObjectFieldValue($object, $field) <= $value; - }; - - case Comparison::GT: - return function ($object) use ($field, $value) { - return static::getObjectFieldValue($object, $field) > $value; - }; - - case Comparison::GTE: - return function ($object) use ($field, $value) { - return static::getObjectFieldValue($object, $field) >= $value; - }; - - case Comparison::IN: - return function ($object) use ($field, $value) { - return in_array(static::getObjectFieldValue($object, $field), $value, true); - }; - - case Comparison::NIN: - return function ($object) use ($field, $value) { - return !in_array(static::getObjectFieldValue($object, $field), $value, true); - }; - - case Comparison::CONTAINS: - return function ($object) use ($field, $value) { - return false !== strpos(static::getObjectFieldValue($object, $field), $value); - }; - - case Comparison::MEMBER_OF: - return function ($object) use ($field, $value) { - $fieldValues = static::getObjectFieldValue($object, $field); - if (!is_array($fieldValues)) { - $fieldValues = iterator_to_array($fieldValues); - } - return in_array($value, $fieldValues, true); - }; - - case Comparison::STARTS_WITH: - return function ($object) use ($field, $value) { - return 0 === strpos(static::getObjectFieldValue($object, $field), $value); - }; - - case Comparison::ENDS_WITH: - return function ($object) use ($field, $value) { - return $value === substr(static::getObjectFieldValue($object, $field), -strlen($value)); - }; - - default: - throw new RuntimeException('Unknown comparison operator: ' . $comparison->getOperator()); - } + return match ($comparison->getOperator()) { + Comparison::EQ => fn($object) => static::getObjectFieldValue($object, $field) === $value, + Comparison::NEQ => fn($object) => static::getObjectFieldValue($object, $field) !== $value, + Comparison::LT => fn($object) => static::getObjectFieldValue($object, $field) < $value, + Comparison::LTE => fn($object) => static::getObjectFieldValue($object, $field) <= $value, + Comparison::GT => fn($object) => static::getObjectFieldValue($object, $field) > $value, + Comparison::GTE => fn($object) => static::getObjectFieldValue($object, $field) >= $value, + Comparison::IN => fn($object) => in_array(static::getObjectFieldValue($object, $field), $value, true), + Comparison::NIN => fn($object) => !in_array(static::getObjectFieldValue($object, $field), $value, true), + Comparison::CONTAINS => fn($object) => str_contains((string) static::getObjectFieldValue($object, $field), (string) $value), + Comparison::MEMBER_OF => function ($object) use ($field, $value) { + $fieldValues = static::getObjectFieldValue($object, $field); + if (!is_array($fieldValues)) { + $fieldValues = iterator_to_array($fieldValues); + } + return in_array($value, $fieldValues, true); + }, + Comparison::STARTS_WITH => fn($object) => str_starts_with((string) static::getObjectFieldValue($object, $field), (string) $value), + Comparison::ENDS_WITH => fn($object) => str_ends_with((string) static::getObjectFieldValue($object, $field), (string) $value), + default => throw new RuntimeException('Unknown comparison operator: ' . $comparison->getOperator()), + }; } } diff --git a/system/src/Grav/Framework/Object/Identifiers/Identifier.php b/system/src/Grav/Framework/Object/Identifiers/Identifier.php index 69f41d2b8..9c5e02908 100644 --- a/system/src/Grav/Framework/Object/Identifiers/Identifier.php +++ b/system/src/Grav/Framework/Object/Identifiers/Identifier.php @@ -11,20 +11,13 @@ use Grav\Framework\Contracts\Object\IdentifierInterface; */ class Identifier implements IdentifierInterface { - /** @var string */ - private $id; - /** @var string */ - private $type; - /** * IdentifierInterface constructor. * @param string $id * @param string $type */ - public function __construct(string $id, string $type) + public function __construct(private readonly string $id, private readonly string $type) { - $this->id = $id; - $this->type = $type; } /** diff --git a/system/src/Grav/Framework/Object/Interfaces/NestedObjectCollectionInterface.php b/system/src/Grav/Framework/Object/Interfaces/NestedObjectCollectionInterface.php index ed81bb2fe..e217e8383 100644 --- a/system/src/Grav/Framework/Object/Interfaces/NestedObjectCollectionInterface.php +++ b/system/src/Grav/Framework/Object/Interfaces/NestedObjectCollectionInterface.php @@ -43,7 +43,7 @@ interface NestedObjectCollectionInterface extends ObjectCollectionInterface * @return $this * @throws RuntimeException */ - public function setNestedProperty($property, $value, $separator = null); + public function setNestedProperty($property, mixed $value, $separator = null); /** * @param string $property Object property to be defined. @@ -52,7 +52,7 @@ interface NestedObjectCollectionInterface extends ObjectCollectionInterface * @return $this * @throws RuntimeException */ - public function defNestedProperty($property, $default, $separator = null); + public function defNestedProperty($property, mixed $default, $separator = null); /** * @param string $property Object property to be unset. diff --git a/system/src/Grav/Framework/Object/Interfaces/NestedObjectInterface.php b/system/src/Grav/Framework/Object/Interfaces/NestedObjectInterface.php index 647f6c780..22adbce5a 100644 --- a/system/src/Grav/Framework/Object/Interfaces/NestedObjectInterface.php +++ b/system/src/Grav/Framework/Object/Interfaces/NestedObjectInterface.php @@ -39,7 +39,7 @@ interface NestedObjectInterface extends ObjectInterface * @return $this * @throws RuntimeException */ - public function setNestedProperty($property, $value, $separator = null); + public function setNestedProperty($property, mixed $value, $separator = null); /** * @param string $property Object property to be defined. @@ -48,7 +48,7 @@ interface NestedObjectInterface extends ObjectInterface * @return $this * @throws RuntimeException */ - public function defNestedProperty($property, $default, $separator = null); + public function defNestedProperty($property, mixed $default, $separator = null); /** * @param string $property Object property to be unset. diff --git a/system/src/Grav/Framework/Object/Interfaces/ObjectCollectionInterface.php b/system/src/Grav/Framework/Object/Interfaces/ObjectCollectionInterface.php index 156856104..1f053836d 100644 --- a/system/src/Grav/Framework/Object/Interfaces/ObjectCollectionInterface.php +++ b/system/src/Grav/Framework/Object/Interfaces/ObjectCollectionInterface.php @@ -57,14 +57,14 @@ interface ObjectCollectionInterface extends CollectionInterface, Selectable, Ser * @param mixed $value New value. * @return $this */ - public function setProperty($property, $value); + public function setProperty($property, mixed $value); /** * @param string $property Object property to be defined. * @param mixed $default Default value. * @return $this */ - public function defProperty($property, $default); + public function defProperty($property, mixed $default); /** * @param string $property Object property to be unset. diff --git a/system/src/Grav/Framework/Object/Interfaces/ObjectInterface.php b/system/src/Grav/Framework/Object/Interfaces/ObjectInterface.php index f505f4711..1eb7b5e77 100644 --- a/system/src/Grav/Framework/Object/Interfaces/ObjectInterface.php +++ b/system/src/Grav/Framework/Object/Interfaces/ObjectInterface.php @@ -46,14 +46,14 @@ interface ObjectInterface extends Serializable, JsonSerializable * @param mixed $value New value. * @return $this */ - public function setProperty($property, $value); + public function setProperty($property, mixed $value); /** * @param string $property Object property to be defined. * @param mixed $default Default value. * @return $this */ - public function defProperty($property, $default); + public function defProperty($property, mixed $default); /** * @param string $property Object property to be unset. diff --git a/system/src/Grav/Framework/Object/ObjectIndex.php b/system/src/Grav/Framework/Object/ObjectIndex.php index a241eda5d..52f164851 100644 --- a/system/src/Grav/Framework/Object/ObjectIndex.php +++ b/system/src/Grav/Framework/Object/ObjectIndex.php @@ -49,7 +49,7 @@ abstract class ObjectIndex extends AbstractIndexCollection implements NestedObje return $type . static::$type; } - $class = get_class($this); + $class = static::class; return $type . strtolower(substr($class, strrpos($class, '\\') + 1)); } diff --git a/system/src/Grav/Framework/Object/Property/ArrayPropertyTrait.php b/system/src/Grav/Framework/Object/Property/ArrayPropertyTrait.php index 0c0a549b9..85dc1489b 100644 --- a/system/src/Grav/Framework/Object/Property/ArrayPropertyTrait.php +++ b/system/src/Grav/Framework/Object/Property/ArrayPropertyTrait.php @@ -50,7 +50,7 @@ trait ArrayPropertyTrait * @param bool $doCreate Set true to create variable. * @return mixed Property value. */ - protected function &doGetProperty($property, $default = null, $doCreate = false) + protected function &doGetProperty($property, mixed $default = null, $doCreate = false) { if (!array_key_exists($property, $this->_elements)) { if ($doCreate) { @@ -68,7 +68,7 @@ trait ArrayPropertyTrait * @param mixed $value New value. * @return void */ - protected function doSetProperty($property, $value) + protected function doSetProperty($property, mixed $value) { $this->_elements[$property] = $value; } @@ -97,9 +97,7 @@ trait ArrayPropertyTrait */ protected function getElements() { - return array_filter($this->_elements, static function ($val) { - return $val !== null; - }); + return array_filter($this->_elements, static fn($val) => $val !== null); } /** diff --git a/system/src/Grav/Framework/Object/Property/LazyPropertyTrait.php b/system/src/Grav/Framework/Object/Property/LazyPropertyTrait.php index fe00d502f..03a97323f 100644 --- a/system/src/Grav/Framework/Object/Property/LazyPropertyTrait.php +++ b/system/src/Grav/Framework/Object/Property/LazyPropertyTrait.php @@ -56,12 +56,10 @@ trait LazyPropertyTrait * @param bool $doCreate * @return mixed Property value. */ - protected function &doGetProperty($property, $default = null, $doCreate = false) + protected function &doGetProperty($property, mixed $default = null, $doCreate = false) { if ($this->hasObjectProperty($property)) { - return $this->getObjectProperty($property, $default, function ($default = null) use ($property) { - return $this->getArrayProperty($property, $default); - }); + return $this->getObjectProperty($property, $default, fn($default = null) => $this->getArrayProperty($property, $default)); } return $this->getArrayProperty($property, $default, $doCreate); @@ -72,7 +70,7 @@ trait LazyPropertyTrait * @param mixed $value New value. * @return void */ - protected function doSetProperty($property, $value) + protected function doSetProperty($property, mixed $value) { if ($this->hasObjectProperty($property)) { $this->setObjectProperty($property, $value); diff --git a/system/src/Grav/Framework/Object/Property/MixedPropertyTrait.php b/system/src/Grav/Framework/Object/Property/MixedPropertyTrait.php index 3734760c1..436cfec31 100644 --- a/system/src/Grav/Framework/Object/Property/MixedPropertyTrait.php +++ b/system/src/Grav/Framework/Object/Property/MixedPropertyTrait.php @@ -57,7 +57,7 @@ trait MixedPropertyTrait * @param bool $doCreate * @return mixed Property value. */ - protected function &doGetProperty($property, $default = null, $doCreate = false) + protected function &doGetProperty($property, mixed $default = null, $doCreate = false) { if ($this->hasObjectProperty($property)) { return $this->getObjectProperty($property); @@ -71,7 +71,7 @@ trait MixedPropertyTrait * @param mixed $value New value. * @return void */ - protected function doSetProperty($property, $value) + protected function doSetProperty($property, mixed $value) { $this->hasObjectProperty($property) ? $this->setObjectProperty($property, $value) : $this->setArrayProperty($property, $value); diff --git a/system/src/Grav/Framework/Object/Property/ObjectPropertyTrait.php b/system/src/Grav/Framework/Object/Property/ObjectPropertyTrait.php index 618dbbd95..56413cfae 100644 --- a/system/src/Grav/Framework/Object/Property/ObjectPropertyTrait.php +++ b/system/src/Grav/Framework/Object/Property/ObjectPropertyTrait.php @@ -55,10 +55,9 @@ trait ObjectPropertyTrait /** * @param string $offset - * @param mixed $value * @return mixed */ - protected function offsetLoad($offset, $value) + protected function offsetLoad($offset, mixed $value) { $methodName = "offsetLoad_{$offset}"; @@ -67,10 +66,9 @@ trait ObjectPropertyTrait /** * @param string $offset - * @param mixed $value * @return mixed */ - protected function offsetPrepare($offset, $value) + protected function offsetPrepare($offset, mixed $value) { $methodName = "offsetPrepare_{$offset}"; @@ -79,10 +77,9 @@ trait ObjectPropertyTrait /** * @param string $offset - * @param mixed $value * @return mixed */ - protected function offsetSerialize($offset, $value) + protected function offsetSerialize($offset, mixed $value) { $methodName = "offsetSerialize_{$offset}"; @@ -104,7 +101,7 @@ trait ObjectPropertyTrait * @param callable|bool $doCreate Set true to create variable. * @return mixed Property value. */ - protected function &doGetProperty($property, $default = null, $doCreate = false) + protected function &doGetProperty($property, mixed $default = null, $doCreate = false) { if (!array_key_exists($property, $this->_definedProperties)) { throw new InvalidArgumentException("Property '{$property}' does not exist in the object!"); @@ -131,7 +128,7 @@ trait ObjectPropertyTrait * @return void * @throws InvalidArgumentException */ - protected function doSetProperty($property, $value) + protected function doSetProperty($property, mixed $value) { if (!array_key_exists($property, $this->_definedProperties)) { throw new InvalidArgumentException("Property '{$property}' does not exist in the object!"); diff --git a/system/src/Grav/Framework/Pagination/AbstractPagination.php b/system/src/Grav/Framework/Pagination/AbstractPagination.php index 401b1662b..f928fa461 100644 --- a/system/src/Grav/Framework/Pagination/AbstractPagination.php +++ b/system/src/Grav/Framework/Pagination/AbstractPagination.php @@ -132,10 +132,10 @@ class AbstractPagination implements PaginationInterface $param = $this->getOptions()['param']; $useQuery = $this->getOptions()['use_query_param']; if ($type === 'page') { - $param = $param ?? 'page'; + $param ??= 'page'; $offset = $page; } else { - $param = $param ?? 'start'; + $param ??= 'start'; $offset = $start; } diff --git a/system/src/Grav/Framework/Psr7/AbstractUri.php b/system/src/Grav/Framework/Psr7/AbstractUri.php index f00913513..b2269a934 100644 --- a/system/src/Grav/Framework/Psr7/AbstractUri.php +++ b/system/src/Grav/Framework/Psr7/AbstractUri.php @@ -264,7 +264,7 @@ abstract class AbstractUri implements UriInterface * @return string */ #[\ReturnTypeWillChange] - public function __toString() + public function __toString(): string { return $this->getUrl(); } @@ -377,10 +377,10 @@ abstract class AbstractUri implements UriInterface } if ($this->getAuthority() === '') { - if (0 === strpos($this->path, '//')) { + if (str_starts_with($this->path, '//')) { throw new InvalidArgumentException('The path of a URI without an authority must not start with two slashes \'//\''); } - if ($this->scheme === '' && false !== strpos(explode('/', $this->path, 2)[0], ':')) { + if ($this->scheme === '' && str_contains(explode('/', $this->path, 2)[0], ':')) { throw new InvalidArgumentException('A relative URI must not have a path beginning with a segment containing a colon'); } } elseif (isset($this->path[0]) && $this->path[0] !== '/') { diff --git a/system/src/Grav/Framework/Psr7/Response.php b/system/src/Grav/Framework/Psr7/Response.php index b7ed93e38..57d41ed12 100644 --- a/system/src/Grav/Framework/Psr7/Response.php +++ b/system/src/Grav/Framework/Psr7/Response.php @@ -21,7 +21,7 @@ use function in_array; * Class Response * @package Slim\Http */ -class Response implements ResponseInterface +class Response implements ResponseInterface, \Stringable { use ResponseDecoratorTrait; @@ -55,7 +55,7 @@ class Response implements ResponseInterface * @return static * @phpstan-param positive-int $depth */ - public function withJson($data, ?int $status = null, int $options = 0, int $depth = 512): ResponseInterface + public function withJson(mixed $data, ?int $status = null, int $options = 0, int $depth = 512): ResponseInterface { $json = (string) json_encode($data, $options, $depth); diff --git a/system/src/Grav/Framework/Psr7/ServerRequest.php b/system/src/Grav/Framework/Psr7/ServerRequest.php index 79f273b20..0bb8c3e59 100644 --- a/system/src/Grav/Framework/Psr7/ServerRequest.php +++ b/system/src/Grav/Framework/Psr7/ServerRequest.php @@ -50,11 +50,7 @@ class ServerRequest implements ServerRequestInterface { $mediaTypeParams = $this->getMediaTypeParams(); - if (isset($mediaTypeParams['charset'])) { - return $mediaTypeParams['charset']; - } - - return null; + return $mediaTypeParams['charset'] ?? null; } /** @@ -95,7 +91,7 @@ class ServerRequest implements ServerRequestInterface * * @return mixed */ - public function getCookieParam($key, $default = null) + public function getCookieParam($key, mixed $default = null) { $cookies = $this->getRequest()->getCookieParams(); @@ -202,11 +198,10 @@ class ServerRequest implements ServerRequestInterface * Note: This method is not part of the PSR-7 standard. * * @param string $key - * @param mixed $default * * @return mixed */ - public function getParsedBodyParam($key, $default = null) + public function getParsedBodyParam($key, mixed $default = null) { $postParams = $this->getParsedBody(); $result = $default; @@ -226,11 +221,10 @@ class ServerRequest implements ServerRequestInterface * Note: This method is not part of the PSR-7 standard. * * @param string $key - * @param mixed $default * * @return mixed */ - public function getQueryParam($key, $default = null) + public function getQueryParam($key, mixed $default = null) { $getParams = $this->getQueryParams(); @@ -243,10 +237,9 @@ class ServerRequest implements ServerRequestInterface * Note: This method is not part of the PSR-7 standard. * * @param string $key - * @param mixed $default * @return mixed */ - public function getServerParam($key, $default = null) + public function getServerParam($key, mixed $default = null) { $serverParams = $this->getRequest()->getServerParams(); diff --git a/system/src/Grav/Framework/Relationships/Relationships.php b/system/src/Grav/Framework/Relationships/Relationships.php index 55c004d47..be089f515 100644 --- a/system/src/Grav/Framework/Relationships/Relationships.php +++ b/system/src/Grav/Framework/Relationships/Relationships.php @@ -102,10 +102,9 @@ class Relationships implements RelationshipsInterface /** * @param string $offset - * @param mixed $value * @return never-return */ - public function offsetSet($offset, $value) + public function offsetSet($offset, mixed $value) { throw new RuntimeException('Setting relationship is not supported', 500); } @@ -201,18 +200,11 @@ class Relationships implements RelationshipsInterface } $cardinality = $options['cardinality'] ?? ''; - switch ($cardinality) { - case 'to-one': - /** @var ToOneRelationship $relationship */ - $relationship = new ToOneRelationship($parent, $name, $options, $data); - break; - case 'to-many': - /** @var ToManyRelationship $relationship */ - $relationship = new ToManyRelationship($parent, $name, $options, $data ?? []); - break; - default: - throw new RuntimeException(sprintf('Bad relationship cardinality %s', $cardinality), 500); - } + $relationship = match ($cardinality) { + 'to-one' => new ToOneRelationship($parent, $name, $options, $data), + 'to-many' => new ToManyRelationship($parent, $name, $options, $data ?? []), + default => throw new RuntimeException(sprintf('Bad relationship cardinality %s', $cardinality), 500), + }; return $relationship; } diff --git a/system/src/Grav/Framework/Relationships/Traits/RelationshipTrait.php b/system/src/Grav/Framework/Relationships/Traits/RelationshipTrait.php index dbe146fcc..1d7d82e88 100644 --- a/system/src/Grav/Framework/Relationships/Traits/RelationshipTrait.php +++ b/system/src/Grav/Framework/Relationships/Traits/RelationshipTrait.php @@ -109,7 +109,7 @@ trait RelationshipTrait throw new RuntimeException(sprintf('Bad identifier type %s', $identifier->getType())); } - if (get_class($identifier) !== Identifier::class) { + if ($identifier::class !== Identifier::class) { return $identifier; } diff --git a/system/src/Grav/Framework/RequestHandler/Exception/InvalidArgumentException.php b/system/src/Grav/Framework/RequestHandler/Exception/InvalidArgumentException.php index 4ca59541a..52092541f 100644 --- a/system/src/Grav/Framework/RequestHandler/Exception/InvalidArgumentException.php +++ b/system/src/Grav/Framework/RequestHandler/Exception/InvalidArgumentException.php @@ -19,9 +19,6 @@ use Throwable; */ class InvalidArgumentException extends \InvalidArgumentException { - /** @var mixed|null */ - private $invalidMiddleware; - /** * InvalidArgumentException constructor. * @@ -30,11 +27,9 @@ class InvalidArgumentException extends \InvalidArgumentException * @param int $code * @param Throwable|null $previous */ - public function __construct($message = '', $invalidMiddleware = null, $code = 0, ?Throwable $previous = null) + public function __construct($message = '', private $invalidMiddleware = null, $code = 0, ?Throwable $previous = null) { parent::__construct($message, $code, $previous); - - $this->invalidMiddleware = $invalidMiddleware; } /** diff --git a/system/src/Grav/Framework/RequestHandler/Exception/RequestException.php b/system/src/Grav/Framework/RequestHandler/Exception/RequestException.php index bd894fe58..2544aae5f 100644 --- a/system/src/Grav/Framework/RequestHandler/Exception/RequestException.php +++ b/system/src/Grav/Framework/RequestHandler/Exception/RequestException.php @@ -64,19 +64,14 @@ class RequestException extends \RuntimeException 511 => 'Network Authentication Required', ]; - /** @var ServerRequestInterface */ - private $request; - /** * @param ServerRequestInterface $request * @param string $message * @param int $code * @param Throwable|null $previous */ - public function __construct(ServerRequestInterface $request, string $message, int $code = 500, ?Throwable $previous = null) + public function __construct(private readonly ServerRequestInterface $request, string $message, int $code = 500, ?Throwable $previous = null) { - $this->request = $request; - parent::__construct($message, $code, $previous); } diff --git a/system/src/Grav/Framework/RequestHandler/Middlewares/Exceptions.php b/system/src/Grav/Framework/RequestHandler/Middlewares/Exceptions.php index 80deef06f..b6e5293e4 100644 --- a/system/src/Grav/Framework/RequestHandler/Middlewares/Exceptions.php +++ b/system/src/Grav/Framework/RequestHandler/Middlewares/Exceptions.php @@ -62,7 +62,7 @@ class Exceptions implements MiddlewareInterface $debugger = Grav::instance()['debugger']; if ($debugger->enabled()) { $response['error'] += [ - 'type' => get_class($exception), + 'type' => $exception::class, 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'trace' => explode("\n", $exception->getTraceAsString()), diff --git a/system/src/Grav/Framework/RequestHandler/Middlewares/MultipartRequestSupport.php b/system/src/Grav/Framework/RequestHandler/Middlewares/MultipartRequestSupport.php index 6e36e8f15..eaa8826c2 100644 --- a/system/src/Grav/Framework/RequestHandler/Middlewares/MultipartRequestSupport.php +++ b/system/src/Grav/Framework/RequestHandler/Middlewares/MultipartRequestSupport.php @@ -83,14 +83,14 @@ class MultipartRequestSupport implements MiddlewareInterface // Parse content disposition header. $contentDisposition = $headers['content-disposition']; - preg_match('/^(.+); *name="([^"]+)"(; *filename="([^"]+)")?/', $contentDisposition, $matches); + preg_match('/^(.+); *name="([^"]+)"(; *filename="([^"]+)")?/', (string) $contentDisposition, $matches); $name = $matches[2]; $filename = $matches[4] ?? null; if ($filename !== null) { $stream = Stream::create($body); $this->addFile($files, $name, new UploadedFile($stream, strlen($body), UPLOAD_ERR_OK, $filename, $headers['content-type'] ?? null)); - } elseif (strpos($contentDisposition, 'filename') !== false) { + } elseif (str_contains((string) $contentDisposition, 'filename')) { // Not uploaded file. $stream = Stream::create(''); $this->addFile($files, $name, new UploadedFile($stream, 0, UPLOAD_ERR_NO_FILE)); diff --git a/system/src/Grav/Framework/Route/Route.php b/system/src/Grav/Framework/Route/Route.php index 8d009890f..927eb21f0 100644 --- a/system/src/Grav/Framework/Route/Route.php +++ b/system/src/Grav/Framework/Route/Route.php @@ -19,7 +19,7 @@ use function array_slice; * * @package Grav\Framework\Route */ -class Route +class Route implements \Stringable { /** @var string */ private $root = ''; @@ -270,20 +270,18 @@ class Route /** * @param string $param - * @param mixed $value * @return Route */ - public function withGravParam($param, $value) + public function withGravParam($param, mixed $value) { return $this->withParam('gravParams', $param, null !== $value ? (string)$value : null); } /** * @param string $param - * @param mixed $value * @return Route */ - public function withQueryParam($param, $value) + public function withQueryParam($param, mixed $value) { return $this->withParam('queryParams', $param, $value); } @@ -346,9 +344,9 @@ class Route * @deprecated 1.6 Use ->toString(true) or ->getUri() instead. */ #[\ReturnTypeWillChange] - public function __toString() + public function __toString(): string { - user_error(__CLASS__ . '::' . __FUNCTION__ . '() will change in the future to return route, not relative url: use ->toString(true) or ->getUri() instead.', E_USER_DEPRECATED); + user_error(self::class . '::' . __FUNCTION__ . '() will change in the future to return route, not relative url: use ->toString(true) or ->getUri() instead.', E_USER_DEPRECATED); return $this->toString(true); } @@ -356,10 +354,9 @@ class Route /** * @param string $type * @param string $param - * @param mixed $value * @return Route */ - protected function withParam($type, $param, $value) + protected function withParam($type, $param, mixed $value) { $values = $this->{$type} ?? []; $oldValue = $values[$param] ?? null; @@ -438,7 +435,7 @@ class Route $path = $parts['path'] ?? '/'; if (isset($parts['params'])) { - $this->route = trim(rawurldecode($path), '/'); + $this->route = trim(rawurldecode((string) $path), '/'); $this->gravParams = $parts['params']; } else { $this->route = trim(RouteFactory::stripParams($path, true), '/'); diff --git a/system/src/Grav/Framework/Route/RouteFactory.php b/system/src/Grav/Framework/Route/RouteFactory.php index 6844e4897..44b91d315 100644 --- a/system/src/Grav/Framework/Route/RouteFactory.php +++ b/system/src/Grav/Framework/Route/RouteFactory.php @@ -49,7 +49,7 @@ class RouteFactory $parts['grav'] += [ 'root' => self::$root, 'language' => self::$language, - 'route' => trim($path, '/'), + 'route' => trim((string) $path, '/'), 'params' => $parts['params'] ?? [], ]; @@ -198,7 +198,7 @@ class RouteFactory $params = explode('/', $str); $list = []; foreach ($params as $param) { - if (mb_strpos($param, $delimiter) === false) { + if (mb_strpos((string) $param, $delimiter) === false) { $list[] = $param; } } @@ -223,10 +223,10 @@ class RouteFactory $list = []; foreach ($params as &$param) { /** @var array $parts */ - $parts = explode($delimiter, $param, 2); + $parts = explode($delimiter, (string) $param, 2); if (isset($parts[1])) { - $var = rawurldecode($parts[0]); - $val = rawurldecode($parts[1]); + $var = rawurldecode((string) $parts[0]); + $val = rawurldecode((string) $parts[1]); $list[$var] = $val; } } diff --git a/system/src/Grav/Framework/Session/Session.php b/system/src/Grav/Framework/Session/Session.php index 5867c1513..b4ac68d5e 100644 --- a/system/src/Grav/Framework/Session/Session.php +++ b/system/src/Grav/Framework/Session/Session.php @@ -198,7 +198,7 @@ class Session implements SessionInterface $sessionExists = isset($_COOKIE[$sessionName]); // Protection against invalid session cookie names throwing exception: http://php.net/manual/en/function.session-id.php#116836 - if ($sessionExists && !preg_match('/^[-,a-zA-Z0-9]{1,128}$/', $_COOKIE[$sessionName])) { + if ($sessionExists && !preg_match('/^[-,a-zA-Z0-9]{1,128}$/', (string) $_COOKIE[$sessionName])) { unset($_COOKIE[$sessionName]); $sessionExists = false; } @@ -260,7 +260,7 @@ class Session implements SessionInterface if ($user && (!$user instanceof UserInterface || (method_exists($user, 'isValid') && !$user->isValid()))) { throw new RuntimeException('Bad user'); } - } catch (Throwable $e) { + } catch (Throwable) { $this->invalidate(); throw new SessionException('Invalid User object, session destroyed.', 500); } @@ -354,7 +354,7 @@ class Session implements SessionInterface setcookie( $name, '', - $this->getCookieOptions(-42000) + ['expires' => $this->getCookieOptions(-42000)] ); } @@ -507,7 +507,7 @@ class Session implements SessionInterface setcookie( $sessionName, $sessionId, - $this->getCookieOptions() + ['expires' => $this->getCookieOptions()] ); } @@ -519,7 +519,7 @@ class Session implements SessionInterface foreach (headers_list() as $header) { // Identify cookie headers - if (strpos($header, 'Set-Cookie:') === 0) { + if (str_starts_with($header, 'Set-Cookie:')) { // Add all but session cookie(s). if (!str_contains($header, $search)) { $cookies[] = $header; @@ -543,10 +543,9 @@ class Session implements SessionInterface /** * @param string $key - * @param mixed $value * @return void */ - protected function setOption($key, $value) + protected function setOption($key, mixed $value) { if (!is_string($value)) { if (is_bool($value)) { diff --git a/system/src/Grav/Framework/Session/SessionInterface.php b/system/src/Grav/Framework/Session/SessionInterface.php index f160b1088..efebc4f46 100644 --- a/system/src/Grav/Framework/Session/SessionInterface.php +++ b/system/src/Grav/Framework/Session/SessionInterface.php @@ -142,11 +142,10 @@ interface SessionInterface extends IteratorAggregate * Sets session variable. * * @param string $name - * @param mixed $value * @return void */ #[\ReturnTypeWillChange] - public function __set($name, $value); + public function __set($name, mixed $value); /** * Removes session variable. diff --git a/system/src/Grav/Framework/Uri/UriFactory.php b/system/src/Grav/Framework/Uri/UriFactory.php index cb917ed6b..6bf6f9eff 100644 --- a/system/src/Grav/Framework/Uri/UriFactory.php +++ b/system/src/Grav/Framework/Uri/UriFactory.php @@ -59,10 +59,10 @@ class UriFactory { // Build scheme. if (isset($env['REQUEST_SCHEME'])) { - $scheme = strtolower($env['REQUEST_SCHEME']); + $scheme = strtolower((string) $env['REQUEST_SCHEME']); } else { $https = $env['HTTPS'] ?? ''; - $scheme = (empty($https) || strtolower($https) === 'off') ? 'http' : 'https'; + $scheme = (empty($https) || strtolower((string) $https) === 'off') ? 'http' : 'https'; } // Build user and password. @@ -77,7 +77,7 @@ class UriFactory $host = $env['SERVER_NAME']; } // Remove port from HTTP_HOST generated $hostname - $host = explode(':', $host)[0]; + $host = explode(':', (string) $host)[0]; // Build port. $port = isset($env['SERVER_PORT']) ? (int)$env['SERVER_PORT'] : null; @@ -93,8 +93,8 @@ class UriFactory } // Support ngnix routes. - if (strpos((string) $query, '_url=') === 0) { - parse_str($query, $q); + if (str_starts_with((string) $query, '_url=')) { + parse_str((string) $query, $q); unset($q['_url']); $query = http_build_query($q); } @@ -125,9 +125,7 @@ class UriFactory $encodedUrl = preg_replace_callback( '%[^:/@?&=#]+%u', - static function ($matches) { - return rawurlencode($matches[0]); - }, + static fn($matches) => rawurlencode((string) $matches[0]), $url ); diff --git a/system/src/Grav/Framework/Uri/UriPartsFilter.php b/system/src/Grav/Framework/Uri/UriPartsFilter.php index 27b72acc9..badf93549 100644 --- a/system/src/Grav/Framework/Uri/UriPartsFilter.php +++ b/system/src/Grav/Framework/Uri/UriPartsFilter.php @@ -50,9 +50,7 @@ class UriPartsFilter return preg_replace_callback( '/(?:[^a-zA-Z0-9_\-\.~!\$&\'\(\)\*\+,;=]+|%(?![A-Fa-f0-9]{2}))/u', - function ($match) { - return rawurlencode($match[0]); - }, + fn($match) => rawurlencode((string) $match[0]), $info ) ?? ''; } @@ -114,9 +112,7 @@ class UriPartsFilter return preg_replace_callback( '/(?:[^a-zA-Z0-9_\-\.~:@&=\+\$,\/;%]+|%(?![A-Fa-f0-9]{2}))/u', - function ($match) { - return rawurlencode($match[0]); - }, + fn($match) => rawurlencode((string) $match[0]), $path ) ?? ''; } @@ -136,9 +132,7 @@ class UriPartsFilter return preg_replace_callback( '/(?:[^a-zA-Z0-9_\-\.~!\$&\'\(\)\*\+,;=%:@\/\?]+|%(?![A-Fa-f0-9]{2}))/u', - function ($match) { - return rawurlencode($match[0]); - }, + fn($match) => rawurlencode((string) $match[0]), $query ) ?? ''; } diff --git a/system/src/Grav/Installer/VersionUpdate.php b/system/src/Grav/Installer/VersionUpdate.php index 1fde78307..2c650c86a 100644 --- a/system/src/Grav/Installer/VersionUpdate.php +++ b/system/src/Grav/Installer/VersionUpdate.php @@ -19,18 +19,15 @@ final class VersionUpdate private $date; /** @var string */ private $patch; - /** @var VersionUpdater */ - private $updater; /** @var callable[] */ private $methods; - public function __construct(string $file, VersionUpdater $updater) + public function __construct(string $file, private readonly VersionUpdater $updater) { $name = basename($file, '.php'); $this->revision = $name; [$this->version, $this->date, $this->patch] = explode('_', $name); - $this->updater = $updater; $this->methods = require $file; } diff --git a/system/src/Grav/Installer/VersionUpdater.php b/system/src/Grav/Installer/VersionUpdater.php index be28ebf4a..b4986dd88 100644 --- a/system/src/Grav/Installer/VersionUpdater.php +++ b/system/src/Grav/Installer/VersionUpdater.php @@ -10,14 +10,6 @@ use DirectoryIterator; */ final class VersionUpdater { - /** @var string */ - private $name; - /** @var string */ - private $path; - /** @var string */ - private $version; - /** @var Versions */ - private $versions; /** @var VersionUpdate[] */ private $updates; @@ -28,13 +20,8 @@ final class VersionUpdater * @param string $version * @param Versions $versions */ - public function __construct(string $name, string $path, string $version, Versions $versions) + public function __construct(private readonly string $name, private readonly string $path, private readonly string $version, private readonly Versions $versions) { - $this->name = $name; - $this->path = $path; - $this->version = $version; - $this->versions = $versions; - $this->loadUpdates(); } diff --git a/system/src/Grav/Installer/Versions.php b/system/src/Grav/Installer/Versions.php index f3f4ef987..9f9342bff 100644 --- a/system/src/Grav/Installer/Versions.php +++ b/system/src/Grav/Installer/Versions.php @@ -20,8 +20,6 @@ use function is_string; */ final class Versions { - /** @var string */ - protected $filename; /** @var array */ protected $items; /** @var bool */ @@ -36,7 +34,7 @@ final class Versions */ public static function instance(?string $filename = null): self { - $filename = $filename ?? USER_DIR . 'config/versions.yaml'; + $filename ??= USER_DIR . 'config/versions.yaml'; if (!isset(self::$instance[$filename])) { self::$instance[$filename] = new self($filename); @@ -250,7 +248,7 @@ final class Versions * @param mixed $default Default value (or null). * @return mixed Value. */ - private function get(string $name, $default = null) + private function get(string $name, mixed $default = null) { $path = explode('/', $name); $current = $this->items; @@ -272,7 +270,7 @@ final class Versions * @param string $name Slash separated path to the requested value. * @param mixed $value New value. */ - private function set(string $name, $value): void + private function set(string $name, mixed $value): void { $path = explode('/', $name); $current = &$this->items; @@ -317,10 +315,9 @@ final class Versions $this->updated = true; } - private function __construct(string $filename) + private function __construct(protected string $filename) { - $this->filename = $filename; - $content = is_file($filename) ? file_get_contents($filename) : null; + $content = is_file($this->filename) ? file_get_contents($this->filename) : null; if (false === $content) { throw new \RuntimeException('Versions file cannot be read'); } diff --git a/system/src/Grav/Installer/YamlUpdater.php b/system/src/Grav/Installer/YamlUpdater.php index b8aa07874..9a6dd2b35 100644 --- a/system/src/Grav/Installer/YamlUpdater.php +++ b/system/src/Grav/Installer/YamlUpdater.php @@ -103,9 +103,8 @@ final class YamlUpdater /** * @param string $variable - * @param mixed $value */ - public function define(string $variable, $value): void + public function define(string $variable, mixed $value): void { // If variable has already value, we're good. if ($this->get($variable) !== null) { @@ -206,7 +205,7 @@ final class YamlUpdater if ($test === true) { $test = false; - $spaces = strlen($line) - strlen(ltrim($line, ' ')); + $spaces = strlen((string) $line) - strlen(ltrim((string) $line, ' ')); if ($spaces <= $indent) { $found[$current] = -$j; @@ -218,10 +217,10 @@ final class YamlUpdater } - if (0 === \strncmp($line, $space, strlen($space))) { + if (str_starts_with((string) $line, $space)) { $pattern = "/^{$space}(['\"]?){$current}\\1\:/"; - if (preg_match($pattern, $line)) { + if (preg_match($pattern, (string) $line)) { $found[$current] = $i; $current = array_shift($parts); if ($current === null) { @@ -337,7 +336,7 @@ final class YamlUpdater * @param mixed $default Default value (or null). * @return mixed Value. */ - private function get(string $name, $default = null) + private function get(string $name, mixed $default = null) { $path = explode('.', $name); $current = $this->items; @@ -359,7 +358,7 @@ final class YamlUpdater * @param string $name Dot separated path to the requested value. * @param mixed $value New value. */ - private function set(string $name, $value): void + private function set(string $name, mixed $value): void { $path = explode('.', $name); $current = &$this->items;