diff --git a/system/src/Doctrine/Common/Cache/FilesystemCache.php b/system/src/Doctrine/Common/Cache/FilesystemCache.php index 5c6845fb09..e8c4c83a49 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 f62f45b563..f8279c0deb 100644 --- a/system/src/Grav/Common/Assets.php +++ b/system/src/Grav/Common/Assets.php @@ -194,12 +194,12 @@ public function add($asset) } $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 @@ public function add($asset) 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 @@ protected function addType($collection, $type, $asset, $options) $default = 'before'; } - $options['position'] = $options['position'] ?? $default; + $options['position'] ??= $default; } unset($options['pipeline']); @@ -432,9 +432,7 @@ protected function filterAssets($assets, $key, $value, $sort = false) */ 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 @@ protected function isValidType($type) */ 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 0659ff85c6..92d5cb82aa 100644 --- a/system/src/Grav/Common/Assets/BaseAsset.php +++ b/system/src/Grav/Common/Assets/BaseAsset.php @@ -114,7 +114,7 @@ public function init($asset, $options) // 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 7c33f7d050..a24b8c56e3 100644 --- a/system/src/Grav/Common/Assets/BlockAssets.php +++ b/system/src/Grav/Common/Assets/BlockAssets.php @@ -192,15 +192,15 @@ protected static function getRelativeUrl($url, $pipeline) { $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 3fd542e3e4..f48e9f1c4b 100644 --- a/system/src/Grav/Common/Assets/Pipeline.php +++ b/system/src/Grav/Common/Assets/Pipeline.php @@ -283,7 +283,7 @@ protected function cssRewrite($file, $dir, $local) } 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 874633f84a..cc7afc671f 100644 --- a/system/src/Grav/Common/Assets/Traits/AssetUtilsTrait.php +++ b/system/src/Grav/Common/Assets/Traits/AssetUtilsTrait.php @@ -55,7 +55,7 @@ public static function isRemoteLink($link) 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 @@ protected function gatherLinks(array $assets, int $type = self::CSS_ASSET): stri 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 @@ protected function gatherLinks(array $assets, int $type = self::CSS_ASSET): stri // 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 @@ protected function gatherLinks(array $assets, int $type = self::CSS_ASSET): stri $file = $this->jsRewrite($file, $relative_dir, $local); } - $file = rtrim($file) . PHP_EOL; + $file = rtrim((string) $file) . PHP_EOL; $buffer .= $file; } @@ -191,7 +191,7 @@ protected function renderQueryString($asset = null) { $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 08a59e2b88..d8ae7454fc 100644 --- a/system/src/Grav/Common/Assets/Traits/LegacyAssetsTrait.php +++ b/system/src/Grav/Common/Assets/Traits/LegacyAssetsTrait.php @@ -113,7 +113,7 @@ protected function createArgumentsFromLegacy(array $args, array $defaults) */ 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 @@ public function addAsyncJs($asset, $priority = 10, $pipeline = true, $group = 'h */ 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 c2648686f8..b69e7acb26 100644 --- a/system/src/Grav/Common/Assets/Traits/TestingAssetsTrait.php +++ b/system/src/Grav/Common/Assets/Traits/TestingAssetsTrait.php @@ -338,7 +338,7 @@ protected function rglob($directory, $pattern, $ltrim = null) $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 d9a1531a6a..be1329db40 100644 --- a/system/src/Grav/Common/Backup/Backups.php +++ b/system/src/Grav/Common/Backup/Backups.php @@ -54,7 +54,7 @@ public function init() /** @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 @@ public function getBackupDownloadUrl($backup, $base_url) { $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 @@ public static function getAvailableBackups($force = false) 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 @@ public static function backup($id = 0, ?callable $status = null) $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 6a92eeea22..24517b75ea 100644 --- a/system/src/Grav/Common/Browser.php +++ b/system/src/Grav/Common/Browser.php @@ -27,7 +27,7 @@ public function __construct() { 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 4d70089ca7..7bd90c6c95 100644 --- a/system/src/Grav/Common/Cache.php +++ b/system/src/Grav/Common/Cache.php @@ -160,7 +160,7 @@ public function init(Grav $grav) /** @var EventDispatcher $dispatcher */ $dispatcher = Grav::instance()['events']; - $dispatcher->addListener('onSchedulerInitialized', [$this, 'onSchedulerInitialized']); + $dispatcher->addListener('onSchedulerInitialized', $this->onSchedulerInitialized(...)); } /** @@ -264,8 +264,8 @@ public function getCacheAdapter(?string $namespace = null, ?int $defaultLifetime } $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 1e29ab5b31..b60f050984 100644 --- a/system/src/Grav/Common/Config/CompiledBase.php +++ b/system/src/Grav/Common/Config/CompiledBase.php @@ -202,7 +202,7 @@ protected function loadCompiledFile($filename) $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 @@ protected function saveCompiledFile($filename) // 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 @@ protected function saveCompiledFile($filename) } $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 17eb117848..eb9ef736dd 100644 --- a/system/src/Grav/Common/Config/Config.php +++ b/system/src/Grav/Common/Config/Config.php @@ -149,7 +149,7 @@ public function init() */ 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 6381e48cc0..1887e7e82d 100644 --- a/system/src/Grav/Common/Config/ConfigFileFinder.php +++ b/system/src/Grav/Common/Config/ConfigFileFinder.php @@ -178,9 +178,7 @@ protected function detectRecursive($folder, $pattern, $levels) '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 @@ protected function detectAll($folder, $pattern, $levels) '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 ba9b52fd4f..c7ce0a3b41 100644 --- a/system/src/Grav/Common/Config/Setup.php +++ b/system/src/Grav/Common/Config/Setup.php @@ -202,7 +202,7 @@ public function __construct($container) $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 3e84dce102..ef31f4aa43 100644 --- a/system/src/Grav/Common/Data/Blueprint.php +++ b/system/src/Grav/Common/Data/Blueprint.php @@ -168,7 +168,7 @@ public function init() // 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 @@ protected function dynamicData(array &$field, $property, array &$call) $params = []; } - [$o, $f] = explode('::', $function, 2); + [$o, $f] = explode('::', (string) $function, 2); $data = null; if (!$f) { @@ -574,10 +574,9 @@ protected function dynamicScope(array &$field, $property, array &$call) /** * @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 1408cb640b..5e13dcae4f 100644 --- a/system/src/Grav/Common/Data/BlueprintSchema.php +++ b/system/src/Grav/Common/Data/BlueprintSchema.php @@ -130,7 +130,7 @@ public function flattenData(array $data, bool $includeAll = false, string $name 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 5534a19991..f6ad6f0948 100644 --- a/system/src/Grav/Common/Data/Blueprints.php +++ b/system/src/Grav/Common/Data/Blueprints.php @@ -22,8 +22,6 @@ */ 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 0900a74306..f60b588cac 100644 --- a/system/src/Grav/Common/Data/Data.php +++ b/system/src/Grav/Common/Data/Data.php @@ -103,7 +103,7 @@ public function value($name, $default = null, $separator = '.') * @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 @@ public function getDefaults() * @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 a34fe69ad8..9cbed83020 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 1b799ad877..a9945f9ecf 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 @@ public static function validate($value, array $field) $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 @@ public static function validate($value, array $field) 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 @@ public static function validate($value, array $field) } /** - * @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 @@ public static function checkSafety($value, array $field) $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 @@ public static function authorize($action, ?UserInterface $user = null) /** * 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 @@ public static function filter($value, array $field) $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 @@ public static function filter($value, array $field) * @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 @@ public static function typeText($value, array $params, array $field) } $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 @@ public static function typeText($value, array $params, array $field) return false; } - if (!$multiline && preg_match('/\R/um', $value)) { + if (!$multiline && preg_match('/\R/um', (string) $value)) { return false; } @@ -266,12 +263,11 @@ public static function typeText($value, array $params, array $field) } /** - * @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 @@ protected static function filterText($value, array $params, array $field) } /** - * @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 @@ protected static function filterCheckbox($value, array $params, array $field) } /** - * @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 @@ public static function typeCommaList($value, array $params, array $field) } /** - * @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 @@ protected static function filterUpper($value, array $params) * @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 @@ public static function typeTextarea($value, array $params, array $field) * @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 @@ public static function typePassword($value, array $params, array $field) * @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 @@ public static function typeHidden($value, array $params, array $field) * @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 @@ public static function typeCheckboxes($value, array $params, array $field) } /** - * @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 @@ protected static function filterCheckboxes($value, array $params, array $field) * @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 @@ public static function typeCheckbox($value, array $params, array $field) * @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 @@ public static function typeRadio($value, array $params, array $field) * @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 @@ public static function typeToggle($value, array $params, array $field) * @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 @@ protected static function filterFile($value, array $params, array $field) * @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 @@ public static function typeSelect($value, array $params, array $field) * @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 @@ public static function typeNumber($value, array $params, array $field) } /** - * @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 @@ protected static function filterDateTime($value, array $params, array $field) * @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 @@ protected static function filterRange($value, array $params, array $field) * @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 @@ public static function typeColor($value, array $params, array $field) * @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 @@ public static function typeEmail($value, array $params, array $field) $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 @@ public static function typeEmail($value, array $params, array $field) * @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 @@ public static function typeUrl($value, array $params, array $field) * @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 @@ public static function typeDatetime($value, array $params, array $field) * @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 @@ public static function typeDatetimeLocal($value, array $params, array $field) * @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 @@ public static function typeDate($value, array $params, array $field) * @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 @@ public static function typeTime($value, array $params, array $field) * @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 @@ public static function typeMonth($value, array $params, array $field) * @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 @@ public static function typeWeek($value, array $params, array $field) * @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 @@ public static function typeArray($value, array $params, array $field) } /** - * @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 @@ protected static function filterFlatten_array($value, $params, $field) } /** - * @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 @@ protected static function filterArray($value, $params, $field) $val = implode(',', $val); $values[$key] = array_map('trim', explode(',', $val)); } else { - $values[$key] = trim($val); + $values[$key] = trim((string) $val); } } } @@ -895,16 +878,11 @@ protected static function arrayFilterRecurse(array $values, array $params): arra { 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 @@ protected static function arrayFilterRecurse(array $values, array $params): arra $val = (string)$val; break; case 'trim': - $val = trim($val); + $val = trim((string) $val); break; } } @@ -952,12 +930,11 @@ protected static function arrayFilterRecurse(array $values, array $params): arra } /** - * @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 @@ public static function typeList($value, array $params, array $field) 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 @@ public static function typeList($value, array $params, array $field) } /** - * @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 @@ public static function filterYaml($value, $params) * @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 @@ public static function filterIgnore($value, array $params, array $field) * @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 @@ public static function validateRequired($value, $params) } /** - * @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 @@ public static function validateHex($value, $params) * @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 @@ public static function typeInt($value, array $params, array $field) } /** - * @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 72570a16fa..73a1955ed0 100644 --- a/system/src/Grav/Common/Data/ValidationException.php +++ b/system/src/Grav/Common/Data/ValidationException.php @@ -37,7 +37,7 @@ public function setMessages(array $messages = []) 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 @@ public function setSimpleMessage(bool $escape = true): void $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 c732cbeafc..0bac330bdc 100644 --- a/system/src/Grav/Common/Debugger.php +++ b/system/src/Grav/Common/Debugger.php @@ -328,9 +328,7 @@ public function debuggerRequest(RequestInterface $request): Response 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 @@ public function stopProfiling(?string $message = null): ?array 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 @@ protected function buildProfilerTimings(array $timings): array } // Do not profile library calls. - if (strpos($context, 'Grav\\') !== 0) { + if (!str_starts_with((string) $context, 'Grav\\')) { continue; } @@ -721,12 +715,11 @@ public function stopTimer($name) /** * 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 @@ public function addMessage($message, $label = 'info', $isString = true) 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 @@ public function addException(Throwable $e) public function setErrorHandler() { $this->errorHandler = set_error_handler( - [$this, 'deprecatedErrorHandler'] + $this->deprecatedErrorHandler(...) ); } @@ -858,7 +851,7 @@ public function deprecatedErrorHandler($errno, $errstr, $errfile, $errline) $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 @@ public function deprecatedErrorHandler($errno, $errstr, $errfile, $errline) } } elseif (stripos($errfile, '/yaml/') !== false) { $scope = 'yaml'; - } elseif (strpos($errfile, '/vendor/') !== false) { + } elseif (str_contains($errfile, '/vendor/')) { $scope = 'vendor'; } @@ -912,7 +905,7 @@ public function deprecatedErrorHandler($errno, $errstr, $errfile, $errline) } 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 @@ public function deprecatedErrorHandler($errno, $errstr, $errfile, $errline) 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 @@ public function deprecatedErrorHandler($errno, $errstr, $errfile, $errline) 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 @@ protected function addDeprecations() /** @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 @@ protected function getFunction($trace) 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 4f11fdd777..50143c3f2a 100644 --- a/system/src/Grav/Common/Errors/SimplePageHandler.php +++ b/system/src/Grav/Common/Errors/SimplePageHandler.php @@ -54,11 +54,7 @@ public function handle() $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 1266e9dc92..d7ea266e0d 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 @@ public function content($var = null) 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 @@ public function content($var = null) * @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 @@ public function save($data = null) 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 06f489de58..f6ce1b3af0 100644 --- a/system/src/Grav/Common/Filesystem/Folder.php +++ b/system/src/Grav/Common/Filesystem/Folder.php @@ -153,8 +153,8 @@ public static function getRelativePath($path, $base = GRAV_ROOT) 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 @@ public static function getRelativePathDotDot($path, $base) 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 @@ public static function getRelativePathDotDot($path, $base) $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 @@ public static function all($path, array $params = []) /** @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 @@ public static function all($path, array $params = []) 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 @@ public static function all($path, array $params = []) 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 @@ public static function copy($source, $target, $ignore = null) // 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 @@ public static function move($source, $target) 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 82b5a769c2..05d77ead76 100644 --- a/system/src/Grav/Common/Filesystem/ZipArchiver.php +++ b/system/src/Grav/Common/Filesystem/ZipArchiver.php @@ -77,7 +77,7 @@ public function compress($source, ?callable $status = null) 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 ba1b8a1334..3d9dcee2ba 100644 --- a/system/src/Grav/Common/Flex/Traits/FlexCollectionTrait.php +++ b/system/src/Grav/Common/Flex/Traits/FlexCollectionTrait.php @@ -35,7 +35,7 @@ public function triggerEvent(string $name, $event = null) '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 2a058062f1..26c4e035c5 100644 --- a/system/src/Grav/Common/Flex/Traits/FlexObjectTrait.php +++ b/system/src/Grav/Common/Flex/Traits/FlexObjectTrait.php @@ -46,7 +46,7 @@ public function triggerEvent(string $name, $event = null) 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 a061f86eff..679e7fbda2 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 @@ public function addPage(PageInterface $page) * @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 @@ public function merge(PageCollectionInterface $collection) * @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 @@ public function random($num = 1) * @return static * @phpstan-return static */ - public function append($items) + public function append($items): never { throw new RuntimeException(__METHOD__ . '(): Not Implemented'); } @@ -303,7 +303,7 @@ protected function buildSort($order_by = 'default', $order_dir = 'asc', $manual // 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 @@ protected function buildSort($order_by = 'default', $order_dir = 'asc', $manual 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 @@ public function dateRange($startDate = null, $endDate = null, $field = null) 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 82e8501ea6..c3b393752d 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 @@ public function setParams(array $params) * 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 @@ protected function getLanguageTemplates(string $key): array */ 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 @@ protected function getFallbackLanguages(?string $languageCode = null, ?bool $fal /** @var Language $language */ $language = $grav['language']; - $languageCode = $languageCode ?? ''; + $languageCode ??= ''; if ($languageCode === '' && $fallback) { return $language->getFallbackLanguages(null, true); } @@ -533,7 +532,7 @@ protected function getLevelListingRecurse(array $options): array // 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 @@ protected function getLevelListingRecurse(array $options): array 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 @@ protected function getLevelListingRecurse(array $options): array // 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 @@ protected function getLevelListingRecurse(array $options): array '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 @@ protected function getLevelListingRecurse(array $options): array '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 @@ protected function getLevelListingRecurse(array $options): array '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 2af4ee7c85..e41c35fc11 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 @@ protected function doGetBlueprint(string $name = ''): Blueprint $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 @@ public function getLevelListing(array $options): array $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 @@ public function filterBy(array $filters, bool $recursive = false): bool $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 @@ protected function filterElements(array &$elements, bool $extended = false): voi } 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 577a0d7aa8..a74d2f92f7 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 @@ protected function saveRow(string $key, array $row): array 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 @@ protected function getObjectMeta(string $key, bool $reload = false): array 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 d8d86b0b40..5e18cc4e06 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 @@ public function translatedLanguages($onlyPublished = false): array $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 9e753d21b8..bbffc8d01c 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 @@ protected function getAccess(): Access } /** - * @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 @@ protected function offsetLoad_access($value): array } /** - * @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 5ce9fe4e0b..2f634ab1d9 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 @@ public function merge(array $data) */ 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 @@ public function getAvatarMedia() */ 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 @@ public function avatarUrl() */ 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 @@ public function authorise($action) #[\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 74524106d2..d97b74a38b 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 @@ public static function updateObjectMeta(array &$meta, array $data, FlexStorageIn // 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 1a3eb3fa27..7f9759e70b 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 @@ public function authorize(string $action, ?string $scope = null): ?bool 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 @@ public function toJson() */ 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 @@ protected function getAccess(): Access } /** - * @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 @@ protected function offsetLoad_access($value): array } /** - * @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 2b359d166f..401b22ef94 100644 --- a/system/src/Grav/Common/GPM/Common/Package.php +++ b/system/src/Grav/Common/GPM/Common/Package.php @@ -14,7 +14,7 @@ /** * @property string $name */ -class Package +class Package implements \Stringable { /** @var Data */ protected $data; @@ -53,11 +53,10 @@ public function __get($key) /** * @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 @@ public function __isset($key) * @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 2f05a76e76..fd61ffe13f 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 @@ public function __construct($refresh = false, $callback = null) $this->cache = []; $this->installed = new Local\Packages(); - $this->refresh = $refresh; $this->callback = $callback; } @@ -78,12 +75,10 @@ public function __construct($refresh = false, $callback = null) #[\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 @@ public function __get($offset) #[\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 @@ public function getRepository() 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 @@ public function getGrav() 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 @@ public function calculateVersionNumberFromDependencyVersion($version) */ public function versionFormatIsNextSignificantRelease($version): bool { - return strpos($version, '~') === 0; + return str_starts_with($version, '~'); } /** @@ -1233,7 +1226,7 @@ public function versionFormatIsNextSignificantRelease($version): bool */ 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 2987e4a27b..de06978351 100644 --- a/system/src/Grav/Common/GPM/Installer.php +++ b/system/src/Grav/Common/GPM/Installer.php @@ -81,7 +81,7 @@ public static function install($zip, $destination, $options = [], $extracted = n { $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 53b249ae8b..72b07b332c 100644 --- a/system/src/Grav/Common/GPM/Local/Package.php +++ b/system/src/Grav/Common/GPM/Local/Package.php @@ -37,7 +37,7 @@ public function __construct(Data $package, $package_type = null) $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 c08108af9a..bcbafe4c62 100644 --- a/system/src/Grav/Common/GPM/Remote/AbstractPackageCollection.php +++ b/system/src/Grav/Common/GPM/Remote/AbstractPackageCollection.php @@ -53,10 +53,10 @@ public function __construct($repository = null, $refresh = false, $callback = nu $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 d97eb834f0..c3a3c9bdc3 100644 --- a/system/src/Grav/Common/GPM/Remote/GravCore.php +++ b/system/src/Grav/Common/GPM/Remote/GravCore.php @@ -46,7 +46,7 @@ public function __construct($refresh = false, $callback = null) $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 aca39bc07d..3ddb1020e2 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 @@ public function offsetGet($offset) /** * @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 f9c9b00fb4..e170c9362d 100644 --- a/system/src/Grav/Common/Grav.php +++ b/system/src/Grav/Common/Grav.php @@ -261,51 +261,23 @@ public function process(): void $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 @@ public function process(): void $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 @@ public function close(ResponseInterface $response): void $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 @@ public function getRedirectResponse($route, $code = null): ResponseInterface 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 @@ public function getRedirectResponse($route, $code = null): ResponseInterface $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 @@ public function header(?ResponseInterface $response = null): void 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 @@ public function setLocale(): void // 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 @@ public function dispatchEvent($event) { /** @var EventDispatcherInterface $events */ $events = $this['events']; - $eventName = get_class($event); + $eventName = $event::class; $timestamp = microtime(true); $event = $events->dispatch($event); @@ -734,9 +706,7 @@ protected function registerServices(): void 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 @@ public function fallbackUrl($path) $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 @@ public function fallbackUrl($path) 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 4c9a79616a..dce738e247 100644 --- a/system/src/Grav/Common/HTTP/Client.php +++ b/system/src/Grav/Common/HTTP/Client.php @@ -33,7 +33,7 @@ public static function getClient(array $overrides = [], int $connections = 6, ?c // 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 @@ public static function getClient(array $overrides = [], int $connections = 6, ?c $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 ca3a6efba6..2d42d7c181 100644 --- a/system/src/Grav/Common/HTTP/Response.php +++ b/system/src/Grav/Common/HTTP/Response.php @@ -73,7 +73,7 @@ public static function request(string $method, string $uri, array $overrides = [ 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 d09c52cbf6..c854a7edd0 100644 --- a/system/src/Grav/Common/Helpers/Truncator.php +++ b/system/src/Grav/Common/Helpers/Truncator.php @@ -62,7 +62,7 @@ public static function truncateWords($html, $limit = 0, $ellipsis = '') $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 @@ private static function getCleanedHTML(DOMDocument $doc, DOMNode $container) */ 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 @@ public function truncate( ) { 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 @@ public function truncate( $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 284b8dd468..cde645e3fa 100644 --- a/system/src/Grav/Common/Inflector.php +++ b/system/src/Grav/Common/Inflector.php @@ -72,7 +72,7 @@ public static function pluralize($word, $count = 2) 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 @@ public static function pluralize($word, $count = 2) 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 @@ public static function pluralize($word, $count = 2) 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 @@ public static function singularize($word, $count = 1) 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 @@ public static function singularize($word, $count = 1) 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 @@ public static function titleize($word, $uppercase = '') */ 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 @@ public static function camelize($word) 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 @@ public static function underscorize($word) 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 @@ public static function ordinalize($number) 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 51ed5d1856..5c18fc2532 100644 --- a/system/src/Grav/Common/Iterator.php +++ b/system/src/Grav/Common/Iterator.php @@ -24,7 +24,7 @@ * 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 @@ public function __clone() * @return string */ #[\ReturnTypeWillChange] - public function __toString() + public function __toString(): string { return implode(',', $this->items); } @@ -143,7 +142,7 @@ public function reverse() * * @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 0e6096c690..baf0b8a77e 100644 --- a/system/src/Grav/Common/Language/Language.php +++ b/system/src/Grav/Common/Language/Language.php @@ -149,9 +149,7 @@ public function getAvailable($delimiter = null) { $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 @@ public function getTranslation($lang, $key, $array_support = false) */ 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 @@ public function getBrowserLanguages($accept_langs = []) $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 bd2ab90394..85db416669 100644 --- a/system/src/Grav/Common/Markdown/Parsedown.php +++ b/system/src/Grav/Common/Markdown/Parsedown.php @@ -35,7 +35,7 @@ public function __construct($excerpts = null, $defaults = null) $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 3ec8080017..616b84bd6b 100644 --- a/system/src/Grav/Common/Markdown/ParsedownExtra.php +++ b/system/src/Grav/Common/Markdown/ParsedownExtra.php @@ -36,7 +36,7 @@ public function __construct($excerpts = null, $defaults = null) $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 3a6ceb498e..adb0a0fdca 100644 --- a/system/src/Grav/Common/Markdown/ParsedownGravTrait.php +++ b/system/src/Grav/Common/Markdown/ParsedownGravTrait.php @@ -49,7 +49,7 @@ protected function init($excerpts = null, $defaults = null) $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 @@ public function addInlineType($type, $tag, $index = null) 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 @@ public function setSpecialChars($special_chars) */ 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 @@ protected function blockTwigTag($line) */ 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 @@ protected function inlineSpecialCharacter($excerpt) */ 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 @@ protected function inlineLink($excerpt) $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 e967702a5e..613be5bc18 100644 --- a/system/src/Grav/Common/Media/Interfaces/MediaObjectInterface.php +++ b/system/src/Grav/Common/Media/Interfaces/MediaObjectInterface.php @@ -207,11 +207,10 @@ public function style($style); * 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 @@ public function __call($method, $args); * @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 83b2d268a3..fb7bff76b6 100644 --- a/system/src/Grav/Common/Media/Traits/ImageMediaTrait.php +++ b/system/src/Grav/Common/Media/Traits/ImageMediaTrait.php @@ -97,7 +97,7 @@ public function getImagePrettyName() } $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 9e3f8704b5..04ed9f7948 100644 --- a/system/src/Grav/Common/Media/Traits/MediaFileTrait.php +++ b/system/src/Grav/Common/Media/Traits/MediaFileTrait.php @@ -88,7 +88,7 @@ public function relativePath($reset = true) } $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 f872dd1aab..7fda705cf9 100644 --- a/system/src/Grav/Common/Media/Traits/MediaObjectTrait.php +++ b/system/src/Grav/Common/Media/Traits/MediaObjectTrait.php @@ -182,7 +182,7 @@ public function querystring($querystring = null, $withQuestionmark = true) // 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 @@ protected function getThumbnail() * @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 @@ abstract public function get($name, $default = null, $separator = null); * @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 93c4fdbcb4..61f6f53b55 100644 --- a/system/src/Grav/Common/Media/Traits/MediaTrait.php +++ b/system/src/Grav/Common/Media/Traits/MediaTrait.php @@ -57,15 +57,15 @@ public function getMediaUri() 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 45d5208af0..281bc373fd 100644 --- a/system/src/Grav/Common/Media/Traits/MediaUploadTrait.php +++ b/system/src/Grav/Common/Media/Traits/MediaUploadTrait.php @@ -206,11 +206,11 @@ public function checkFileMetadata(array $metadata, ?string $filename = null, ?ar 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 @@ public function checkFileMetadata(array $metadata, ?string $filename = null, ?ar 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 @@ public function copyUploadedFile(UploadedFileInterface $uploadedFile, string $fi 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 @@ protected function doRemove(string $filename, string $path): void $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 e0c5d813d8..59b4b51dc2 100644 --- a/system/src/Grav/Common/Media/Traits/ThumbnailMediaTrait.php +++ b/system/src/Grav/Common/Media/Traits/ThumbnailMediaTrait.php @@ -138,7 +138,7 @@ protected function bubble($method, array $arguments = [], $testLinked = true) $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 90d3346fd9..041fb60553 100644 --- a/system/src/Grav/Common/Page/Collection.php +++ b/system/src/Grav/Common/Page/Collection.php @@ -139,9 +139,7 @@ public function intersect(PageCollectionInterface $collection) $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 @@ public function dateRange($startDate = null, $endDate = null, $field = null) 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 0d38c7d3ae..c58fb6c265 100644 --- a/system/src/Grav/Common/Page/Interfaces/PageLegacyInterface.php +++ b/system/src/Grav/Common/Page/Interfaces/PageLegacyInterface.php @@ -43,9 +43,8 @@ public function frontmatter($var = null); * 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 @@ public function contentMeta(); * 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 406b4a4796..3675615055 100644 --- a/system/src/Grav/Common/Page/Markdown/Excerpts.php +++ b/system/src/Grav/Common/Page/Markdown/Excerpts.php @@ -49,7 +49,7 @@ public function __construct(?PageInterface $page = null, ?array $config = null) // 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 @@ public function fireInitializedEvent($markdown): void 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 @@ static function ($carry, $item) { $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 @@ static function ($carry, $item) { */ 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 @@ public function processImageExcerpt(array $excerpt): array 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 @@ public function processMediaActions($medium, $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 = $parts[1] ?? null; @@ -296,10 +296,10 @@ static function ($carry, $item) { 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 6478528e5d..2a27cb6245 100644 --- a/system/src/Grav/Common/Page/Media.php +++ b/system/src/Grav/Common/Page/Media.php @@ -152,14 +152,14 @@ protected function init() 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 554382a8a9..636b00b5b3 100644 --- a/system/src/Grav/Common/Page/Medium/ImageFile.php +++ b/system/src/Grav/Common/Page/Medium/ImageFile.php @@ -95,9 +95,7 @@ public function cacheFile($type = 'jpg', $quality = 80, $actual = false, $extras // 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 @@ public function cacheFile($type = 'jpg', $quality = 80, $actual = false, $extras // 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 5539d9fb0d..6db4a783e6 100644 --- a/system/src/Grav/Common/Page/Medium/ImageMedium.php +++ b/system/src/Grav/Common/Page/Medium/ImageMedium.php @@ -370,7 +370,7 @@ public function watermark($image = null, $position = null, $scale = null) $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 @@ public function __call($method, $args) // 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 1abc7efd7a..2dd158e5d2 100644 --- a/system/src/Grav/Common/Page/Medium/Link.php +++ b/system/src/Grav/Common/Page/Medium/Link.php @@ -76,16 +76,15 @@ public function parsedownElement($title = null, $alt = null, $class = null, $id * 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 ede2a74415..5143deb3ec 100644 --- a/system/src/Grav/Common/Page/Medium/Medium.php +++ b/system/src/Grav/Common/Page/Medium/Medium.php @@ -99,7 +99,7 @@ public function getMeta(): array * @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 3f555969cb..3aa80e77d6 100644 --- a/system/src/Grav/Common/Page/Medium/MediumFactory.php +++ b/system/src/Grav/Common/Page/Medium/MediumFactory.php @@ -46,7 +46,7 @@ public static function fromFile($file, array $params = []) $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 @@ public static function fromUploadedFile(UploadedFileInterface $uploadedFile, arr $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 @@ public static function fromArray(array $items = [], ?Blueprint $blueprint = null { $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 2883b6ff8b..17cc39c377 100644 --- a/system/src/Grav/Common/Page/Page.php +++ b/system/src/Grav/Common/Page/Page.php @@ -203,14 +203,14 @@ public function init(SplFileInfo $file, $extension = null) $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 @@ protected function processFrontmatter() } } $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 @@ public function translatedLanguages($onlyPublished = false) $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 @@ public function raw($var = null) // 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 @@ public function frontmatter($var = null) } // 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 @@ public function header($var = null) } // 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 @@ public function content($var = null) } // 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 @@ public function content($var = null) // 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 @@ protected function processMarkdown(bool $keepTwig = false) // 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 @@ static function ($matches) use ($token) { return $token[0] . base64_encode($matc // 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 @@ public function move(PageInterface $parent) } $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 @@ public function blueprintName() } $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 @@ public function metadata($var = null) $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 @@ public function metadata($var = null) 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 @@ public function url($include_host = false, $canonical = false, $include_base = t /** @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 @@ public function id($var = null) { 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 @@ public function currentPosition() */ 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 @@ public function folderExists() 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 @@ protected function doReorder($new_order) // 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 a0b0506dcc..1ecfff4fff 100644 --- a/system/src/Grav/Common/Page/Pages.php +++ b/system/src/Grav/Common/Page/Pages.php @@ -168,7 +168,7 @@ public function base($path = null) */ 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 @@ public function referrerRoute(?string &$langCode, string $route = '/'): ?string // 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 @@ public function getCollection(array $params = [], array $context = []) /** @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 @@ public function getCollection(array $params = [], array $context = []) } // 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 @@ public function getCollection(array $params = [], array $context = []) 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 @@ protected function findSiteBasedRoute($route) 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 @@ public function dispatch($route, $all = false, $redirect = true) $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 @@ public function blueprints($type) try { $blueprint = $this->blueprints->get($type); - } catch (RuntimeException $e) { + } catch (RuntimeException) { $blueprint = $this->blueprints->get('default'); } @@ -1254,7 +1252,7 @@ public function getList(?PageInterface $current = null, $level = 0, $rawRoutes = } 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 @@ public static function getTypes() $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 @@ public static function pageTypes($type = null) $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 @@ public static function getHomeRoute() } 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 @@ protected function buildRegularPages(): void $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 @@ protected function recurse(string $directory, ?PageInterface $parent = null) // 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 @@ static function ($str) { $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 @@ protected function buildSort($path, array $pages, $order_by = 'default', $manual $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 @@ protected function buildSort($path, array $pages, $order_by = 'default', $manual 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 b99e7b75c4..eab786e10b 100644 --- a/system/src/Grav/Common/Page/Traits/PageFormTrait.php +++ b/system/src/Grav/Common/Page/Traits/PageFormTrait.php @@ -111,7 +111,7 @@ protected function normalizeForm($form, $name = null, array $rules = []): ?array $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 d9bdc331de..24c0677c2d 100644 --- a/system/src/Grav/Common/Page/Types.php +++ b/system/src/Grav/Common/Page/Types.php @@ -142,7 +142,7 @@ public function modularSelect() { $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 f6235141d3..1e1a8f4166 100644 --- a/system/src/Grav/Common/Plugin.php +++ b/system/src/Grav/Common/Plugin.php @@ -30,8 +30,6 @@ */ class Plugin implements EventSubscriberInterface, ArrayAccess { - /** @var string */ - public $name; /** @var array */ public $features = []; @@ -57,7 +55,7 @@ public static function getSubscribedEvents() $list = []; foreach ($methods as $method) { - if (strpos($method, 'on') === 0) { + if (str_starts_with($method, 'on')) { $list[$method] = [$method, 0]; } } @@ -72,9 +70,8 @@ public static function getSubscribedEvents() * @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 @@ protected function isPluginActiveAdmin($plugin_route) /** @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 @@ public function offsetGet($offset) * @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 @@ public function offsetSet($offset, $value) #[\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 @@ protected function parseLinks($content, $function, $internal_regex = '(.*)') * @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 @@ public static function inheritedConfigOption(string $plugin, string $var, ?PageI 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 af54ec8a16..47e8144820 100644 --- a/system/src/Grav/Common/Plugins.php +++ b/system/src/Grav/Common/Plugins.php @@ -86,7 +86,7 @@ public function setup() $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 @@ public function init() 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 417f6c5436..95bafb84c1 100644 --- a/system/src/Grav/Common/Processors/InitializeProcessor.php +++ b/system/src/Grav/Common/Processors/InitializeProcessor.php @@ -126,9 +126,7 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface // 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 @@ protected function initializeSession(Config $config): void 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 ab5caf9b17..544678e3eb 100644 --- a/system/src/Grav/Common/Processors/TasksProcessor.php +++ b/system/src/Grav/Common/Processors/TasksProcessor.php @@ -53,7 +53,7 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface $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 d50d1007a9..b7f12b65b1 100644 --- a/system/src/Grav/Common/Scheduler/Cron.php +++ b/system/src/Grav/Common/Scheduler/Cron.php @@ -224,8 +224,8 @@ public function getText($lang) 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 @@ public function getType() 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 @@ public function setCron($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 @@ public function setDaysOfMonth($dom) } /** - * @param mixed $date * @param int $min * @param int $hour * @param int $day @@ -423,7 +422,7 @@ public function setDaysOfMonth($dom) * @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 a5a5e6087d..a502e5a032 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 @@ public function __construct($command, $args = [], $id = null) // 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 @@ public function isDue(?DateTime $date = null) $this->at('* * * * *'); } - $date = $date ?? $this->creationTime; + $date ??= $this->creationTime; return $this->executionTime->isDue($date); } @@ -271,9 +268,7 @@ public function onlyOne($tempDir = null, ?callable $whenOverlapping = null) if ($whenOverlapping) { $this->whenOverlapping = $whenOverlapping; } else { - $this->whenOverlapping = static function () { - return false; - }; + $this->whenOverlapping = static fn() => false; } return $this; @@ -410,10 +405,9 @@ private function postRun() /** * 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 8e0f9e1d63..3bb71e5806 100644 --- a/system/src/Grav/Common/Scheduler/Scheduler.php +++ b/system/src/Grav/Common/Scheduler/Scheduler.php @@ -244,16 +244,12 @@ public function resetRun() */ 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 @@ public function getCronCommand() 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 @@ private function pushFailedJob(Job $job) 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 491a61c01b..bdff7eeca6 100644 --- a/system/src/Grav/Common/Security.php +++ b/system/src/Grav/Common/Security.php @@ -129,7 +129,7 @@ public static function detectXssFromPages(Pages $pages, $route = true, ?callable $list[$page->rawRoute()] = $results; } } - } catch (Exception $e) { + } catch (Exception) { continue; } } @@ -196,7 +196,7 @@ public static function detectXss($string, ?array $options = null): ?string 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 @@ public static function detectXss($string, ?array $options = null): ?string $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 @@ public static function detectXss($string, ?array $options = null): ?string // 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 54bb2f4691..192a8d303b 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 6f0ffae72d..1fe45a1a1c 100644 --- a/system/src/Grav/Common/Service/ConfigServiceProvider.php +++ b/system/src/Grav/Common/Service/ConfigServiceProvider.php @@ -42,9 +42,7 @@ public function register(Container $container) 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 @@ public function register(Container $container) 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 @@ public static function load(Container $container) $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 eadcb52ec6..0114eab600 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 fcb49aa568..131717bb38 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 dd1be13c09..5b5233d87e 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 ad9858f24e..071337ff95 100644 --- a/system/src/Grav/Common/Service/RequestServiceProvider.php +++ b/system/src/Grav/Common/Service/RequestServiceProvider.php @@ -73,7 +73,7 @@ public function register(Container $container) if (!is_array($post)) { $post = null; } - } catch (JsonException $e) { + } catch (JsonException) { $post = null; } break 2; @@ -86,7 +86,7 @@ public function register(Container $container) 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 @@ public function register(Container $container) 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 2fbe41797e..4ba32ea3e6 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 a2c35f7a88..8e5ea9bd16 100644 --- a/system/src/Grav/Common/Service/SessionServiceProvider.php +++ b/system/src/Grav/Common/Service/SessionServiceProvider.php @@ -64,7 +64,7 @@ public function register(Container $container) // 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 @@ public function register(Container $container) } $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 a75e08367a..fc519057cf 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 @@ public function setAutoStart($auto) */ 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 @@ public function all() */ 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 @@ public function started() * 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 @@ public function getFlashObject($name) * 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 @@ public function getFlashCookieObject($name) { 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 75bd8b15fe..5943d384cb 100644 --- a/system/src/Grav/Common/Themes.php +++ b/system/src/Grav/Common/Themes.php @@ -77,7 +77,7 @@ public function initTheme() try { $instance = $themes->load(); - } catch (InvalidArgumentException $e) { + } catch (InvalidArgumentException) { throw new RuntimeException($this->current() . ' theme could not be found'); } @@ -377,7 +377,7 @@ protected function loadLanguages(Config $config) 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 cbafdb246a..23bea7543a 100644 --- a/system/src/Grav/Common/Twig/Extension/FilesystemExtension.php +++ b/system/src/Grav/Common/Twig/Extension/FilesystemExtension.php @@ -36,29 +36,29 @@ public function __construct() 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 @@ public function getFilters() 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 8e159ac865..4fb54a97a7 100644 --- a/system/src/Grav/Common/Twig/Extension/GravExtension.php +++ b/system/src/Grav/Common/Twig/Extension/GravExtension.php @@ -109,72 +109,72 @@ public function getGlobals(): array 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 @@ public function getFilters(): array 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 @@ public function getFunctions(): array 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 @@ public function getTokenParsers(): array } /** - * @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 @@ public function containsFilter($haystack, $needle) return $haystack; } - return (strpos($haystack, (string) $needle) !== false); + return (str_contains($haystack, (string) $needle)); } /** @@ -700,9 +699,7 @@ public function xssFunc($data) } $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 @@ public function endsWithFilter($haystack, $needle) } /** - * @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 @@ public function ltrimFilter($value, $chars = null) /** * 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 @@ public function stringFilter($value) /** * 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 @@ public function intFilter($input) /** * 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 @@ public function boolFilter($input) /** * 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 @@ public function floatFilter($input) /** * 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 @@ public function dump(Environment $env, $context) 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 @@ public static function padFilter($input, $pad_length, $pad_string = ' ', $pad_ty 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 @@ public function isAjaxFunc() { 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 @@ public function mediaDirFunc($media_dir) /** * 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 @@ public function niceNumberFunc($n) */ 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 @@ public static function svgImageFunction($path, $classes = null, $strip_style = f //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 @@ public static function svgImageFunction($path, $classes = null, $strip_style = f 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 @@ public static function svgImageFunction($path, $classes = null, $strip_style = f $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 831abf0895..d416a2ac79 100644 --- a/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserCache.php +++ b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserCache.php @@ -55,7 +55,7 @@ public function parse(Token $token) $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 581df504e0..420cf23b86 100644 --- a/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserMarkdown.php +++ b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserMarkdown.php @@ -35,7 +35,7 @@ public function parse(Token $token) { $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 073d93db57..e5dd8ae56c 100644 --- a/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserScript.php +++ b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserScript.php @@ -48,7 +48,7 @@ public function parse(Token $token) $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 590394d54b..7f0710cb1c 100644 --- a/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserStyle.php +++ b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserStyle.php @@ -41,7 +41,7 @@ public function parse(Token $token) $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 c2806f8f8f..6946d102ad 100644 --- a/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserSwitch.php +++ b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserSwitch.php @@ -74,7 +74,7 @@ public function parse(Token $token) } $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 @@ public function parse(Token $token) 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 dcb183bd04..410745399e 100644 --- a/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserTryCatch.php +++ b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserTryCatch.php @@ -41,10 +41,10 @@ public function parse(Token $token) $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 45f54b3a4b..1927477a8b 100644 --- a/system/src/Grav/Common/Twig/Twig.php +++ b/system/src/Grav/Common/Twig/Twig.php @@ -45,13 +45,13 @@ // 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 @@ public function setTemplate($name, $template) */ 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 @@ public function getPageTwigTemplate($page, &$format = null) 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 dcd9c27a82..3e8884da73 100644 --- a/system/src/Grav/Common/Uri.php +++ b/system/src/Grav/Common/Uri.php @@ -30,7 +30,7 @@ * 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 @@ public function init() } // 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 @@ public function init() // 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 @@ public function params($id = null, $array = false) 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 @@ public function extension($default = null) */ 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 @@ public function referrer($default = null, $attributes = null, bool $withoutBaseR * @return string */ #[\ReturnTypeWillChange] - public function __toString() + public function __toString(): string { return static::buildUrl($this->toArray()); } @@ -743,7 +743,7 @@ public static function getCurrentRoute() */ 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 @@ public static function buildUrl($parsed_url) $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 @@ public static function convertUrl(PageInterface $page, $url, $type = 'link', $ab $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 @@ public static function convertUrl(PageInterface $page, $url, $type = 'link', $ab } 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 @@ public static function convertUrl(PageInterface $page, $url, $type = 'link', $ab 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 @@ public static function parseUrl($url) $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 @@ public static function extractParams($uri, $delimiter) { $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 @@ public static function convertUrlOld(PageInterface $page, $markdown_url, $type = 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 @@ public static function convertUrlOld(PageInterface $page, $markdown_url, $type = */ 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 @@ protected function createFromEnvironment(array $env) $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 @@ protected function createFromEnvironment(array $env) } // 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 @@ public function post($element = null, $filter_type = null) $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 @@ public static function getAllHeaders() 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 @@ private function buildEnvironment() */ 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 8a4ac2ae4f..d4d1dd45f3 100644 --- a/system/src/Grav/Common/User/DataUser/User.php +++ b/system/src/Grav/Common/User/DataUser/User.php @@ -122,7 +122,7 @@ public function save() /** @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 @@ public function __wakeup() */ 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 @@ public function merge(array $data) */ 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 @@ public function getAvatarMedia() */ 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 @@ public function avatarUrl() */ 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 @@ public function authorise($action) #[\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 3db16d379c..b214adf69c 100644 --- a/system/src/Grav/Common/User/DataUser/UserCollection.php +++ b/system/src/Grav/Common/User/DataUser/UserCollection.php @@ -27,16 +27,12 @@ */ 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 @@ public function find($query, $fields = ['username', 'email']): UserInterface 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 6b657bf3fd..99844387f1 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 @@ public function get($name, $default = null, $separator = null); * @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 @@ public function undef($name, $separator = null); * @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 @@ public function def($name, $default = null, $separator = null); * @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 @@ public function getDefaults(); * @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 085de03eba..8b943d8802 100644 --- a/system/src/Grav/Common/User/Traits/UserTrait.php +++ b/system/src/Grav/Common/User/Traits/UserTrait.php @@ -89,7 +89,7 @@ public function authorize(string $action, ?string $scope = null): ?bool } // 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 @@ public function getAvatarUrl(): string 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 e87302edb7..156783cff9 100644 --- a/system/src/Grav/Common/User/User.php +++ b/system/src/Grav/Common/User/User.php @@ -36,7 +36,7 @@ class User extends Flex\Types\Users\UserObject */ 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 @@ public static function load($username) */ 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 @@ public static function find($query, $fields = ['username', 'email']) */ 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 @@ class User extends DataUser\User */ 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 @@ public static function load($username) */ 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 @@ public static function find($query, $fields = ['username', 'email']) */ 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 f106a64e7b..d5c9b1abba 100644 --- a/system/src/Grav/Common/Utils.php +++ b/system/src/Grav/Common/Utils.php @@ -276,8 +276,8 @@ public static function contains($haystack, $needle, $case_sensitive = true) 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 @@ public static function simpleTemplate(string $template, array $variables, array { $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 @@ public static function arrayMergeRecursiveUnique($array1, $array2) */ 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 @@ public static function download($file, $force_download = true, $sec = 0, $bytes // 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 @@ public static function download($file, $force_download = true, $sec = 0, $bytes // 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 @@ public static function arrayFlatten($array) */ 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 @@ public static function date2timestamp($date, $format = null) } else { try { $datetime = new DateTime($date); - } catch (Exception $e) { + } catch (Exception) { $datetime = false; } } @@ -1357,7 +1355,7 @@ public static function date2timestamp($date, $format = null) */ 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 @@ public static function getDotNotation($array, $key, $default = null) * * @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 @@ public static function setDotNotation(&$array, $key, $value, $merge = false) $key = array_shift($keys); if (!isset($array[$key]) || !is_array($array[$key])) { - $array[$key] = array(); + $array[$key] = []; } $array =& $array[$key]; @@ -1562,7 +1558,7 @@ public static function isWindows() */ 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 @@ public static function sortArrayByArray(array $array, array $orderArray) /** * 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 @@ public static function getPathFromToken($path, $object = null) */ 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 @@ public static function getUploadLimit() */ 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 @@ public static function convertSize($bytes, $to, $decimal_places = 1) */ 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 @@ public static function multibyteParseUrl($url) { $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 @@ static function ($matches) { 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 @@ public static function processMarkdown($string, $block = true, $page = null) 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 @@ public static function isDangerousFunction($name): bool 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 d2fa0cdc47..00185f1c6e 100644 --- a/system/src/Grav/Console/Application/Application.php +++ b/system/src/Grav/Console/Application/Application.php @@ -43,7 +43,7 @@ public function __construct(string $name = 'UNKNOWN', string $version = 'UNKNOWN // 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 210250c64f..ac60859443 100644 --- a/system/src/Grav/Console/Application/CommandLoader/PluginCommandLoader.php +++ b/system/src/Grav/Console/Application/CommandLoader/PluginCommandLoader.php @@ -52,7 +52,7 @@ public function __construct(string $name) $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 fce40a10ef..ea3168e13d 100644 --- a/system/src/Grav/Console/Cli/InstallCommand.php +++ b/system/src/Grav/Console/Cli/InstallCommand.php @@ -76,7 +76,7 @@ protected function serve(): int $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 @@ private function symlink(?string $name = null, ?string $type = null): int $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 @@ private function addSymlinks(string $from, string $to, array $options): int $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 1e8302d237..f682b6ca5c 100644 --- a/system/src/Grav/Console/Cli/PageSystemValidatorCommand.php +++ b/system/src/Grav/Console/Cli/PageSystemValidatorCommand.php @@ -240,7 +240,7 @@ private function recordRow(PageInterface $page): array $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 fb302440a4..bc7e4d3264 100644 --- a/system/src/Grav/Console/Cli/SchedulerCommand.php +++ b/system/src/Grav/Console/Cli/SchedulerCommand.php @@ -137,7 +137,7 @@ protected function serve(): int 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 d75a4a6cf6..ee8caa1b27 100644 --- a/system/src/Grav/Console/Cli/SecurityCommand.php +++ b/system/src/Grav/Console/Cli/SecurityCommand.php @@ -53,15 +53,13 @@ protected function serve(): int $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 a514e88a2a..1ab9d2ccf1 100644 --- a/system/src/Grav/Console/ConsoleTrait.php +++ b/system/src/Grav/Console/ConsoleTrait.php @@ -106,7 +106,7 @@ final protected function setupGrav(): void // 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 d9b544878e..512efcaa77 100644 --- a/system/src/Grav/Console/Gpm/IndexCommand.php +++ b/system/src/Grav/Console/Gpm/IndexCommand.php @@ -134,7 +134,7 @@ protected function serve(): int } 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 @@ public function sort(AbstractPackageCollection $packages): array // 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 d343cfd362..55582f839f 100644 --- a/system/src/Grav/Console/Gpm/InfoCommand.php +++ b/system/src/Grav/Console/Gpm/InfoCommand.php @@ -123,7 +123,7 @@ protected function serve(): int 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 @@ protected function serve(): int $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 adbfea9de9..2c9eaf1a70 100644 --- a/system/src/Grav/Console/Gpm/InstallCommand.php +++ b/system/src/Grav/Console/Gpm/InstallCommand.php @@ -179,7 +179,7 @@ protected function serve(): int $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 @@ public function askConfirmationIfMajorVersionUpdated(Package $package): void 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 @@ private function getSymlinkSource(Package $package) 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 @@ private function downloadPackage(Package $package, ?string $license = null) } 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 @@ public function progress(array $progress): void $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 2b164d029a..79dd440bd4 100644 --- a/system/src/Grav/Console/Gpm/SelfupgradeCommand.php +++ b/system/src/Grav/Console/Gpm/SelfupgradeCommand.php @@ -186,9 +186,7 @@ protected function serve(): int $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 @@ private function download(array $package): string '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 @@ public function progress(array $progress): void $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 @@ public function progress(array $progress): void 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 3e16adbfb1..74b8e51a87 100644 --- a/system/src/Grav/Console/Gpm/VersionCommand.php +++ b/system/src/Grav/Console/Gpm/VersionCommand.php @@ -67,7 +67,7 @@ protected function serve(): int } 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 f89d565e65..8be004a95c 100644 --- a/system/src/Grav/Console/GpmCommand.php +++ b/system/src/Grav/Console/GpmCommand.php @@ -62,7 +62,7 @@ protected function displayGPMRelease() $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 408fa046e3..6c34baf50f 100644 --- a/system/src/Grav/Framework/Acl/Access.php +++ b/system/src/Grav/Framework/Acl/Access.php @@ -28,8 +28,6 @@ */ 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 @@ public function toArray(): array */ 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 63c0141c79..778576aa52 100644 --- a/system/src/Grav/Framework/Acl/Permissions.php +++ b/system/src/Grav/Framework/Acl/Permissions.php @@ -181,10 +181,9 @@ public function offsetGet($offset): ?Action /** * @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 295784146f..6c3ca81211 100644 --- a/system/src/Grav/Framework/Cache/Adapter/ChainCache.php +++ b/system/src/Grav/Framework/Cache/Adapter/ChainCache.php @@ -52,7 +52,7 @@ public function __construct(array $caches, $defaultLifetime = null) 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 d2058d5f7e..6a049f114f 100644 --- a/system/src/Grav/Framework/Cache/Adapter/FileCache.php +++ b/system/src/Grav/Framework/Cache/Adapter/FileCache.php @@ -197,7 +197,7 @@ protected function initFileCache($namespace, $directory) */ 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 @@ private function mkdir($dir) * @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 c095f3d09c..73248b03f7 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 @@ public function doClear(); /** * @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 f7eeb04883..5c4f19cf4b 100644 --- a/system/src/Grav/Framework/Cache/CacheTrait.php +++ b/system/src/Grav/Framework/Cache/CacheTrait.php @@ -95,12 +95,11 @@ public function get($key, $default = null) /** * @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 @@ public function getMultiple($keys, $default = null) 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 @@ public function setMultiple($values, $ttl = null) 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 @@ public function deleteMultiple($keys) 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 @@ public function has($key) /** * @param array $keys - * @param mixed $miss * @return array */ - public function doGetMultiple($keys, $miss) + public function doGetMultiple($keys, mixed $miss) { $results = []; @@ -308,7 +306,7 @@ protected function validateKey($key) 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 @@ protected function convertTtl($ttl) 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 88682733fe..8a7647841a 100644 --- a/system/src/Grav/Framework/Collection/AbstractFileCollection.php +++ b/system/src/Grav/Framework/Collection/AbstractFileCollection.php @@ -31,8 +31,6 @@ */ 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 @@ protected function addFilter(callable $filterFunction) { 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 be5d5c5c62..c4f1d8c09e 100644 --- a/system/src/Grav/Framework/Collection/AbstractIndexCollection.php +++ b/system/src/Grav/Framework/Collection/AbstractIndexCollection.php @@ -26,25 +26,23 @@ * @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 @@ public function offsetGet($offset) * 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 @@ public function partition(Closure $p) * @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 @@ protected function getCurrentKey($element) /** * @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 protected function loadElements(?array $entries = null): array; 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 6d98bc8895..60807de180 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 3ba8abe2d9..fe78096ef8 100644 --- a/system/src/Grav/Framework/ContentBlock/ContentBlock.php +++ b/system/src/Grav/Framework/ContentBlock/ContentBlock.php @@ -118,7 +118,7 @@ public function toArray() } $array = [ - '_type' => get_class($this), + '_type' => static::class, '_version' => $this->version, 'id' => $this->id, 'cached' => $this->cached @@ -162,7 +162,7 @@ public function toString() * @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 5d6bf6235d..be8126b4eb 100644 --- a/system/src/Grav/Framework/ContentBlock/HtmlBlock.php +++ b/system/src/Grav/Framework/ContentBlock/HtmlBlock.php @@ -182,7 +182,7 @@ public function addStyle($element, $priority = 0, $location = 'head') $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 @@ public function addScript($element, $priority = 0, $location = 'head') 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 @@ protected function sortAssetsInLocation(array &$items) 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 a50c6d18bd..5b818bf35a 100644 --- a/system/src/Grav/Framework/Controller/Traits/ControllerResponseTrait.php +++ b/system/src/Grav/Framework/Controller/Traits/ControllerResponseTrait.php @@ -51,11 +51,11 @@ protected function createDisplayResponse(): ResponseInterface */ 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 @@ protected function createHtmlResponse(string $content, ?int $code = null, ?array */ 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 @@ protected function createDownloadResponse(string $filename, $resource, ?array $h @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 @@ protected function getErrorJson(Throwable $e): array $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 @@ protected function getAccept(array $compare) { $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 f49112b03f..2b704c977c 100644 --- a/system/src/Grav/Framework/File/AbstractFile.php +++ b/system/src/Grav/Framework/File/AbstractFile.php @@ -285,7 +285,7 @@ public function save($data): void 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 @@ public function save($data): void $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 83a444dce0..0789f763ae 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 9bdd6628d4..960b0aa946 100644 --- a/system/src/Grav/Framework/File/Formatter/CsvFormatter.php +++ b/system/src/Grav/Framework/File/Formatter/CsvFormatter.php @@ -64,7 +64,7 @@ public function encode($data, $delimiter = null): string 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 @@ public function encode($data, $delimiter = null): string */ 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 @@ public function decode($data, $delimiter = null): array $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 809de1cbe7..5bdfda3b36 100644 --- a/system/src/Grav/Framework/File/Formatter/IniFormatter.php +++ b/system/src/Grav/Framework/File/Formatter/IniFormatter.php @@ -44,7 +44,7 @@ public function encode($data): string $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 2ed8b93bf1..5c4bf695f8 100644 --- a/system/src/Grav/Framework/File/Formatter/SerializeFormatter.php +++ b/system/src/Grav/Framework/File/Formatter/SerializeFormatter.php @@ -77,12 +77,11 @@ public function decode($data) /** * 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 e76ba10b6b..97095cac68 100644 --- a/system/src/Grav/Framework/File/Interfaces/FileFormatterInterface.php +++ b/system/src/Grav/Framework/File/Interfaces/FileFormatterInterface.php @@ -59,7 +59,7 @@ public function getSupportedFileExtensions(): array; * @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 0abb46adcd..ec917490b8 100644 --- a/system/src/Grav/Framework/File/Interfaces/FileInterface.php +++ b/system/src/Grav/Framework/File/Interfaces/FileInterface.php @@ -156,7 +156,7 @@ public function load(); * @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 20b42c8d07..cc80df41c0 100644 --- a/system/src/Grav/Framework/Filesystem/Filesystem.php +++ b/system/src/Grav/Framework/Filesystem/Filesystem.php @@ -24,9 +24,6 @@ */ class Filesystem implements FilesystemInterface { - /** @var bool|null */ - private $normalize; - /** @var static|null */ protected static $default; @@ -63,9 +60,8 @@ public static function getInstance(?bool $normalize = null): Filesystem * @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 f51a4c84cd..c16d3ed69d 100644 --- a/system/src/Grav/Framework/Flex/Flex.php +++ b/system/src/Grav/Framework/Flex/Flex.php @@ -306,7 +306,7 @@ public function count(): int 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 @@ protected function resolveKeyAndType(string $flexKey, ?string $type = null): arr */ 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 7984719fc4..5e3d63d1bc 100644 --- a/system/src/Grav/Framework/Flex/FlexCollection.php +++ b/system/src/Grav/Framework/Flex/FlexCollection.php @@ -99,8 +99,8 @@ public static function createFromArray(array $entries, FlexDirectory $directory, 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 @@ public function getFlexFeatures(): array $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 @@ public function render(?string $layout = null, array $context = []) $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 @@ public function find($value, $field = 'id') { 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 @@ protected function setKeyField($keyField = null): void */ 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 @@ public function triggerEvent(string $name, $event = null) '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 3fb2f30bb5..8928f8cc58 100644 --- a/system/src/Grav/Framework/Flex/FlexDirectory.php +++ b/system/src/Grav/Framework/Flex/FlexDirectory.php @@ -402,7 +402,7 @@ public function getCollection(?array $keys = null, ?string $keyField = null): Fl */ 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 @@ public function getObject($key = null, ?string $keyField = null): ?FlexObjectInt return $this->createObject([], ''); } - $keyField = $keyField ?? ''; + $keyField ??= ''; $index = $this->indexes[$keyField] ?? $this->loadIndex($keyField); return $index->get($key); @@ -908,14 +908,14 @@ protected function dynamicFlexField(array &$field, $property, array $call): void $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 @@ protected function dynamicAuthorizeField(array &$field, $property, array $call): $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 @@ protected function getAuthorizeScope(): string */ 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 @@ public function getType(): string */ 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 @@ public function update(array $data, ?string $key = null): FlexObjectInterface */ 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 01041f7115..aea03d3179 100644 --- a/system/src/Grav/Framework/Flex/FlexDirectoryForm.php +++ b/system/src/Grav/Framework/Flex/FlexDirectoryForm.php @@ -148,11 +148,10 @@ public function setUniqueId(string $uniqueId): void /** * @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 @@ public function get($name, $default = null, $separator = null) /** * @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 @@ public function __get($name) /** * @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 2d00b9d678..f08456bc57 100644 --- a/system/src/Grav/Framework/Flex/FlexForm.php +++ b/system/src/Grav/Framework/Flex/FlexForm.php @@ -191,11 +191,10 @@ public function setUniqueId(string $uniqueId): void /** * @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 @@ public function get($name, $default = null, $separator = null) /** * @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 @@ public function __get($name) /** * @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 084c346b96..2e04cc8956 100644 --- a/system/src/Grav/Framework/Flex/FlexFormFlash.php +++ b/system/src/Grav/Framework/Flex/FlexFormFlash.php @@ -103,7 +103,7 @@ protected function init(?array $data, array $config): void { 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 ec47ed8c97..aaa03d82f4 100644 --- a/system/src/Grav/Framework/Flex/FlexIdentifier.php +++ b/system/src/Grav/Framework/Flex/FlexIdentifier.php @@ -15,8 +15,6 @@ */ class FlexIdentifier extends Identifier { - /** @var string */ - private $keyField; /** @var FlexObjectInterface|null */ private $object = null; @@ -38,11 +36,9 @@ public static function createFromObject(FlexObjectInterface $object): FlexIdenti * @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 4f73a3e35f..bbfbebac26 100644 --- a/system/src/Grav/Framework/Flex/FlexIndex.php +++ b/system/src/Grav/Framework/Flex/FlexIndex.php @@ -44,9 +44,6 @@ 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 @@ public static function updateObjectMeta(array &$meta, array $data, FlexStorageIn * 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 @@ public function getFlexFeatures(): array $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 @@ public function orderBy(array $orderings) } // 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 @@ protected static function onChanges(array $entries, array $added, array $updated */ 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 8be3081891..6763020424 100644 --- a/system/src/Grav/Framework/Flex/FlexObject.php +++ b/system/src/Grav/Framework/Flex/FlexObject.php @@ -51,7 +51,7 @@ * 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 @@ public static function createFromStorage(array $elements, array $storage, FlexDi * {@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 @@ public function getFlexFeatures(): array $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 @@ public function refresh(bool $keepMissing = false): bool // 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 @@ public function search(string $search, $properties = null, ?array $options = nul $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 @@ public function exists(): bool */ 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 @@ public function searchProperty(string $property, string $search, ?array $options */ 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 @@ public function searchNestedProperty(string $property, string $search, ?array $o /** * @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 @@ public function render(?string $layout = null, array $context = []) $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 @@ public function setFlexDirectory(FlexDirectory $directory): void * @return string */ #[\ReturnTypeWillChange] - public function __toString() + public function __toString(): string { return $this->getFlexKey(); } @@ -1090,7 +1080,7 @@ protected function getTemplatePaths(string $layout): array 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 @@ public function triggerEvent(string $name, $event = null) '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 bea37ee8da..9ad0fa62a6 100644 --- a/system/src/Grav/Framework/Flex/Interfaces/FlexDirectoryInterface.php +++ b/system/src/Grav/Framework/Flex/Interfaces/FlexDirectoryInterface.php @@ -46,10 +46,9 @@ public function getDescription(): string; /** * @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 5893c23de9..84cd2fa6d4 100644 --- a/system/src/Grav/Framework/Flex/Interfaces/FlexObjectInterface.php +++ b/system/src/Grav/Framework/Flex/Interfaces/FlexObjectInterface.php @@ -207,5 +207,5 @@ public function getDefaultValues(): array; * @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 1e49734f84..3d9fddbc92 100644 --- a/system/src/Grav/Framework/Flex/Pages/FlexPageObject.php +++ b/system/src/Grav/Framework/Flex/Pages/FlexPageObject.php @@ -300,20 +300,18 @@ public function getMediaOrder(): array 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 @@ protected function loadHeaderProperty(string $property, $var, callable $filter) * 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 @@ public function setProperty($property, $value) 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 @@ public function setNestedProperty($property, $value, $separator = null) 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 @@ protected function filterElements(array &$elements, bool $extended = false): voi } 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 878c5cba60..7b0f8f2010 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 @@ protected function loadAuthors(iterable $authors): array */ 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 99c5dfde15..4d58e981ad 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 @@ public function title($var = null): string 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 @@ public function menu($var = null): string return $this->loadHeaderProperty( 'menu', $var, - function ($value) { - return trim($value ?: $this->title()); - } + fn($value) => trim((string) ($value ?: $this->title())) ); } @@ -230,9 +226,7 @@ public function visible($var = null): bool $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 @@ public function published($var = null): bool return $this->loadHeaderProperty( 'published', $var, - static function ($value) { - return (bool)($value ?? true); - } + static fn($value) => (bool)($value ?? true) ); } @@ -260,9 +252,7 @@ public function publishDate($var = null): ?int 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 @@ public function unpublishDate($var = null): ?int 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 @@ public function lastModified($var = null): bool 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 @@ public function dateformat($var = null): ?string return $this->loadHeaderProperty( 'dateformat', $var, - static function ($value) { - return $value; - } + static fn($value) => $value ); } @@ -568,7 +552,7 @@ protected function pageContentValue($name, $default = null) 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 @@ protected function processSummary($size = null, $textOnly = false): string $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 @@ protected function processSummary($size = null, $textOnly = false): string 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 @@ protected function processSummary($size = null, $textOnly = false): string // 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 @@ protected function processMarkdown($content, array $options = []): string // 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 @@ static function ($matches) use ($token) { return $token[0] . base64_encode($matc // 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 37bca5e5af..581e4f2f21 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 @@ public function httpHeaders(): array // 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 @@ public function blueprintName(): string } $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 @@ public function name($var = null): string '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 @@ public function template($var = null): string 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 @@ public function templateFormat($var = null): string 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 @@ public function expires($var = null): int 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 @@ public function cacheControl($var = null): ?string 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 @@ public function ssl($var = null): ?bool return $this->loadHeaderProperty( 'ssl', $var, - static function ($value) { - return $value ? (bool)$value : null; - } + static fn($value) => $value ? (bool)$value : null ); } @@ -655,7 +645,7 @@ public function metadata($var = null): array $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 @@ public function metadata($var = null): array 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 @@ public function eTag($var = null): bool 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 @@ public function orderDir($var = null): string 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 @@ public function orderBy($var = null): string 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 @@ public function orderManual($var = null): array return $this->loadHeaderProperty( 'order_manual', $var, - static function ($value) { - return (array)$value; - } + static fn($value) => (array)$value ); } @@ -827,9 +809,7 @@ public function maxCount($var = null): int 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 @@ public function modularTwig($var = null): bool } } - 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 b5b3f899e1..6892d99220 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 @@ public function routable($var = null): bool $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 @@ public function redirect($var = null): ?string 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 6fc09fb0e9..1a0c6e5881 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 @@ public function language($var = null): ?string 'lang', $var, function ($value) { - $value = $value ?? $this->getMetaData()['lang'] ?? ''; + $value ??= $this->getMetaData()['lang'] ?? ''; return trim($value) ?: null; } @@ -272,7 +272,7 @@ protected function getLanguageTemplates(): array */ 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 @@ protected function getFallbackLanguages(?string $languageCode = null, ?bool $fal /** @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 d919f3a4b9..ccb164f100 100644 --- a/system/src/Grav/Framework/Flex/Storage/AbstractFilesystemStorage.php +++ b/system/src/Grav/Framework/Flex/Storage/AbstractFilesystemStorage.php @@ -163,19 +163,12 @@ protected function getFile(string $filename) $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 4ed0660fd0..fabe798d8a 100644 --- a/system/src/Grav/Framework/Flex/Storage/FileStorage.php +++ b/system/src/Grav/Framework/Flex/Storage/FileStorage.php @@ -146,7 +146,7 @@ protected function buildIndex(): array $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 790eafdc4d..0f0a95a165 100644 --- a/system/src/Grav/Framework/Flex/Storage/FolderStorage.php +++ b/system/src/Grav/Framework/Flex/Storage/FolderStorage.php @@ -413,7 +413,7 @@ protected function saveRow(string $key, array $row): array 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 @@ protected function getObjectMeta(string $key, bool $reload = false): array 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 @@ protected function buildIndexFromFilesystem($path) $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 @@ protected function buildPrefixedIndexFromFilesystem($path) $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 4ffddd3b24..6e27f44974 100644 --- a/system/src/Grav/Framework/Flex/Storage/SimpleStorage.php +++ b/system/src/Grav/Framework/Flex/Storage/SimpleStorage.php @@ -119,7 +119,7 @@ public function hasKey(string $key): bool $this->buildIndex(); } - return $key && strpos($key, '@@') === false && isset($this->data[$key]); + return $key && !str_contains($key, '@@') && isset($this->data[$key]); } /** @@ -355,7 +355,7 @@ protected function saveRow(string $key, array $row): array 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 17b3212b5a..48f8ab1cbe 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 e87b878865..ecf1a13aa4 100644 --- a/system/src/Grav/Framework/Flex/Traits/FlexMediaTrait.php +++ b/system/src/Grav/Framework/Flex/Traits/FlexMediaTrait.php @@ -143,7 +143,7 @@ public function getFieldSettings(string $field): ?array // 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 2922f030c8..2e7aa65f00 100644 --- a/system/src/Grav/Framework/Flex/Traits/FlexRelatedDirectoryTrait.php +++ b/system/src/Grav/Framework/Flex/Traits/FlexRelatedDirectoryTrait.php @@ -35,9 +35,7 @@ protected function getCollectionByProperty($type, $property) $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 8de7588900..0a0ae1741b 100644 --- a/system/src/Grav/Framework/Form/FormFlash.php +++ b/system/src/Grav/Framework/Form/FormFlash.php @@ -64,7 +64,7 @@ public function __construct($config) { // 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 @@ public function __construct($config) '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 @@ protected function loadStoredForm(): ?array if ($exists) { try { $data = (array)$file->content(); - } catch (Exception $e) { + } catch (Exception) { } } @@ -168,7 +166,7 @@ public function getUniqueId(): string */ 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 3dcf59e2ab..bbe312d45e 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 b64dd9a9ba..4c07468f62 100644 --- a/system/src/Grav/Framework/Form/Traits/FormTrait.php +++ b/system/src/Grav/Framework/Form/Traits/FormTrait.php @@ -612,7 +612,7 @@ protected function getFlashFolder(): ?string $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 @@ protected function getFlashId(): ?string $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 @@ protected function jsonDecode(array $data): array 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 e177c9f0bb..773b53aa28 100644 --- a/system/src/Grav/Framework/Media/Interfaces/MediaObjectInterface.php +++ b/system/src/Grav/Framework/Media/Interfaces/MediaObjectInterface.php @@ -43,5 +43,5 @@ public function url($reset = true); * @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 986e997c70..a8ed764e59 100644 --- a/system/src/Grav/Framework/Media/MediaIdentifier.php +++ b/system/src/Grav/Framework/Media/MediaIdentifier.php @@ -121,7 +121,7 @@ protected function findFlash(array $parts): ?array 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 8a438bf93a..49fc4381ff 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 @@ protected function processMediaActions(GravMediaObjectInterface $medium, array $ 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 0fe12e1cc0..5d5d366fc0 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 @@ public static function createFromFlash(FlexFormFlash $flash, ?string $field, str * @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 de6c6b9ed2..95fca777ae 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 @@ public function offsetExists($offset) * @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 @@ public function offsetGet($offset) * @return void */ #[\ReturnTypeWillChange] - public function offsetSet($offset, $value) + public function offsetSet(mixed $offset, mixed $value) { $this->setProperty($offset, $value); } @@ -59,7 +59,7 @@ public function offsetSet($offset, $value) * @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 938ec26b4f..f63e2a0915 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 @@ public function offsetExists($offset) * @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 @@ public function offsetGet($offset) * @return void */ #[\ReturnTypeWillChange] - public function offsetSet($offset, $value) + public function offsetSet(mixed $offset, mixed $value) { $this->setNestedProperty($offset, $value); } @@ -59,7 +59,7 @@ public function offsetSet($offset, $value) * @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 1d749e3dab..5fb9f993f7 100644 --- a/system/src/Grav/Framework/Object/Access/NestedPropertyCollectionTrait.php +++ b/system/src/Grav/Framework/Object/Access/NestedPropertyCollectionTrait.php @@ -40,7 +40,7 @@ public function hasNestedProperty($property, $separator = null) * @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 @@ public function getNestedProperty($property, $default = null, $separator = null) * @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 3bfebe0bde..3feec5f876 100644 --- a/system/src/Grav/Framework/Object/Access/NestedPropertyTrait.php +++ b/system/src/Grav/Framework/Object/Access/NestedPropertyTrait.php @@ -82,7 +82,7 @@ public function getNestedProperty($property, $default = null, $separator = null) * @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 @@ public function unsetNestedProperty($property, $separator = null) * @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 428473aff3..e18bb1539a 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 @@ public function __isset($offset) * @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 @@ public function __get($offset) * @return void */ #[\ReturnTypeWillChange] - public function __set($offset, $value) + public function __set(mixed $offset, mixed $value) { $this->setProperty($offset, $value); } @@ -59,7 +59,7 @@ public function __set($offset, $value) * @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 d9d8e41df8..bc1e0391cd 100644 --- a/system/src/Grav/Framework/Object/Base/ObjectCollectionTrait.php +++ b/system/src/Grav/Framework/Object/Base/ObjectCollectionTrait.php @@ -54,7 +54,7 @@ public function getType($prefix = true) return $type . static::$type; } - $class = get_class($this); + $class = $this::class; return $type . strtolower(substr($class, strrpos($class, '\\') + 1)); } @@ -89,7 +89,7 @@ public function hasProperty($property) * @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 @@ public function getProperty($property, $default = null) * @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 @@ public function unsetProperty($property) * @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 @@ public function doHasProperty($property) * @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 @@ public function &doGetProperty($property, $default = null, $doCreate = false) * @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 @@ public function doUnsetProperty($property) * @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 522e5142e5..4bb2d0ba45 100644 --- a/system/src/Grav/Framework/Object/Base/ObjectTrait.php +++ b/system/src/Grav/Framework/Object/Base/ObjectTrait.php @@ -48,7 +48,7 @@ public function getType($prefix = true) return $type . static::$type; } - $class = get_class($this); + $class = $this::class; return $type . strtolower(substr($class, strrpos($class, '\\') + 1)); } @@ -82,7 +82,7 @@ public function hasProperty($property) * @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 @@ public function getProperty($property, $default = null) * @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 @@ public function unsetProperty($property) * @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 d622538251..844f81140a 100644 --- a/system/src/Grav/Framework/Object/Collection/ObjectExpressionVisitor.php +++ b/system/src/Grav/Framework/Object/Collection/ObjectExpressionVisitor.php @@ -46,7 +46,7 @@ public static function getObjectFieldValue($object, $field) 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 @@ public static function filterTrim($str) 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 @@ public function walkComparison(Comparison $comparison) $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 69f41d2b87..9c5e029089 100644 --- a/system/src/Grav/Framework/Object/Identifiers/Identifier.php +++ b/system/src/Grav/Framework/Object/Identifiers/Identifier.php @@ -11,20 +11,13 @@ */ 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 ed81bb2fec..e217e8383b 100644 --- a/system/src/Grav/Framework/Object/Interfaces/NestedObjectCollectionInterface.php +++ b/system/src/Grav/Framework/Object/Interfaces/NestedObjectCollectionInterface.php @@ -43,7 +43,7 @@ public function getNestedProperty($property, $default = null, $separator = null) * @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 @@ public function setNestedProperty($property, $value, $separator = null); * @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 647f6c7803..22adbce5aa 100644 --- a/system/src/Grav/Framework/Object/Interfaces/NestedObjectInterface.php +++ b/system/src/Grav/Framework/Object/Interfaces/NestedObjectInterface.php @@ -39,7 +39,7 @@ public function getNestedProperty($property, $default = null, $separator = null) * @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 @@ public function setNestedProperty($property, $value, $separator = null); * @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 1568561047..1f053836db 100644 --- a/system/src/Grav/Framework/Object/Interfaces/ObjectCollectionInterface.php +++ b/system/src/Grav/Framework/Object/Interfaces/ObjectCollectionInterface.php @@ -57,14 +57,14 @@ public function getProperty($property, $default = null); * @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 f505f4711e..1eb7b5e774 100644 --- a/system/src/Grav/Framework/Object/Interfaces/ObjectInterface.php +++ b/system/src/Grav/Framework/Object/Interfaces/ObjectInterface.php @@ -46,14 +46,14 @@ public function getProperty($property, $default = null); * @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 a241eda5db..52f1648516 100644 --- a/system/src/Grav/Framework/Object/ObjectIndex.php +++ b/system/src/Grav/Framework/Object/ObjectIndex.php @@ -49,7 +49,7 @@ public function getType($prefix = true) 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 0c0a549b94..85dc1489b0 100644 --- a/system/src/Grav/Framework/Object/Property/ArrayPropertyTrait.php +++ b/system/src/Grav/Framework/Object/Property/ArrayPropertyTrait.php @@ -50,7 +50,7 @@ protected function doHasProperty($property) * @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 @@ protected function &doGetProperty($property, $default = null, $doCreate = false) * @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 @@ protected function getElement($property, $default = null) */ 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 fe00d502f8..03a97323fe 100644 --- a/system/src/Grav/Framework/Object/Property/LazyPropertyTrait.php +++ b/system/src/Grav/Framework/Object/Property/LazyPropertyTrait.php @@ -56,12 +56,10 @@ protected function doHasProperty($property) * @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 @@ protected function &doGetProperty($property, $default = null, $doCreate = false) * @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 3734760c14..436cfec31a 100644 --- a/system/src/Grav/Framework/Object/Property/MixedPropertyTrait.php +++ b/system/src/Grav/Framework/Object/Property/MixedPropertyTrait.php @@ -57,7 +57,7 @@ protected function doHasProperty($property) * @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 @@ protected function &doGetProperty($property, $default = null, $doCreate = false) * @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 618dbbd958..56413cfae8 100644 --- a/system/src/Grav/Framework/Object/Property/ObjectPropertyTrait.php +++ b/system/src/Grav/Framework/Object/Property/ObjectPropertyTrait.php @@ -55,10 +55,9 @@ protected function isPropertyLoaded($property) /** * @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 @@ protected function offsetLoad($offset, $value) /** * @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 @@ protected function offsetPrepare($offset, $value) /** * @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 @@ protected function doHasProperty($property) * @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 @@ protected function &doGetProperty($property, $default = null, $doCreate = false) * @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 401b1662b8..f928fa461f 100644 --- a/system/src/Grav/Framework/Pagination/AbstractPagination.php +++ b/system/src/Grav/Framework/Pagination/AbstractPagination.php @@ -132,10 +132,10 @@ public function getPage(int $page, ?string $label = null): ?PaginationPage $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 f00913513a..b2269a9342 100644 --- a/system/src/Grav/Framework/Psr7/AbstractUri.php +++ b/system/src/Grav/Framework/Psr7/AbstractUri.php @@ -264,7 +264,7 @@ public function withFragment($fragment) * @return string */ #[\ReturnTypeWillChange] - public function __toString() + public function __toString(): string { return $this->getUrl(); } @@ -377,10 +377,10 @@ private function validate() } 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 b7ed93e380..57d41ed12b 100644 --- a/system/src/Grav/Framework/Psr7/Response.php +++ b/system/src/Grav/Framework/Psr7/Response.php @@ -21,7 +21,7 @@ * Class Response * @package Slim\Http */ -class Response implements ResponseInterface +class Response implements ResponseInterface, \Stringable { use ResponseDecoratorTrait; @@ -55,7 +55,7 @@ public function __construct(int $status = 200, array $headers = [], $body = null * @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 79f273b200..0bb8c3e593 100644 --- a/system/src/Grav/Framework/Psr7/ServerRequest.php +++ b/system/src/Grav/Framework/Psr7/ServerRequest.php @@ -50,11 +50,7 @@ public function getContentCharset(): ?string { $mediaTypeParams = $this->getMediaTypeParams(); - if (isset($mediaTypeParams['charset'])) { - return $mediaTypeParams['charset']; - } - - return null; + return $mediaTypeParams['charset'] ?? null; } /** @@ -95,7 +91,7 @@ public function getContentLength(): ?int * * @return mixed */ - public function getCookieParam($key, $default = null) + public function getCookieParam($key, mixed $default = null) { $cookies = $this->getRequest()->getCookieParams(); @@ -202,11 +198,10 @@ public function getParams(): array * 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 @@ public function getParsedBodyParam($key, $default = null) * 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 @@ public function getQueryParam($key, $default = null) * 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 55c004d47f..be089f5157 100644 --- a/system/src/Grav/Framework/Relationships/Relationships.php +++ b/system/src/Grav/Framework/Relationships/Relationships.php @@ -102,10 +102,9 @@ public function offsetGet($offset): ?RelationshipInterface /** * @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 @@ private function createRelationship(string $name, array $options): RelationshipI } $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 dbe146fcc3..1d7d82e88f 100644 --- a/system/src/Grav/Framework/Relationships/Traits/RelationshipTrait.php +++ b/system/src/Grav/Framework/Relationships/Traits/RelationshipTrait.php @@ -109,7 +109,7 @@ private function checkIdentifier(IdentifierInterface $identifier): IdentifierInt 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 4ca59541a5..52092541f0 100644 --- a/system/src/Grav/Framework/RequestHandler/Exception/InvalidArgumentException.php +++ b/system/src/Grav/Framework/RequestHandler/Exception/InvalidArgumentException.php @@ -19,9 +19,6 @@ */ 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 bd894fe580..2544aae5f1 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 80deef06fc..b6e5293e4d 100644 --- a/system/src/Grav/Framework/RequestHandler/Middlewares/Exceptions.php +++ b/system/src/Grav/Framework/RequestHandler/Middlewares/Exceptions.php @@ -62,7 +62,7 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface $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 6e36e8f152..eaa8826c2f 100644 --- a/system/src/Grav/Framework/RequestHandler/Middlewares/MultipartRequestSupport.php +++ b/system/src/Grav/Framework/RequestHandler/Middlewares/MultipartRequestSupport.php @@ -83,14 +83,14 @@ static function (array $headers, $header) { // 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 8d009890fa..927eb21f01 100644 --- a/system/src/Grav/Framework/Route/Route.php +++ b/system/src/Grav/Framework/Route/Route.php @@ -19,7 +19,7 @@ * * @package Grav\Framework\Route */ -class Route +class Route implements \Stringable { /** @var string */ private $root = ''; @@ -270,20 +270,18 @@ public function withExtension($extension) /** * @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 @@ public function toString(bool $includeRoot = false) * @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 @@ public function __toString() /** * @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 @@ protected function initParts(array $parts) $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 6844e48975..44b91d315e 100644 --- a/system/src/Grav/Framework/Route/RouteFactory.php +++ b/system/src/Grav/Framework/Route/RouteFactory.php @@ -49,7 +49,7 @@ public static function createFromLegacyUri(Uri $uri): Route $parts['grav'] += [ 'root' => self::$root, 'language' => self::$language, - 'route' => trim($path, '/'), + 'route' => trim((string) $path, '/'), 'params' => $parts['params'] ?? [], ]; @@ -198,7 +198,7 @@ public static function trimParams(string $str): string $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 @@ public static function parseParams(string $str): array $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 5867c15133..b4ac68d5e6 100644 --- a/system/src/Grav/Framework/Session/Session.php +++ b/system/src/Grav/Framework/Session/Session.php @@ -198,7 +198,7 @@ public function start($readonly = false) $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 @@ public function start($readonly = false) 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 @@ public function invalidate() setcookie( $name, '', - $this->getCookieOptions(-42000) + ['expires' => $this->getCookieOptions(-42000)] ); } @@ -507,7 +507,7 @@ protected function setCookie(): void setcookie( $sessionName, $sessionId, - $this->getCookieOptions() + ['expires' => $this->getCookieOptions()] ); } @@ -519,7 +519,7 @@ protected function removeCookie(): void 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 @@ protected function removeCookie(): void /** * @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 f160b10880..efebc4f46c 100644 --- a/system/src/Grav/Framework/Session/SessionInterface.php +++ b/system/src/Grav/Framework/Session/SessionInterface.php @@ -142,11 +142,10 @@ public function __get($name); * 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 cb917ed6bd..6bf6f9eff9 100644 --- a/system/src/Grav/Framework/Uri/UriFactory.php +++ b/system/src/Grav/Framework/Uri/UriFactory.php @@ -59,10 +59,10 @@ public static function parseUrlFromEnvironment(array $env) { // 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 @@ public static function parseUrlFromEnvironment(array $env) $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 @@ public static function parseUrlFromEnvironment(array $env) } // 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 @@ public static function parseUrl($url) $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 27b72acc93..badf935497 100644 --- a/system/src/Grav/Framework/Uri/UriPartsFilter.php +++ b/system/src/Grav/Framework/Uri/UriPartsFilter.php @@ -50,9 +50,7 @@ public static function filterUserInfo($info) 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 @@ public static function filterPath($path) 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 @@ public static function filterQueryOrFragment($query) 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 1fde78307b..2c650c86a9 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 be28ebf4aa..b4986dd88d 100644 --- a/system/src/Grav/Installer/VersionUpdater.php +++ b/system/src/Grav/Installer/VersionUpdater.php @@ -10,14 +10,6 @@ */ 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 f3f4ef9873..9f9342bff2 100644 --- a/system/src/Grav/Installer/Versions.php +++ b/system/src/Grav/Installer/Versions.php @@ -20,8 +20,6 @@ */ 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 @@ private function fixHistory(array $history): array * @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 @@ private function get(string $name, $default = null) * @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 @@ private function undef(string $name): void $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 b8aa07874c..9a6dd2b356 100644 --- a/system/src/Grav/Installer/YamlUpdater.php +++ b/system/src/Grav/Installer/YamlUpdater.php @@ -103,9 +103,8 @@ public function getComments(): array /** * @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 @@ private function findPath(array $lines, array $parts) 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 @@ private function findPath(array $lines, array $parts) } - 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 @@ private function getLineIndentation(string $line): int * @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 @@ private function get(string $name, $default = null) * @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;