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('