rector fixes for PHP 8.2+

Signed-off-by: Andy Miller <rhuk@mac.com>
This commit is contained in:
Andy Miller
2024-12-09 17:23:56 -07:00
parent 4a27bd780c
commit 17548131d3
211 changed files with 1096 additions and 1645 deletions

View File

@@ -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);
}

View File

@@ -194,12 +194,12 @@ class Assets extends PropertyObject
}
$params = array_merge([$location], $params);
call_user_func_array([$this, 'add'], $params);
call_user_func_array($this->add(...), $params);
}
} elseif (isset($this->collections[$asset])) {
array_shift($args);
$args = array_merge([$this->collections[$asset]], $args);
call_user_func_array([$this, 'add'], $args);
call_user_func_array($this->add(...), $args);
} else {
// Get extension
$path = parse_url($asset, PHP_URL_PATH);
@@ -209,11 +209,11 @@ class Assets extends PropertyObject
if ($extension !== '') {
$extension = strtolower($extension);
if ($extension === 'css') {
call_user_func_array([$this, 'addCss'], $args);
call_user_func_array($this->addCss(...), $args);
} elseif ($extension === 'js') {
call_user_func_array([$this, 'addJs'], $args);
call_user_func_array($this->addJs(...), $args);
} elseif ($extension === 'mjs') {
call_user_func_array([$this, 'addJsModule'], $args);
call_user_func_array($this->addJsModule(...), $args);
}
}
}
@@ -261,7 +261,7 @@ class Assets extends PropertyObject
$default = 'before';
}
$options['position'] = $options['position'] ?? $default;
$options['position'] ??= $default;
}
unset($options['pipeline']);
@@ -432,9 +432,7 @@ class Assets extends PropertyObject
*/
protected function sortAssets($assets)
{
uasort($assets, static function ($a, $b) {
return $b['priority'] <=> $a['priority'] ?: $a['order'] <=> $b['order'];
});
uasort($assets, static fn($a, $b) => $b['priority'] <=> $a['priority'] ?: $a['order'] <=> $b['order']);
return $assets;
}
@@ -577,18 +575,11 @@ class Assets extends PropertyObject
*/
protected function getBaseType($type)
{
switch ($type) {
case $this::JS_TYPE:
case $this::INLINE_JS_TYPE:
$base_type = $this::JS;
break;
case $this::JS_MODULE_TYPE:
case $this::INLINE_JS_MODULE_TYPE:
$base_type = $this::JS_MODULE;
break;
default:
$base_type = $this::CSS;
}
$base_type = match ($type) {
$this::JS_TYPE, $this::INLINE_JS_TYPE => $this::JS,
$this::JS_MODULE_TYPE, $this::INLINE_JS_MODULE_TYPE => $this::JS_MODULE,
default => $this::CSS,
};
return $base_type;
}

View File

@@ -114,7 +114,7 @@ abstract class BaseAsset extends PropertyObject
// Do some special stuff for CSS/JS (not inline)
if (!Utils::startsWith($this->getType(), 'inline')) {
$this->base_url = rtrim($uri->rootUrl($config->get('system.absolute_urls')), '/') . '/';
$this->base_url = rtrim((string) $uri->rootUrl($config->get('system.absolute_urls')), '/') . '/';
$this->remote = static::isRemoteLink($asset);
// Move this to render?

View File

@@ -192,15 +192,15 @@ class BlockAssets
{
$grav = Grav::instance();
$base = rtrim($grav['base_url'], '/') ?: '/';
$base = rtrim((string) $grav['base_url'], '/') ?: '/';
if (strpos($url, $base) === 0) {
if (str_starts_with($url, $base)) {
if ($pipeline) {
// Remove file timestamp if CSS pipeline has been enabled.
$url = preg_replace('|[?#].*|', '', $url);
}
return substr($url, strlen($base) - 1);
return substr((string) $url, strlen($base) - 1);
}
return $url;
}

View File

@@ -283,7 +283,7 @@ class Pipeline extends PropertyObject
} else {
return str_replace($matches[2], $new_url, $matches[0]);
}
}, $file);
}, (string) $file);
return $file;
}

View File

@@ -55,7 +55,7 @@ trait AssetUtilsTrait
return false;
}
return (0 === strpos($link, 'http://') || 0 === strpos($link, 'https://') || 0 === strpos($link, '//'));
return (str_starts_with($link, 'http://') || str_starts_with($link, 'https://') || str_starts_with($link, '//'));
}
/**
@@ -76,18 +76,18 @@ trait AssetUtilsTrait
if (static::isRemoteLink($link)) {
$local = false;
if (0 === strpos($link, '//')) {
if (str_starts_with((string) $link, '//')) {
$link = 'http:' . $link;
}
$relative_dir = dirname($relative_path);
$relative_dir = dirname((string) $relative_path);
} else {
// Fix to remove relative dir if grav is in one
if (($this->base_url !== '/') && Utils::startsWith($relative_path, $this->base_url)) {
$base_url = '#' . preg_quote($this->base_url, '#') . '#';
$relative_path = ltrim(preg_replace($base_url, '/', $link, 1), '/');
$relative_path = ltrim(preg_replace($base_url, '/', (string) $link, 1), '/');
}
$relative_dir = dirname($relative_path);
$relative_dir = dirname((string) $relative_path);
$link = GRAV_ROOT . '/' . $relative_path;
}
@@ -101,7 +101,7 @@ trait AssetUtilsTrait
// Double check last character being
if ($type === self::JS_ASSET || $type === self::JS_MODULE_ASSET) {
$file = rtrim($file, ' ;') . ';';
$file = rtrim((string) $file, ' ;') . ';';
}
// If this is CSS + the file is local + rewrite enabled
@@ -113,7 +113,7 @@ trait AssetUtilsTrait
$file = $this->jsRewrite($file, $relative_dir, $local);
}
$file = rtrim($file) . PHP_EOL;
$file = rtrim((string) $file) . PHP_EOL;
$buffer .= $file;
}
@@ -191,7 +191,7 @@ trait AssetUtilsTrait
{
$querystring = '';
$asset = $asset ?? $this->asset;
$asset ??= $this->asset;
$attributes = $this->attributes;
if (!empty($this->query)) {

View File

@@ -113,7 +113,7 @@ trait LegacyAssetsTrait
*/
public function addAsyncJs($asset, $priority = 10, $pipeline = true, $group = 'head')
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use dynamic method with [\'loading\' => \'async\']', E_USER_DEPRECATED);
user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use dynamic method with [\'loading\' => \'async\']', E_USER_DEPRECATED);
return $this->addJs($asset, $priority, $pipeline, 'async', $group);
}
@@ -130,7 +130,7 @@ trait LegacyAssetsTrait
*/
public function addDeferJs($asset, $priority = 10, $pipeline = true, $group = 'head')
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use dynamic method with [\'loading\' => \'defer\']', E_USER_DEPRECATED);
user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use dynamic method with [\'loading\' => \'defer\']', E_USER_DEPRECATED);
return $this->addJs($asset, $priority, $pipeline, 'defer', $group);
}

View File

@@ -338,7 +338,7 @@ trait TestingAssetsTrait
$directory,
FilesystemIterator::SKIP_DOTS
)), $pattern);
$offset = strlen($ltrim);
$offset = strlen((string) $ltrim);
$files = [];
foreach ($iterator as $file) {

View File

@@ -54,7 +54,7 @@ class Backups
/** @var EventDispatcher $dispatcher */
$dispatcher = $grav['events'];
$dispatcher->addListener('onSchedulerInitialized', [$this, 'onSchedulerInitialized']);
$dispatcher->addListener('onSchedulerInitialized', $this->onSchedulerInitialized(...));
$grav->fireEvent('onBackupsInitialized', new Event(['backups' => $this]));
}
@@ -106,7 +106,7 @@ class Backups
{
$param_sep = Grav::instance()['config']->get('system.param_sep', ':');
$download = urlencode(base64_encode(Utils::basename($backup)));
$url = rtrim(Grav::instance()['uri']->rootUrl(true), '/') . '/' . trim(
$url = rtrim((string) Grav::instance()['uri']->rootUrl(true), '/') . '/' . trim(
$base_url,
'/'
) . '/task' . $param_sep . 'backup/download' . $param_sep . $download . '/admin-nonce' . $param_sep . Utils::getNonce('admin-form');
@@ -158,7 +158,7 @@ class Backups
static::$backups = [];
$grav = Grav::instance();
$backups_itr = new GlobIterator(static::$backup_dir . '/*.zip', FilesystemIterator::KEY_AS_FILENAME);
$backups_itr = new GlobIterator(static::$backup_dir . '/*.zip', FilesystemIterator::KEY_AS_FILENAME | \FilesystemIterator::SKIP_DOTS);
$inflector = $grav['inflector'];
$long_date_format = DATE_RFC2822;
@@ -210,7 +210,7 @@ class Backups
$name = $grav['inflector']->underscorize($backup->name);
$date = date(static::BACKUP_DATE_FORMAT, time());
$filename = trim($name, '_') . '--' . $date . '.zip';
$filename = trim((string) $name, '_') . '--' . $date . '.zip';
$destination = static::$backup_dir . DS . $filename;
$max_execution_time = ini_set('max_execution_time', '600');
$backup_root = $backup->root;

View File

@@ -27,7 +27,7 @@ class Browser
{
try {
$this->useragent = parse_user_agent();
} catch (InvalidArgumentException $e) {
} catch (InvalidArgumentException) {
$this->useragent = parse_user_agent("Mozilla/5.0 (compatible; Unknown;)");
}
}

View File

@@ -160,7 +160,7 @@ class Cache extends Getters
/** @var EventDispatcher $dispatcher */
$dispatcher = Grav::instance()['events'];
$dispatcher->addListener('onSchedulerInitialized', [$this, 'onSchedulerInitialized']);
$dispatcher->addListener('onSchedulerInitialized', $this->onSchedulerInitialized(...));
}
/**
@@ -264,8 +264,8 @@ class Cache extends Getters
}
$this->driver_name = $driver_name;
$namespace = $namespace ?? $this->key;
$defaultLifetime = $defaultLifetime ?? 0;
$namespace ??= $this->key;
$defaultLifetime ??= 0;
switch ($driver_name) {
case 'apc':

View File

@@ -202,7 +202,7 @@ abstract class CompiledBase
$cache = include $filename;
if (!is_array($cache)
|| !isset($cache['checksum'], $cache['data'], $cache['@class'])
|| $cache['@class'] !== get_class($this)
|| $cache['@class'] !== static::class
) {
return false;
}
@@ -235,7 +235,7 @@ abstract class CompiledBase
// Attempt to lock the file for writing.
try {
$file->lock(false);
} catch (Exception $e) {
} catch (Exception) {
// Another process has locked the file; we will check this in a bit.
}
@@ -245,7 +245,7 @@ abstract class CompiledBase
}
$cache = [
'@class' => get_class($this),
'@class' => static::class,
'timestamp' => time(),
'checksum' => $this->checksum(),
'files' => $this->files,

View File

@@ -149,7 +149,7 @@ class Config extends Data
*/
public function getLanguages()
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use Grav::instance()[\'languages\'] instead', E_USER_DEPRECATED);
user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use Grav::instance()[\'languages\'] instead', E_USER_DEPRECATED);
return Grav::instance()['languages'];
}

View File

@@ -178,9 +178,7 @@ class ConfigFileFinder
'filters' => [
'pre-key' => $this->base,
'key' => $pattern,
'value' => function (RecursiveDirectoryIterator $file) use ($path) {
return ['file' => "{$path}/{$file->getSubPathname()}", 'modified' => $file->getMTime()];
}
'value' => fn(RecursiveDirectoryIterator $file) => ['file' => "{$path}/{$file->getSubPathname()}", 'modified' => $file->getMTime()]
],
'key' => 'SubPathname'
];
@@ -254,9 +252,7 @@ class ConfigFileFinder
'filters' => [
'pre-key' => $this->base,
'key' => $pattern,
'value' => function (RecursiveDirectoryIterator $file) use ($path) {
return ["{$path}/{$file->getSubPathname()}" => $file->getMTime()];
}
'value' => fn(RecursiveDirectoryIterator $file) => ["{$path}/{$file->getSubPathname()}" => $file->getMTime()]
],
'key' => 'SubPathname'
];

View File

@@ -202,7 +202,7 @@ class Setup extends Data
$setupFile = defined('GRAV_SETUP_PATH') ? GRAV_SETUP_PATH : (getenv('GRAV_SETUP_PATH') ?: null);
if (null !== $setupFile) {
// Make sure that the custom setup file exists. Terminates the script if not.
if (!str_starts_with($setupFile, '/')) {
if (!str_starts_with((string) $setupFile, '/')) {
$setupFile = GRAV_WEBROOT . '/' . $setupFile;
}
if (!is_file($setupFile)) {

View File

@@ -168,7 +168,7 @@ class Blueprint extends BlueprintForm
// Set dynamic property.
foreach ($data as $property => $call) {
$action = $call['action'];
$method = 'dynamic' . ucfirst($action);
$method = 'dynamic' . ucfirst((string) $action);
$call['object'] = $this->object;
if (isset($this->handlers[$action])) {
@@ -434,7 +434,7 @@ class Blueprint extends BlueprintForm
$params = [];
}
[$o, $f] = explode('::', $function, 2);
[$o, $f] = explode('::', (string) $function, 2);
$data = null;
if (!$f) {
@@ -574,10 +574,9 @@ class Blueprint extends BlueprintForm
/**
* @param array $field
* @param string $property
* @param mixed $value
* @return void
*/
public static function addPropertyRecursive(array &$field, $property, $value)
public static function addPropertyRecursive(array &$field, $property, mixed $value)
{
if (is_array($value) && isset($field[$property]) && is_array($field[$property])) {
$field[$property] = array_merge_recursive($field[$property], $value);

View File

@@ -130,7 +130,7 @@ class BlueprintSchema extends BlueprintSchemaBase implements ExportInterface
foreach ($items as $key => $rules) {
$type = $rules['type'] ?? '';
$ignore = (bool) array_filter((array)($rules['validate']['ignore'] ?? [])) ?? false;
if (!str_starts_with($type, '_') && !str_contains($key, '*') && $ignore !== true) {
if (!str_starts_with((string) $type, '_') && !str_contains((string) $key, '*') && $ignore !== true) {
$list[$prefix . $key] = null;
}
}

View File

@@ -22,8 +22,6 @@ use function is_object;
*/
class Blueprints
{
/** @var array|string */
protected $search;
/** @var array */
protected $types;
/** @var array */
@@ -32,9 +30,8 @@ class Blueprints
/**
* @param string|array $search Search path.
*/
public function __construct($search = 'blueprints://')
public function __construct(protected $search = 'blueprints://')
{
$this->search = $search;
}
/**

View File

@@ -103,7 +103,7 @@ class Data implements DataInterface, ArrayAccess, \Countable, JsonSerializable,
* @return $this
* @throws RuntimeException
*/
public function join($name, $value, $separator = '.')
public function join($name, mixed $value, $separator = '.')
{
$old = $this->get($name, null, $separator);
if ($old !== null) {
@@ -145,7 +145,7 @@ class Data implements DataInterface, ArrayAccess, \Countable, JsonSerializable,
* @param string $separator Separator, defaults to '.'
* @return $this
*/
public function joinDefaults($name, $value, $separator = '.')
public function joinDefaults($name, mixed $value, $separator = '.')
{
if (is_object($value)) {
$value = (array) $value;

View File

@@ -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.

View File

@@ -37,11 +37,10 @@ class Validation
/**
* Validate value against a blueprint field definition.
*
* @param mixed $value
* @param array $field
* @return array
*/
public static function validate($value, array $field)
public static function validate(mixed $value, array $field)
{
if (!isset($field['type'])) {
$field['type'] = 'text';
@@ -76,7 +75,7 @@ class Validation
$messages = [];
$success = method_exists(__CLASS__, $method) ? self::$method($value, $validate, $field) : true;
$success = method_exists(self::class, $method) ? self::$method($value, $validate, $field) : true;
if (!$success) {
$messages[$field['name']][] = $message;
}
@@ -85,7 +84,7 @@ class Validation
foreach ($validate as $rule => $params) {
$method = 'validate' . ucfirst(str_replace('-', '_', $rule));
if (method_exists(__CLASS__, $method)) {
if (method_exists(self::class, $method)) {
$success = self::$method($value, $params);
if (!$success) {
@@ -98,11 +97,10 @@ class Validation
}
/**
* @param mixed $value
* @param array $field
* @return array
*/
public static function checkSafety($value, array $field)
public static function checkSafety(mixed $value, array $field)
{
$messages = [];
@@ -115,7 +113,7 @@ class Validation
$options = [];
}
$name = ucfirst($field['label'] ?? $field['name'] ?? 'UNKNOWN');
$name = ucfirst((string) ($field['label'] ?? $field['name'] ?? 'UNKNOWN'));
/** @var UserInterface $user */
$user = Grav::instance()['user'] ?? null;
@@ -186,11 +184,10 @@ class Validation
/**
* Filter value against a blueprint field definition.
*
* @param mixed $value
* @param array $field
* @return mixed Filtered value.
*/
public static function filter($value, array $field)
public static function filter(mixed $value, array $field)
{
$validate = (array)($field['filter'] ?? $field['validate'] ?? null);
@@ -211,7 +208,7 @@ class Validation
$method = 'filterYaml';
}
if (!method_exists(__CLASS__, $method)) {
if (!method_exists(self::class, $method)) {
$method = isset($field['array']) && $field['array'] === true ? 'filterArray' : 'filterText';
}
@@ -226,7 +223,7 @@ class Validation
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeText($value, array $params, array $field)
public static function typeText(mixed $value, array $params, array $field)
{
if (!is_string($value) && !is_numeric($value)) {
return false;
@@ -239,7 +236,7 @@ class Validation
}
$value = preg_replace("/\r\n|\r/um", "\n", $value);
$len = mb_strlen($value);
$len = mb_strlen((string) $value);
$min = (int)($params['min'] ?? 0);
if ($min && $len < $min) {
@@ -258,7 +255,7 @@ class Validation
return false;
}
if (!$multiline && preg_match('/\R/um', $value)) {
if (!$multiline && preg_match('/\R/um', (string) $value)) {
return false;
}
@@ -266,12 +263,11 @@ class Validation
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return string
*/
protected static function filterText($value, array $params, array $field)
protected static function filterText(mixed $value, array $params, array $field)
{
if (!is_string($value) && !is_numeric($value)) {
return '';
@@ -287,12 +283,11 @@ class Validation
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return string|null
*/
protected static function filterCheckbox($value, array $params, array $field)
protected static function filterCheckbox(mixed $value, array $params, array $field)
{
$value = (string)$value;
$field_value = (string)($field['value'] ?? '1');
@@ -301,23 +296,21 @@ class Validation
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return array|array[]|false|string[]
*/
protected static function filterCommaList($value, array $params, array $field)
protected static function filterCommaList(mixed $value, array $params, array $field)
{
return is_array($value) ? $value : preg_split('/\s*,\s*/', $value, -1, PREG_SPLIT_NO_EMPTY);
return is_array($value) ? $value : preg_split('/\s*,\s*/', (string) $value, -1, PREG_SPLIT_NO_EMPTY);
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return bool
*/
public static function typeCommaList($value, array $params, array $field)
public static function typeCommaList(mixed $value, array $params, array $field)
{
if (!isset($params['max'])) {
$params['max'] = 2048;
@@ -327,34 +320,31 @@ class Validation
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return array|array[]|false|string[]
*/
protected static function filterLines($value, array $params, array $field)
protected static function filterLines(mixed $value, array $params, array $field)
{
return is_array($value) ? $value : preg_split('/\s*[\r\n]+\s*/', $value, -1, PREG_SPLIT_NO_EMPTY);
return is_array($value) ? $value : preg_split('/\s*[\r\n]+\s*/', (string) $value, -1, PREG_SPLIT_NO_EMPTY);
}
/**
* @param mixed $value
* @param array $params
* @return string
*/
protected static function filterLower($value, array $params)
protected static function filterLower(mixed $value, array $params)
{
return mb_strtolower($value);
return mb_strtolower((string) $value);
}
/**
* @param mixed $value
* @param array $params
* @return string
*/
protected static function filterUpper($value, array $params)
protected static function filterUpper(mixed $value, array $params)
{
return mb_strtoupper($value);
return mb_strtoupper((string) $value);
}
@@ -366,7 +356,7 @@ class Validation
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeTextarea($value, array $params, array $field)
public static function typeTextarea(mixed $value, array $params, array $field)
{
if (!isset($params['multiline'])) {
$params['multiline'] = true;
@@ -383,7 +373,7 @@ class Validation
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typePassword($value, array $params, array $field)
public static function typePassword(mixed $value, array $params, array $field)
{
if (!isset($params['max'])) {
$params['max'] = 256;
@@ -400,7 +390,7 @@ class Validation
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeHidden($value, array $params, array $field)
public static function typeHidden(mixed $value, array $params, array $field)
{
return self::typeText($value, $params, $field);
}
@@ -413,7 +403,7 @@ class Validation
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeCheckboxes($value, array $params, array $field)
public static function typeCheckboxes(mixed $value, array $params, array $field)
{
// Set multiple: true so checkboxes can easily use min/max counts to control number of options required
$field['multiple'] = true;
@@ -422,12 +412,11 @@ class Validation
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return array|null
*/
protected static function filterCheckboxes($value, array $params, array $field)
protected static function filterCheckboxes(mixed $value, array $params, array $field)
{
return self::filterArray($value, $params, $field);
}
@@ -440,7 +429,7 @@ class Validation
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeCheckbox($value, array $params, array $field)
public static function typeCheckbox(mixed $value, array $params, array $field)
{
$value = (string)$value;
$field_value = (string)($field['value'] ?? '1');
@@ -456,7 +445,7 @@ class Validation
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeRadio($value, array $params, array $field)
public static function typeRadio(mixed $value, array $params, array $field)
{
return self::typeArray((array) $value, $params, $field);
}
@@ -469,7 +458,7 @@ class Validation
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeToggle($value, array $params, array $field)
public static function typeToggle(mixed $value, array $params, array $field)
{
if (is_bool($value)) {
$value = (int)$value;
@@ -486,18 +475,17 @@ class Validation
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeFile($value, array $params, array $field)
public static function typeFile(mixed $value, array $params, array $field)
{
return self::typeArray((array)$value, $params, $field);
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return array
*/
protected static function filterFile($value, array $params, array $field)
protected static function filterFile(mixed $value, array $params, array $field)
{
return (array)$value;
}
@@ -510,7 +498,7 @@ class Validation
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeSelect($value, array $params, array $field)
public static function typeSelect(mixed $value, array $params, array $field)
{
return self::typeArray((array) $value, $params, $field);
}
@@ -523,7 +511,7 @@ class Validation
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeNumber($value, array $params, array $field)
public static function typeNumber(mixed $value, array $params, array $field)
{
if (!is_numeric($value)) {
return false;
@@ -558,23 +546,21 @@ class Validation
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return float|int
*/
protected static function filterNumber($value, array $params, array $field)
protected static function filterNumber(mixed $value, array $params, array $field)
{
return (string)(int)$value !== (string)(float)$value ? (float)$value : (int)$value;
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return string
*/
protected static function filterDateTime($value, array $params, array $field)
protected static function filterDateTime(mixed $value, array $params, array $field)
{
$format = Grav::instance()['config']->get('system.pages.dateformat.default');
if ($format) {
@@ -592,18 +578,17 @@ class Validation
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeRange($value, array $params, array $field)
public static function typeRange(mixed $value, array $params, array $field)
{
return self::typeNumber($value, $params, $field);
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return float|int
*/
protected static function filterRange($value, array $params, array $field)
protected static function filterRange(mixed $value, array $params, array $field)
{
return self::filterNumber($value, $params, $field);
}
@@ -616,9 +601,9 @@ class Validation
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeColor($value, array $params, array $field)
public static function typeColor(mixed $value, array $params, array $field)
{
return (bool)preg_match('/^\#[0-9a-fA-F]{3}[0-9a-fA-F]{3}?$/u', $value);
return (bool)preg_match('/^\#[0-9a-fA-F]{3}[0-9a-fA-F]{3}?$/u', (string) $value);
}
/**
@@ -629,7 +614,7 @@ class Validation
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeEmail($value, array $params, array $field)
public static function typeEmail(mixed $value, array $params, array $field)
{
if (empty($value)) {
return false;
@@ -639,10 +624,10 @@ class Validation
$params['max'] = 320;
}
$values = !is_array($value) ? explode(',', preg_replace('/\s+/', '', $value)) : $value;
$values = !is_array($value) ? explode(',', preg_replace('/\s+/', '', (string) $value)) : $value;
foreach ($values as $val) {
if (!(self::typeText($val, $params, $field) && strpos($val, '@', 1))) {
if (!(self::typeText($val, $params, $field) && strpos((string) $val, '@', 1))) {
return false;
}
}
@@ -658,7 +643,7 @@ class Validation
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeUrl($value, array $params, array $field)
public static function typeUrl(mixed $value, array $params, array $field)
{
if (!isset($params['max'])) {
$params['max'] = 2048;
@@ -675,7 +660,7 @@ class Validation
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeDatetime($value, array $params, array $field)
public static function typeDatetime(mixed $value, array $params, array $field)
{
if ($value instanceof DateTime) {
return true;
@@ -700,7 +685,7 @@ class Validation
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeDatetimeLocal($value, array $params, array $field)
public static function typeDatetimeLocal(mixed $value, array $params, array $field)
{
return self::typeDatetime($value, $params, $field);
}
@@ -713,7 +698,7 @@ class Validation
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeDate($value, array $params, array $field)
public static function typeDate(mixed $value, array $params, array $field)
{
if (!isset($params['format'])) {
$params['format'] = 'Y-m-d';
@@ -730,7 +715,7 @@ class Validation
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeTime($value, array $params, array $field)
public static function typeTime(mixed $value, array $params, array $field)
{
if (!isset($params['format'])) {
$params['format'] = 'H:i';
@@ -747,7 +732,7 @@ class Validation
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeMonth($value, array $params, array $field)
public static function typeMonth(mixed $value, array $params, array $field)
{
if (!isset($params['format'])) {
$params['format'] = 'Y-m';
@@ -764,9 +749,9 @@ class Validation
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeWeek($value, array $params, array $field)
public static function typeWeek(mixed $value, array $params, array $field)
{
if (!isset($params['format']) && !preg_match('/^\d{4}-W\d{2}$/u', $value)) {
if (!isset($params['format']) && !preg_match('/^\d{4}-W\d{2}$/u', (string) $value)) {
return false;
}
@@ -781,7 +766,7 @@ class Validation
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeArray($value, array $params, array $field)
public static function typeArray(mixed $value, array $params, array $field)
{
if (!is_array($value)) {
return false;
@@ -829,12 +814,11 @@ class Validation
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return array|null
*/
protected static function filterFlatten_array($value, $params, $field)
protected static function filterFlatten_array(mixed $value, $params, $field)
{
$value = static::filterArray($value, $params, $field);
@@ -842,12 +826,11 @@ class Validation
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return array|null
*/
protected static function filterArray($value, $params, $field)
protected static function filterArray(mixed $value, $params, $field)
{
$values = (array) $value;
$options = isset($field['options']) ? array_keys($field['options']) : [];
@@ -871,7 +854,7 @@ class Validation
$val = implode(',', $val);
$values[$key] = array_map('trim', explode(',', $val));
} else {
$values[$key] = trim($val);
$values[$key] = trim((string) $val);
}
}
}
@@ -895,16 +878,11 @@ class Validation
{
foreach ($values as $key => &$val) {
if ($params['key_type']) {
switch ($params['key_type']) {
case 'int':
$result = is_int($key);
break;
case 'string':
$result = is_string($key);
break;
default:
$result = false;
}
$result = match ($params['key_type']) {
'int' => is_int($key),
'string' => is_string($key),
default => false,
};
if (!$result) {
unset($values[$key]);
}
@@ -937,7 +915,7 @@ class Validation
$val = (string)$val;
break;
case 'trim':
$val = trim($val);
$val = trim((string) $val);
break;
}
}
@@ -952,12 +930,11 @@ class Validation
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return bool
*/
public static function typeList($value, array $params, array $field)
public static function typeList(mixed $value, array $params, array $field)
{
if (!is_array($value)) {
return false;
@@ -966,7 +943,7 @@ class Validation
if (isset($field['fields'])) {
foreach ($value as $key => $item) {
foreach ($field['fields'] as $subKey => $subField) {
$subKey = trim($subKey, '.');
$subKey = trim((string) $subKey, '.');
$subValue = $item[$subKey] ?? null;
self::validate($subValue, $subField);
}
@@ -977,22 +954,20 @@ class Validation
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return array
*/
protected static function filterList($value, array $params, array $field)
protected static function filterList(mixed $value, array $params, array $field)
{
return (array) $value;
}
/**
* @param mixed $value
* @param array $params
* @return array
*/
public static function filterYaml($value, $params)
public static function filterYaml(mixed $value, $params)
{
if (!is_string($value)) {
return $value;
@@ -1009,18 +984,17 @@ class Validation
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeIgnore($value, array $params, array $field)
public static function typeIgnore(mixed $value, array $params, array $field)
{
return true;
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return mixed
*/
public static function filterIgnore($value, array $params, array $field)
public static function filterIgnore(mixed $value, array $params, array $field)
{
return $value;
}
@@ -1033,30 +1007,27 @@ class Validation
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeUnset($value, array $params, array $field)
public static function typeUnset(mixed $value, array $params, array $field)
{
return true;
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return null
*/
public static function filterUnset($value, array $params, array $field)
public static function filterUnset(mixed $value, array $params, array $field)
{
return null;
}
// HTML5 attributes (min, max and range are handled inside the types)
/**
* @param mixed $value
* @param bool $params
* @return bool
*/
public static function validateRequired($value, $params)
public static function validateRequired(mixed $value, $params)
{
if (is_scalar($value)) {
return (bool) $params !== true || $value !== '';
@@ -1066,105 +1037,85 @@ class Validation
}
/**
* @param mixed $value
* @param string $params
* @return bool
*/
public static function validatePattern($value, $params)
public static function validatePattern(mixed $value, $params)
{
return (bool) preg_match("`^{$params}$`u", $value);
return (bool) preg_match("`^{$params}$`u", (string) $value);
}
// Internal types
/**
* @param mixed $value
* @param mixed $params
* @return bool
*/
public static function validateAlpha($value, $params)
public static function validateAlpha(mixed $value, mixed $params)
{
return ctype_alpha($value);
return ctype_alpha((string) $value);
}
/**
* @param mixed $value
* @param mixed $params
* @return bool
*/
public static function validateAlnum($value, $params)
public static function validateAlnum(mixed $value, mixed $params)
{
return ctype_alnum($value);
return ctype_alnum((string) $value);
}
/**
* @param mixed $value
* @param mixed $params
* @return bool
*/
public static function typeBool($value, $params)
public static function typeBool(mixed $value, mixed $params)
{
return is_bool($value) || $value == 1 || $value == 0;
}
/**
* @param mixed $value
* @param mixed $params
* @return bool
*/
public static function validateBool($value, $params)
public static function validateBool(mixed $value, mixed $params)
{
return is_bool($value) || $value == 1 || $value == 0;
}
/**
* @param mixed $value
* @param mixed $params
* @return bool
*/
protected static function filterBool($value, $params)
protected static function filterBool(mixed $value, mixed $params)
{
return (bool) $value;
}
/**
* @param mixed $value
* @param mixed $params
* @return bool
*/
public static function validateDigit($value, $params)
public static function validateDigit(mixed $value, mixed $params)
{
return ctype_digit($value);
return ctype_digit((string) $value);
}
/**
* @param mixed $value
* @param mixed $params
* @return bool
*/
public static function validateFloat($value, $params)
public static function validateFloat(mixed $value, mixed $params)
{
return is_float(filter_var($value, FILTER_VALIDATE_FLOAT));
}
/**
* @param mixed $value
* @param mixed $params
* @return float
*/
protected static function filterFloat($value, $params)
protected static function filterFloat(mixed $value, mixed $params)
{
return (float) $value;
}
/**
* @param mixed $value
* @param mixed $params
* @return bool
*/
public static function validateHex($value, $params)
public static function validateHex(mixed $value, mixed $params)
{
return ctype_xdigit($value);
return ctype_xdigit((string) $value);
}
/**
@@ -1175,7 +1126,7 @@ class Validation
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeInt($value, array $params, array $field)
public static function typeInt(mixed $value, array $params, array $field)
{
$params['step'] = max(1, (int)($params['step'] ?? 0));
@@ -1183,54 +1134,42 @@ class Validation
}
/**
* @param mixed $value
* @param mixed $params
* @return bool
*/
public static function validateInt($value, $params)
public static function validateInt(mixed $value, mixed $params)
{
return is_numeric($value) && (int)$value == $value;
}
/**
* @param mixed $value
* @param mixed $params
* @return int
*/
protected static function filterInt($value, $params)
protected static function filterInt(mixed $value, mixed $params)
{
return (int)$value;
}
/**
* @param mixed $value
* @param mixed $params
* @return bool
*/
public static function validateArray($value, $params)
public static function validateArray(mixed $value, mixed $params)
{
return is_array($value) || ($value instanceof ArrayAccess && $value instanceof Traversable && $value instanceof Countable);
}
/**
* @param mixed $value
* @param mixed $params
* @return array
*/
public static function filterItem_List($value, $params)
public static function filterItem_List(mixed $value, mixed $params)
{
return array_values(array_filter($value, static function ($v) {
return !empty($v);
}));
return array_values(array_filter($value, static fn($v) => !empty($v)));
}
/**
* @param mixed $value
* @param mixed $params
* @return bool
*/
public static function validateJson($value, $params)
public static function validateJson(mixed $value, mixed $params)
{
return (bool) (@json_decode($value));
return (bool) (@json_decode((string) $value));
}
}

View File

@@ -37,7 +37,7 @@ class ValidationException extends RuntimeException implements JsonSerializable
foreach ($messages as $list) {
$list = array_unique($list);
foreach ($list as $message) {
$this->message .= '<br/>' . htmlspecialchars($message, ENT_QUOTES | ENT_HTML5, 'UTF-8');
$this->message .= '<br/>' . htmlspecialchars((string) $message, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
}
@@ -49,7 +49,7 @@ class ValidationException extends RuntimeException implements JsonSerializable
$first = reset($this->messages);
$message = reset($first);
$this->message = $escape ? htmlspecialchars($message, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $message;
$this->message = $escape ? htmlspecialchars((string) $message, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $message;
}
/**

View File

@@ -328,9 +328,7 @@ class Debugger
return new Response(404, $headers, json_encode($response));
}
$data = is_array($data) ? array_map(static function ($item) {
return $item->toArray();
}, $data) : $data->toArray();
$data = is_array($data) ? array_map(static fn($item) => $item->toArray(), $data) : $data->toArray();
return new Response(200, $headers, json_encode($data));
}
@@ -619,13 +617,9 @@ class Debugger
protected function buildProfilerTimings(array $timings): array
{
// Filter method calls which take almost no time.
$timings = array_filter($timings, function ($value) {
return $value['wt'] > 50;
});
$timings = array_filter($timings, fn($value) => $value['wt'] > 50);
uasort($timings, function (array $a, array $b) {
return $b['wt'] <=> $a['wt'];
});
uasort($timings, fn(array $a, array $b) => $b['wt'] <=> $a['wt']);
$table = [];
foreach ($timings as $key => $timing) {
@@ -639,7 +633,7 @@ class Debugger
}
// Do not profile library calls.
if (strpos($context, 'Grav\\') !== 0) {
if (!str_starts_with((string) $context, 'Grav\\')) {
continue;
}
@@ -721,12 +715,11 @@ class Debugger
/**
* Dump variables into the Messages tab of the Debug Bar
*
* @param mixed $message
* @param string $label
* @param mixed|bool $isString
* @return $this
*/
public function addMessage($message, $label = 'info', $isString = true)
public function addMessage(mixed $message, $label = 'info', $isString = true)
{
if ($this->enabled) {
if ($this->censored) {
@@ -779,7 +772,7 @@ class Debugger
public function addEvent(string $name, $event, EventDispatcherInterface $dispatcher, ?float $time = null)
{
if ($this->enabled && $this->clockwork) {
$time = $time ?? microtime(true);
$time ??= microtime(true);
$duration = (microtime(true) - $time) * 1000;
$data = null;
@@ -829,7 +822,7 @@ class Debugger
public function setErrorHandler()
{
$this->errorHandler = set_error_handler(
[$this, 'deprecatedErrorHandler']
$this->deprecatedErrorHandler(...)
);
}
@@ -858,7 +851,7 @@ class Debugger
$scope = 'unknown';
if (stripos($errstr, 'grav') !== false) {
$scope = 'grav';
} elseif (strpos($errfile, '/twig/') !== false) {
} elseif (str_contains($errfile, '/twig/')) {
$scope = 'twig';
// TODO: remove when upgrading to Twig 2+
if (str_contains($errstr, '#[\ReturnTypeWillChange]') || str_contains($errstr, 'Passing null to parameter')) {
@@ -866,7 +859,7 @@ class Debugger
}
} elseif (stripos($errfile, '/yaml/') !== false) {
$scope = 'yaml';
} elseif (strpos($errfile, '/vendor/') !== false) {
} elseif (str_contains($errfile, '/vendor/')) {
$scope = 'vendor';
}
@@ -912,7 +905,7 @@ class Debugger
} elseif (is_scalar($arg)) {
$arg = $arg;
} elseif (is_object($arg)) {
$arg = get_class($arg) . ' $object';
$arg = $arg::class . ' $object';
} elseif (is_array($arg)) {
$arg = '$array';
} else {
@@ -938,7 +931,7 @@ class Debugger
if ($object instanceof Template) {
$file = $current['file'] ?? null;
if (preg_match('`(Template.php|TemplateWrapper.php)$`', $file)) {
if (preg_match('`(Template.php|TemplateWrapper.php)$`', (string) $file)) {
$current = null;
continue;
}
@@ -998,7 +991,7 @@ class Debugger
if (!isset($current['file'])) {
continue;
}
if (strpos($current['file'], '/vendor/') !== false) {
if (str_contains($current['file'], '/vendor/')) {
$cut = $i + 1;
continue;
}
@@ -1073,7 +1066,7 @@ class Debugger
/** @var array $deprecated */
foreach ($this->deprecations as $deprecated) {
list($message, $scope) = $this->getDepracatedMessage($deprecated);
[$message, $scope] = $this->getDepracatedMessage($deprecated);
$collector->addMessage($message, $scope);
}
@@ -1140,7 +1133,7 @@ class Debugger
protected function resolveCallable(callable $callable)
{
if (is_array($callable)) {
return get_class($callable[0]) . '->' . $callable[1] . '()';
return $callable[0]::class . '->' . $callable[1] . '()';
}
return 'unknown';

View File

@@ -54,11 +54,7 @@ class SimplePageHandler extends Handler
$code = Misc::translateErrorCode($code);
}
$vars = array(
'stylesheet' => file_get_contents($cssFile),
'code' => $code,
'message' => htmlspecialchars(strip_tags(rawurldecode($message)), ENT_QUOTES, 'UTF-8'),
);
$vars = ['stylesheet' => file_get_contents($cssFile), 'code' => $code, 'message' => htmlspecialchars(strip_tags(rawurldecode($message)), ENT_QUOTES, 'UTF-8')];
$helper->setVariables($vars);
$helper->render($templateFile);

View File

@@ -28,10 +28,9 @@ trait CompiledFile
/**
* Get/set parsed file contents.
*
* @param mixed $var
* @return array
*/
public function content($var = null)
public function content(mixed $var = null)
{
try {
$filename = $this->filename;
@@ -44,12 +43,12 @@ trait CompiledFile
if (!$modified) {
try {
return $this->decode($this->raw());
} catch (Throwable $e) {
} catch (Throwable) {
// If the compiled file is broken, we can safely ignore the error and continue.
}
}
$class = get_class($this);
$class = $this::class;
$size = filesize($filename);
$cache = $file->exists() ? $file->content() : null;
@@ -115,7 +114,7 @@ trait CompiledFile
* @return void
* @throws RuntimeException
*/
public function save($data = null)
public function save(mixed $data = null)
{
// Make sure that the cache file is always up to date!
$key = md5($this->filename);
@@ -135,7 +134,7 @@ trait CompiledFile
if ($locked) {
$modified = $this->modified();
$filename = $this->filename;
$class = get_class($this);
$class = $this::class;
$size = filesize($filename);
// windows doesn't play nicely with this as it can't read when locked

View File

@@ -153,8 +153,8 @@ abstract class Folder
if ($base) {
$base = preg_replace('![\\\/]+!', '/', $base);
$path = preg_replace('![\\\/]+!', '/', $path);
if (strpos($path, $base) === 0) {
$path = ltrim(substr($path, strlen($base)), '/');
if (str_starts_with((string) $path, (string) $base)) {
$path = ltrim(substr((string) $path, strlen((string) $base)), '/');
}
}
@@ -178,8 +178,8 @@ abstract class Folder
return '';
}
$baseParts = explode('/', ltrim($base, '/'));
$pathParts = explode('/', ltrim($path, '/'));
$baseParts = explode('/', ltrim((string) $base, '/'));
$pathParts = explode('/', ltrim((string) $path, '/'));
array_pop($baseParts);
$lastPart = array_pop($pathParts);
@@ -194,7 +194,7 @@ abstract class Folder
$path = str_repeat('../', count($baseParts)) . implode('/', $pathParts);
return '' === $path
|| strpos($path, '/') === 0
|| str_starts_with($path, '/')
|| false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos)
? "./$path" : $path;
}
@@ -266,7 +266,7 @@ abstract class Folder
/** @var RecursiveDirectoryIterator $file */
foreach ($iterator as $file) {
// Ignore hidden files.
if (strpos($file->getFilename(), '.') === 0 && $file->isFile()) {
if (str_starts_with($file->getFilename(), '.') && $file->isFile()) {
continue;
}
if (!$folders && $file->isDir()) {
@@ -275,7 +275,7 @@ abstract class Folder
if (!$files && $file->isFile()) {
continue;
}
if ($compare && $pattern && !preg_match($pattern, $file->{$compare}())) {
if ($compare && $pattern && !preg_match($pattern, (string) $file->{$compare}())) {
continue;
}
$fileKey = $key ? $file->{$key}() : null;
@@ -283,14 +283,14 @@ abstract class Folder
if ($filters) {
if (isset($filters['key'])) {
$pre = !empty($filters['pre-key']) ? $filters['pre-key'] : '';
$fileKey = $pre . preg_replace($filters['key'], '', $fileKey);
$fileKey = $pre . preg_replace($filters['key'], '', (string) $fileKey);
}
if (isset($filters['value'])) {
$filter = $filters['value'];
if (is_callable($filter)) {
$filePath = $filter($file);
} else {
$filePath = preg_replace($filter, '', $filePath);
$filePath = preg_replace($filter, '', (string) $filePath);
}
}
}
@@ -331,7 +331,7 @@ abstract class Folder
// Go through all sub-directories and copy everything.
$files = self::all($source);
foreach ($files as $file) {
if ($ignore && preg_match($ignore, $file)) {
if ($ignore && preg_match($ignore, (string) $file)) {
continue;
}
$src = $source .'/'. $file;
@@ -377,7 +377,7 @@ abstract class Folder
return;
}
if (strpos($target, $source . '/') === 0) {
if (str_starts_with($target, $source . '/')) {
throw new RuntimeException('Cannot move folder to itself');
}

View File

@@ -77,7 +77,7 @@ class ZipArchiver extends Archiver
foreach ($files as $file) {
$filePath = $file->getPathname();
$relativePath = ltrim(substr($filePath, strlen($rootPath)), '/');
$relativePath = ltrim(substr((string) $filePath, strlen($rootPath)), '/');
if ($file->isDir()) {
$zip->addEmptyDir($relativePath);

View File

@@ -35,7 +35,7 @@ trait FlexCollectionTrait
'collection' => $this
]);
}
if (strpos($name, 'onFlexCollection') !== 0 && strpos($name, 'on') === 0) {
if (!str_starts_with($name, 'onFlexCollection') && str_starts_with($name, 'on')) {
$name = 'onFlexCollection' . substr($name, 2);
}

View File

@@ -46,7 +46,7 @@ trait FlexObjectTrait
if (isset($events['name'])) {
$name = $events['name'];
} elseif (strpos($name, 'onFlexObject') !== 0 && strpos($name, 'on') === 0) {
} elseif (!str_starts_with($name, 'onFlexObject') && str_starts_with($name, 'on')) {
$name = 'onFlexObject' . substr($name, 2);
}

View File

@@ -172,7 +172,7 @@ class PageCollection extends FlexPageCollection implements PageCollectionInterfa
* @return static
* @phpstan-return static<T>
*/
public function merge(PageCollectionInterface $collection)
public function merge(PageCollectionInterface $collection): never
{
throw new RuntimeException(__METHOD__ . '(): Not Implemented');
}
@@ -184,7 +184,7 @@ class PageCollection extends FlexPageCollection implements PageCollectionInterfa
* @return static
* @phpstan-return static<T>
*/
public function intersect(PageCollectionInterface $collection)
public function intersect(PageCollectionInterface $collection): never
{
throw new RuntimeException(__METHOD__ . '(): Not Implemented');
}
@@ -242,7 +242,7 @@ class PageCollection extends FlexPageCollection implements PageCollectionInterfa
* @return static
* @phpstan-return static<T>
*/
public function append($items)
public function append($items): never
{
throw new RuntimeException(__METHOD__ . '(): Not Implemented');
}
@@ -303,7 +303,7 @@ class PageCollection extends FlexPageCollection implements PageCollectionInterfa
// do this header query work only once
$header_query = null;
$header_default = null;
if (strpos($order_by, 'header.') === 0) {
if (str_starts_with($order_by, 'header.')) {
$query = explode('|', str_replace('header.', '', $order_by), 2);
$header_query = array_shift($query) ?? '';
$header_default = array_shift($query);
@@ -373,9 +373,7 @@ class PageCollection extends FlexPageCollection implements PageCollectionInterfa
if ($col) {
$col->setAttribute(Collator::NUMERIC_COLLATION, Collator::ON);
if (($sort_flags & SORT_NATURAL) === SORT_NATURAL) {
$list = preg_replace_callback('~([0-9]+)\.~', static function ($number) {
return sprintf('%032d.', $number[0]);
}, $list);
$list = preg_replace_callback('~([0-9]+)\.~', static fn($number) => sprintf('%032d.', $number[0]), $list);
if (!is_array($list)) {
throw new RuntimeException('Internal Error');
}
@@ -457,7 +455,7 @@ class PageCollection extends FlexPageCollection implements PageCollectionInterfa
continue;
}
$date = $field ? strtotime($object->getNestedProperty($field)) : $object->date();
$date = $field ? strtotime((string) $object->getNestedProperty($field)) : $object->date();
if ((!$start || $date >= $start) && (!$end || $date <= $end)) {
$entries[$key] = $object;

View File

@@ -239,10 +239,9 @@ class PageIndex extends FlexPageIndex implements PageCollectionInterface
* Set a parameter to the Collection
*
* @param string $name
* @param mixed $value
* @return $this
*/
public function setParam(string $name, $value)
public function setParam(string $name, mixed $value)
{
$this->_params[$name] = $value;
@@ -495,7 +494,7 @@ class PageIndex extends FlexPageIndex implements PageCollectionInterface
*/
protected function getFallbackLanguages(?string $languageCode = null, ?bool $fallback = null): array
{
$fallback = $fallback ?? true;
$fallback ??= true;
if (!$fallback && null !== $languageCode) {
return [$languageCode];
}
@@ -504,7 +503,7 @@ class PageIndex extends FlexPageIndex implements PageCollectionInterface
/** @var Language $language */
$language = $grav['language'];
$languageCode = $languageCode ?? '';
$languageCode ??= '';
if ($languageCode === '' && $fallback) {
return $language->getFallbackLanguages(null, true);
}
@@ -533,7 +532,7 @@ class PageIndex extends FlexPageIndex implements PageCollectionInterface
// Handle leaf_route
$leaf = null;
if ($leaf_route && $route !== $leaf_route) {
$nodes = explode('/', $leaf_route);
$nodes = explode('/', (string) $leaf_route);
$sub_route = '/' . implode('/', array_slice($nodes, 1, $options['level']++));
$options['route'] = $sub_route;
@@ -544,7 +543,7 @@ class PageIndex extends FlexPageIndex implements PageCollectionInterface
if (!$route) {
$page = $this->getRoot();
} else {
$page = $this->get(trim($route, '/'));
$page = $this->get(trim((string) $route, '/'));
}
$path = $page ? $page->path() : null;
@@ -558,7 +557,7 @@ class PageIndex extends FlexPageIndex implements PageCollectionInterface
// Clean up filter.
$filter_type = (array)($filters['type'] ?? []);
unset($filters['type']);
$filters = array_filter($filters, static function($val) { return $val !== null && $val !== ''; });
$filters = array_filter($filters, static fn($val) => $val !== null && $val !== '');
if ($page) {
$status = 'success';
@@ -682,9 +681,7 @@ class PageIndex extends FlexPageIndex implements PageCollectionInterface
'tags' => $tags,
'actions' => $this->getListingActions($child, $user),
];
$extras = array_filter($extras, static function ($v) {
return $v !== null;
});
$extras = array_filter($extras, static fn($v) => $v !== null);
/** @var PageIndex $tmp */
$tmp = $child->children()->getIndex();
@@ -698,7 +695,7 @@ class PageIndex extends FlexPageIndex implements PageCollectionInterface
'title' => htmlspecialchars($child->menu()),
'route' => [
'display' => htmlspecialchars($route) ?: null,
'raw' => htmlspecialchars($child->rawRoute()),
'raw' => htmlspecialchars((string) $child->rawRoute()),
],
'modified' => $this->jsDate($child->modified()),
'child_count' => $child_count ?: null,
@@ -706,9 +703,7 @@ class PageIndex extends FlexPageIndex implements PageCollectionInterface
'filters_hit' => $filters ? ($child->filterBy($filters, false) ?: null) : null,
'extras' => $extras
];
$payload = array_filter($payload, static function ($v) {
return $v !== null;
});
$payload = array_filter($payload, static fn($v) => $v !== null);
}
// Add children if any

View File

@@ -521,7 +521,7 @@ class PageObject extends FlexPageObject
$template = $this->getProperty('template') . ($name ? '.' . $name : '');
$blueprint = $this->getFlexDirectory()->getBlueprint($template, 'blueprints://pages');
} catch (RuntimeException $e) {
} catch (RuntimeException) {
$template = 'default' . ($name ? '.' . $name : '');
$blueprint = $this->getFlexDirectory()->getBlueprint($template, 'blueprints://pages');
@@ -554,7 +554,7 @@ class PageObject extends FlexPageObject
$initial = $options['initial'] ?? null;
$var = $initial ? 'leaf_route' : 'route';
$route = $options[$var] ?? '';
if ($route !== '' && !str_starts_with($route, '/')) {
if ($route !== '' && !str_starts_with((string) $route, '/')) {
$filesystem = Filesystem::getInstance();
$route = "/{$this->getKey()}/{$route}";
@@ -600,7 +600,7 @@ class PageObject extends FlexPageObject
$matches = $test->search((string)$value) > 0.0;
break;
case 'page_type':
$types = $value ? explode(',', $value) : [];
$types = $value ? explode(',', (string) $value) : [];
$matches = in_array($test->template(), $types, true);
break;
case 'extension':
@@ -698,7 +698,7 @@ class PageObject extends FlexPageObject
} elseif (array_key_exists('ordering', $elements) && array_key_exists('order', $elements)) {
// Store ordering.
$ordering = $elements['order'] ?? null;
$this->_reorder = !empty($ordering) ? explode(',', $ordering) : [];
$this->_reorder = !empty($ordering) ? explode(',', (string) $ordering) : [];
$order = false;
if ((bool)($elements['ordering'] ?? false)) {

View File

@@ -394,14 +394,14 @@ class PageStorage extends FolderStorage
if ($oldFolder !== $newFolder && file_exists($oldFolder)) {
$isCopy = $row['__META']['copy'] ?? false;
if ($isCopy) {
if (strpos($newFolder, $oldFolder . '/') === 0) {
if (str_starts_with($newFolder, $oldFolder . '/')) {
throw new RuntimeException(sprintf('Page /%s cannot be copied to itself', $oldKey));
}
$this->copyRow($oldKey, $newKey);
$debugger->addMessage("Page copied: {$oldFolder} => {$newFolder}", 'debug');
} else {
if (strpos($newFolder, $oldFolder . '/') === 0) {
if (str_starts_with($newFolder, $oldFolder . '/')) {
throw new RuntimeException(sprintf('Page /%s cannot be moved to itself', $oldKey));
}
@@ -538,7 +538,7 @@ class PageStorage extends FolderStorage
if ($reload || !isset($this->meta[$key])) {
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
if (mb_strpos($key, '@@') === false) {
if (mb_strpos((string) $key, '@@') === false) {
$path = $this->getStoragePath($key);
if (is_string($path)) {
$path = $locator->isStream($path) ? $locator->findResource($path) : GRAV_ROOT . "/{$path}";

View File

@@ -92,9 +92,7 @@ trait PageTranslateTrait
$list[$languageCode ?: $defaultCode] = $route ?? '';
}
$list = array_filter($list, static function ($var) {
return null !== $var;
});
$list = array_filter($list, static fn($var) => null !== $var);
// Hack to get the same result as with old pages.
foreach ($list as &$path) {

View File

@@ -100,10 +100,9 @@ class UserGroupObject extends FlexObject implements UserGroupInterface
}
/**
* @param mixed $value
* @return array
*/
protected function offsetLoad_access($value): array
protected function offsetLoad_access(mixed $value): array
{
if (!$value instanceof Access) {
$value = new Access($value);
@@ -115,10 +114,9 @@ class UserGroupObject extends FlexObject implements UserGroupInterface
}
/**
* @param mixed $value
* @return array
*/
protected function offsetPrepare_access($value): array
protected function offsetPrepare_access(mixed $value): array
{
return $this->offsetLoad_access($value);
}

View File

@@ -30,7 +30,7 @@ trait UserObjectLegacyTrait
*/
public function merge(array $data)
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use ->update($data) method instead', E_USER_DEPRECATED);
user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use ->update($data) method instead', E_USER_DEPRECATED);
$this->setElements($this->getBlueprint()->mergeData($this->toArray(), $data));
@@ -45,7 +45,7 @@ trait UserObjectLegacyTrait
*/
public function getAvatarMedia()
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use ->getAvatarImage() method instead', E_USER_DEPRECATED);
user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use ->getAvatarImage() method instead', E_USER_DEPRECATED);
return $this->getAvatarImage();
}
@@ -58,7 +58,7 @@ trait UserObjectLegacyTrait
*/
public function avatarUrl()
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use ->getAvatarUrl() method instead', E_USER_DEPRECATED);
user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use ->getAvatarUrl() method instead', E_USER_DEPRECATED);
return $this->getAvatarUrl();
}
@@ -73,7 +73,7 @@ trait UserObjectLegacyTrait
*/
public function authorise($action)
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use ->authorize() method instead', E_USER_DEPRECATED);
user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use ->authorize() method instead', E_USER_DEPRECATED);
return $this->authorize($action) ?? false;
}
@@ -87,7 +87,7 @@ trait UserObjectLegacyTrait
#[\ReturnTypeWillChange]
public function count()
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6', E_USER_DEPRECATED);
user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6', E_USER_DEPRECATED);
return count($this->jsonSerialize());
}

View File

@@ -67,7 +67,7 @@ class UserIndex extends FlexIndex implements UserCollectionInterface
// Username can also be number and stored as such.
$key = (string)($data['username'] ?? $meta['key'] ?? $meta['storage_key']);
$meta['key'] = static::filterUsername($key, $storage);
$meta['email'] = isset($data['email']) ? mb_strtolower($data['email']) : null;
$meta['email'] = isset($data['email']) ? mb_strtolower((string) $data['email']) : null;
}
/**

View File

@@ -286,7 +286,7 @@ class UserObject extends FlexObject implements UserInterface, Countable
return false;
}
if (strpos($action, 'login') === false && !$this->getProperty('authorized')) {
if (!str_contains($action, 'login') && !$this->getProperty('authorized')) {
// User needs to be authorized (2FA).
return false;
}
@@ -401,7 +401,7 @@ class UserObject extends FlexObject implements UserInterface, Countable
*/
public function join($name, $value, $separator = null)
{
$separator = $separator ?? '.';
$separator ??= '.';
$old = $this->get($name, null, $separator);
if ($old !== null) {
if (!is_array($old)) {
@@ -1027,10 +1027,9 @@ class UserObject extends FlexObject implements UserInterface, Countable
}
/**
* @param mixed $value
* @return array
*/
protected function offsetLoad_access($value): array
protected function offsetLoad_access(mixed $value): array
{
if (!$value instanceof Access) {
$value = new Access($value);
@@ -1040,10 +1039,9 @@ class UserObject extends FlexObject implements UserInterface, Countable
}
/**
* @param mixed $value
* @return array
*/
protected function offsetPrepare_access($value): array
protected function offsetPrepare_access(mixed $value): array
{
return $this->offsetLoad_access($value);
}

View File

@@ -14,7 +14,7 @@ use Grav\Common\Data\Data;
/**
* @property string $name
*/
class Package
class Package implements \Stringable
{
/** @var Data */
protected $data;
@@ -53,11 +53,10 @@ class Package
/**
* @param string $key
* @param mixed $value
* @return void
*/
#[\ReturnTypeWillChange]
public function __set($key, $value)
public function __set($key, mixed $value)
{
$this->data->set($key, $value);
}
@@ -76,7 +75,7 @@ class Package
* @return string
*/
#[\ReturnTypeWillChange]
public function __toString()
public function __toString(): string
{
return $this->toJson();
}

View File

@@ -37,8 +37,6 @@ class GPM extends Iterator
private $repository;
/** @var Remote\GravCore|null Remove Grav Packages */
private $grav;
/** @var bool */
private $refresh;
/** @var callable|null */
private $callback;
@@ -57,7 +55,7 @@ class GPM extends Iterator
* @param bool $refresh Applies to Remote Packages only and forces a refetch of data
* @param callable|null $callback Either a function or callback in array notation
*/
public function __construct($refresh = false, $callback = null)
public function __construct(private $refresh = false, $callback = null)
{
parent::__construct();
@@ -65,7 +63,6 @@ class GPM extends Iterator
$this->cache = [];
$this->installed = new Local\Packages();
$this->refresh = $refresh;
$this->callback = $callback;
}
@@ -78,12 +75,10 @@ class GPM extends Iterator
#[\ReturnTypeWillChange]
public function __get($offset)
{
switch ($offset) {
case 'grav':
return $this->getGrav();
}
return parent::__get($offset);
return match ($offset) {
'grav' => $this->getGrav(),
default => parent::__get($offset),
};
}
/**
@@ -95,12 +90,10 @@ class GPM extends Iterator
#[\ReturnTypeWillChange]
public function __isset($offset)
{
switch ($offset) {
case 'grav':
return $this->getGrav() !== null;
}
return parent::__isset($offset);
return match ($offset) {
'grav' => $this->getGrav() !== null,
default => parent::__isset($offset),
};
}
/**
@@ -550,7 +543,7 @@ class GPM extends Iterator
if (null === $this->repository) {
try {
$this->repository = new Remote\Packages($this->refresh, $this->callback);
} catch (Exception $e) {}
} catch (Exception) {}
}
return $this->repository;
@@ -566,7 +559,7 @@ class GPM extends Iterator
if (null === $this->grav) {
try {
$this->grav = new Remote\GravCore($this->refresh, $this->callback);
} catch (Exception $e) {}
} catch (Exception) {}
}
return $this->grav;
@@ -1220,7 +1213,7 @@ class GPM extends Iterator
*/
public function versionFormatIsNextSignificantRelease($version): bool
{
return strpos($version, '~') === 0;
return str_starts_with($version, '~');
}
/**
@@ -1233,7 +1226,7 @@ class GPM extends Iterator
*/
public function versionFormatIsEqualOrHigher($version): bool
{
return strpos($version, '>=') === 0;
return str_starts_with($version, '>=');
}
/**

View File

@@ -81,7 +81,7 @@ class Installer
{
$destination = rtrim($destination, DS);
$options = array_merge(self::$options, $options);
$install_path = rtrim($destination . DS . ltrim($options['install_path'], DS), DS);
$install_path = rtrim($destination . DS . ltrim((string) $options['install_path'], DS), DS);
if (!self::isGravInstance($destination) || !self::isValidDestination(
$install_path,

View File

@@ -37,7 +37,7 @@ class Package extends BasePackage
$html_description = Parsedown::instance()->line($this->__get('description'));
$this->data->set('slug', $package->__get('slug'));
$this->data->set('description_html', $html_description);
$this->data->set('description_plain', strip_tags($html_description));
$this->data->set('description_plain', strip_tags((string) $html_description));
$this->data->set('symlink', is_link(USER_DIR . $package_type . DS . $this->__get('slug')));
}

View File

@@ -53,10 +53,10 @@ class AbstractPackageCollection extends BaseCollection
$this->raw = $this->cache->fetch(md5($this->repository));
$this->fetch($refresh, $callback);
foreach (json_decode($this->raw, true) as $slug => $data) {
foreach (json_decode((string) $this->raw, true) as $slug => $data) {
// Temporarily fix for using multi-sites
if (isset($data['install_path'])) {
$path = preg_replace('~^user/~i', 'user://', $data['install_path']);
$path = preg_replace('~^user/~i', 'user://', (string) $data['install_path']);
$data['install_path'] = Grav::instance()['locator']->findResource($path, false, true);
}
$this->items[$slug] = new Package($data, $this->type);

View File

@@ -46,7 +46,7 @@ class GravCore extends AbstractPackageCollection
$this->fetch($refresh, $callback);
$this->data = json_decode($this->raw, true);
$this->data = json_decode((string) $this->raw, true);
$this->version = $this->data['version'] ?? '-';
$this->date = $this->data['date'] ?? '-';
$this->min_php = $this->data['min_php'] ?? null;

View File

@@ -29,7 +29,7 @@ abstract class Getters implements ArrayAccess, Countable
* @param mixed $value Medium value
*/
#[\ReturnTypeWillChange]
public function __set($offset, $value)
public function __set($offset, mixed $value)
{
$this->offsetSet($offset, $value);
}
@@ -103,10 +103,9 @@ abstract class Getters implements ArrayAccess, Countable
/**
* @param int|string $offset
* @param mixed $value
*/
#[\ReturnTypeWillChange]
public function offsetSet($offset, $value)
public function offsetSet($offset, mixed $value)
{
if ($this->gettersVariable) {
$var = $this->gettersVariable;

View File

@@ -261,51 +261,23 @@ class Grav extends Container
$container = new Container(
[
'multipartRequestSupport' => function () {
return new MultipartRequestSupport();
},
'initializeProcessor' => function () {
return new InitializeProcessor($this);
},
'backupsProcessor' => function () {
return new BackupsProcessor($this);
},
'pluginsProcessor' => function () {
return new PluginsProcessor($this);
},
'themesProcessor' => function () {
return new ThemesProcessor($this);
},
'schedulerProcessor' => function () {
return new SchedulerProcessor($this);
},
'requestProcessor' => function () {
return new RequestProcessor($this);
},
'tasksProcessor' => function () {
return new TasksProcessor($this);
},
'assetsProcessor' => function () {
return new AssetsProcessor($this);
},
'twigProcessor' => function () {
return new TwigProcessor($this);
},
'pagesProcessor' => function () {
return new PagesProcessor($this);
},
'debuggerAssetsProcessor' => function () {
return new DebuggerAssetsProcessor($this);
},
'renderProcessor' => function () {
return new RenderProcessor($this);
},
'multipartRequestSupport' => fn() => new MultipartRequestSupport(),
'initializeProcessor' => fn() => new InitializeProcessor($this),
'backupsProcessor' => fn() => new BackupsProcessor($this),
'pluginsProcessor' => fn() => new PluginsProcessor($this),
'themesProcessor' => fn() => new ThemesProcessor($this),
'schedulerProcessor' => fn() => new SchedulerProcessor($this),
'requestProcessor' => fn() => new RequestProcessor($this),
'tasksProcessor' => fn() => new TasksProcessor($this),
'assetsProcessor' => fn() => new AssetsProcessor($this),
'twigProcessor' => fn() => new TwigProcessor($this),
'pagesProcessor' => fn() => new PagesProcessor($this),
'debuggerAssetsProcessor' => fn() => new DebuggerAssetsProcessor($this),
'renderProcessor' => fn() => new RenderProcessor($this),
]
);
$default = static function () {
return new Response(404, ['Expires' => 0, 'Cache-Control' => 'no-store, max-age=0'], 'Not Found');
};
$default = static fn() => new Response(404, ['Expires' => 0, 'Cache-Control' => 'no-store, max-age=0'], 'Not Found');
$collection = new RequestHandler($this->middleware, $default, $container);
@@ -326,7 +298,7 @@ class Grav extends Container
$etag = md5($body);
$response = $response->withHeader('ETag', '"' . $etag . '"');
$search = trim($this['request']->getHeaderLine('If-None-Match'), '"');
$search = trim((string) $this['request']->getHeaderLine('If-None-Match'), '"');
if ($noCache === false && $search === $etag) {
$response = $response->withStatus(304);
$body = '';
@@ -403,7 +375,7 @@ class Grav extends Container
$etag = md5($body);
$response = $response->withHeader('ETag', '"' . $etag . '"');
$search = trim($this['request']->getHeaderLine('If-None-Match'), '"');
$search = trim((string) $this['request']->getHeaderLine('If-None-Match'), '"');
if ($noCache === false && $search === $etag) {
$response = $response->withStatus(304);
$body = '';
@@ -461,7 +433,7 @@ class Grav extends Container
if (null === $code) {
// Check for redirect code in the route: e.g. /new/[301], /new[301]/route or /new[301].html
$regex = '/.*(\[(30[1-7])\])(.\w+|\/.*?)?$/';
preg_match($regex, $route, $matches);
preg_match($regex, (string) $route, $matches);
if ($matches) {
$route = str_replace($matches[1], '', $matches[0]);
$code = $matches[2];
@@ -474,9 +446,9 @@ class Grav extends Container
$url = rtrim($uri->rootUrl(), '/') . '/';
if ($this['config']->get('system.pages.redirect_trailing_slash', true)) {
$url .= trim($route, '/'); // Remove trailing slash
$url .= trim((string) $route, '/'); // Remove trailing slash
} else {
$url .= ltrim($route, '/'); // Support trailing slash default routes
$url .= ltrim((string) $route, '/'); // Support trailing slash default routes
}
}
} elseif ($route instanceof Route) {
@@ -533,7 +505,7 @@ class Grav extends Container
header("HTTP/{$response->getProtocolVersion()} {$response->getStatusCode()} {$response->getReasonPhrase()}");
foreach ($response->getHeaders() as $key => $values) {
// Skip internal Grav headers.
if (strpos($key, 'Grav-Internal-') === 0) {
if (str_starts_with($key, 'Grav-Internal-')) {
continue;
}
foreach ($values as $i => $value) {
@@ -552,7 +524,7 @@ class Grav extends Container
// Initialize Locale if set and configured.
if ($this['language']->enabled() && $this['config']->get('system.languages.override_locale')) {
$language = $this['language']->getLanguage();
setlocale(LC_ALL, strlen($language) < 3 ? ($language . '_' . strtoupper($language)) : $language);
setlocale(LC_ALL, strlen((string) $language) < 3 ? ($language . '_' . strtoupper((string) $language)) : $language);
} elseif ($this['config']->get('system.default_locale')) {
setlocale(LC_ALL, $this['config']->get('system.default_locale'));
}
@@ -566,7 +538,7 @@ class Grav extends Container
{
/** @var EventDispatcherInterface $events */
$events = $this['events'];
$eventName = get_class($event);
$eventName = $event::class;
$timestamp = microtime(true);
$event = $events->dispatch($event);
@@ -734,9 +706,7 @@ class Grav extends Container
if (is_int($serviceKey)) {
$this->register(new $serviceClass);
} else {
$this[$serviceKey] = function ($c) use ($serviceClass) {
return new $serviceClass($c);
};
$this[$serviceKey] = fn($c) => new $serviceClass($c);
}
}
}
@@ -799,7 +769,7 @@ class Grav extends Container
$medium = $media[$media_file];
foreach ($uri->query(null, true) as $action => $params) {
if (in_array($action, ImageMedium::$magic_actions, true)) {
call_user_func_array([&$medium, $action], explode(',', $params));
call_user_func_array([&$medium, $action], explode(',', (string) $params));
}
}
Utils::download($medium->path(), false);
@@ -816,7 +786,7 @@ class Grav extends Container
if ($extension) {
$download = true;
if (in_array(ltrim($extension, '.'), $config->get('system.media.unsupported_inline_types', []), true)) {
if (in_array(ltrim((string) $extension, '.'), $config->get('system.media.unsupported_inline_types', []), true)) {
$download = false;
}
Utils::download($page->path() . DIRECTORY_SEPARATOR . $uri->basename(), $download);

View File

@@ -33,7 +33,7 @@ class Client
// Use callback if provided
if ($callback) {
self::$callback = $callback;
$options->setOnProgress([Client::class, 'progress']);
$options->setOnProgress(Client::progress(...));
}
$settings = array_merge($options->toArray(), $overrides);
@@ -43,17 +43,11 @@ class Client
$preferred_method = $config->get('system.gpm.method', 'auto');
}
switch ($preferred_method) {
case 'curl':
$client = new CurlHttpClient($settings, $connections);
break;
case 'fopen':
case 'native':
$client = new NativeHttpClient($settings, $connections);
break;
default:
$client = HttpClient::create($settings, $connections);
}
$client = match ($preferred_method) {
'curl' => new CurlHttpClient($settings, $connections),
'fopen', 'native' => new NativeHttpClient($settings, $connections),
default => HttpClient::create($settings, $connections),
};
return $client;
}

View File

@@ -73,7 +73,7 @@ class Response
if (Utils::functionExists('set_time_limit')) {
@set_time_limit(0);
}
} catch (Exception $e) {}
} catch (Exception) {}
$client = Client::getClient($overrides, 6, $callback);

View File

@@ -62,7 +62,7 @@ class Truncator
$curNode->nodeValue = substr(
$curNode->nodeValue,
0,
$words[$offset][1] + strlen($words[$offset][0])
$words[$offset][1] + strlen((string) $words[$offset][0])
);
self::removeProceedingNodes($curNode, $container);
@@ -216,7 +216,7 @@ class Truncator
*/
private static function insertEllipsis($domNode, $ellipsis)
{
$avoid = array('a', 'strong', 'em', 'h1', 'h2', 'h3', 'h4', 'h5'); //html tags to avoid appending the ellipsis to
$avoid = ['a', 'strong', 'em', 'h1', 'h2', 'h3', 'h4', 'h5']; //html tags to avoid appending the ellipsis to
if ($domNode->parentNode->parentNode !== null && in_array($domNode->parentNode->nodeName, $avoid, true)) {
// Append as text node to parent instead
@@ -252,7 +252,7 @@ class Truncator
) {
if ($considerHtml) {
// if the plain text is shorter than the maximum length, return the whole text
if (strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
if (strlen((string) preg_replace('/<.*?>/', '', $text)) <= $length) {
return $text;
}
@@ -284,7 +284,7 @@ class Truncator
$truncate .= $line_matchings[1];
}
// calculate the length of the plain text part of the line; handle entities as one character
$content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
$content_length = strlen((string) preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
if ($total_length+$content_length> $length) {
// the number of characters which are left
$left = $length - $total_length;

View File

@@ -72,7 +72,7 @@ class Inflector
if (is_array(static::$uncountable)) {
foreach (static::$uncountable as $_uncountable) {
if (substr($lowercased_word, -1 * strlen($_uncountable)) === $_uncountable) {
if (substr($lowercased_word, -1 * strlen((string) $_uncountable)) === $_uncountable) {
return $word;
}
}
@@ -81,7 +81,7 @@ class Inflector
if (is_array(static::$irregular)) {
foreach (static::$irregular as $_plural => $_singular) {
if (preg_match('/(' . $_plural . ')$/i', $word, $arr)) {
return preg_replace('/(' . $_plural . ')$/i', substr($arr[0], 0, 1) . substr($_singular, 1), $word);
return preg_replace('/(' . $_plural . ')$/i', substr($arr[0], 0, 1) . substr((string) $_singular, 1), $word);
}
}
}
@@ -89,7 +89,7 @@ class Inflector
if (is_array(static::$plural)) {
foreach (static::$plural as $rule => $replacement) {
if (preg_match($rule, $word)) {
return preg_replace($rule, $replacement, $word);
return preg_replace($rule, (string) $replacement, $word);
}
}
}
@@ -117,7 +117,7 @@ class Inflector
if (is_array(static::$uncountable)) {
foreach (static::$uncountable as $_uncountable) {
if (substr($lowercased_word, -1 * strlen($_uncountable)) === $_uncountable) {
if (substr($lowercased_word, -1 * strlen((string) $_uncountable)) === $_uncountable) {
return $word;
}
}
@@ -134,7 +134,7 @@ class Inflector
if (is_array(static::$singular)) {
foreach (static::$singular as $rule => $replacement) {
if (preg_match($rule, $word)) {
return preg_replace($rule, $replacement, $word);
return preg_replace($rule, (string) $replacement, $word);
}
}
}
@@ -186,7 +186,7 @@ class Inflector
*/
public static function camelize($word)
{
return str_replace(' ', '', ucwords(preg_replace('/[^\p{L}^0-9]+/', ' ', $word)));
return str_replace(' ', '', ucwords((string) preg_replace('/[^\p{L}^0-9]+/', ' ', $word)));
}
/**
@@ -203,10 +203,10 @@ class Inflector
public static function underscorize($word)
{
$regex1 = preg_replace('/([A-Z]+)([A-Z][a-z])/', '\1_\2', $word);
$regex2 = preg_replace('/([a-zd])([A-Z])/', '\1_\2', $regex1);
$regex3 = preg_replace('/[^\p{L}^0-9]+/u', '_', $regex2);
$regex2 = preg_replace('/([a-zd])([A-Z])/', '\1_\2', (string) $regex1);
$regex3 = preg_replace('/[^\p{L}^0-9]+/u', '_', (string) $regex2);
return strtolower($regex3);
return strtolower((string) $regex3);
}
/**
@@ -223,11 +223,11 @@ class Inflector
public static function hyphenize($word)
{
$regex1 = preg_replace('/([A-Z]+)([A-Z][a-z])/', '\1-\2', $word);
$regex2 = preg_replace('/([a-z])([A-Z])/', '\1-\2', $regex1);
$regex3 = preg_replace('/([0-9])([A-Z])/', '\1-\2', $regex2);
$regex4 = preg_replace('/[^\p{L}^0-9]+/', '-', $regex3);
$regex2 = preg_replace('/([a-z])([A-Z])/', '\1-\2', (string) $regex1);
$regex3 = preg_replace('/([0-9])([A-Z])/', '\1-\2', (string) $regex2);
$regex4 = preg_replace('/[^\p{L}^0-9]+/', '-', (string) $regex3);
$regex4 = trim($regex4, '-');
$regex4 = trim((string) $regex4, '-');
return strtolower($regex4);
}
@@ -326,16 +326,12 @@ class Inflector
return $number . static::$ordinals['default'];
}
switch ($number % 10) {
case 1:
return $number . static::$ordinals['first'];
case 2:
return $number . static::$ordinals['second'];
case 3:
return $number . static::$ordinals['third'];
default:
return $number . static::$ordinals['default'];
}
return match ($number % 10) {
1 => $number . static::$ordinals['first'],
2 => $number . static::$ordinals['second'],
3 => $number . static::$ordinals['third'],
default => $number . static::$ordinals['default'],
};
}
/**

View File

@@ -24,7 +24,7 @@ use function is_object;
* Class Iterator
* @package Grav\Common
*/
class Iterator implements \ArrayAccess, \Iterator, \Countable, \Serializable
class Iterator implements \ArrayAccess, \Iterator, \Countable, \Serializable, \Stringable
{
use Constructor, ArrayAccessWithGetters, ArrayIterator, Countable, Serializable, Export;
@@ -35,11 +35,10 @@ class Iterator implements \ArrayAccess, \Iterator, \Countable, \Serializable
* Convert function calls for the existing keys into their values.
*
* @param string $key
* @param mixed $args
* @return mixed
*/
#[\ReturnTypeWillChange]
public function __call($key, $args)
public function __call($key, mixed $args)
{
return $this->items[$key] ?? null;
}
@@ -63,7 +62,7 @@ class Iterator implements \ArrayAccess, \Iterator, \Countable, \Serializable
* @return string
*/
#[\ReturnTypeWillChange]
public function __toString()
public function __toString(): string
{
return implode(',', $this->items);
}
@@ -143,7 +142,7 @@ class Iterator implements \ArrayAccess, \Iterator, \Countable, \Serializable
*
* @return string|int|false Key if found, otherwise false.
*/
public function indexOf($needle)
public function indexOf(mixed $needle)
{
foreach (array_values($this->items) as $key => $value) {
if ($value === $needle) {

View File

@@ -149,9 +149,7 @@ class Language
{
$languagesArray = $this->languages; //Make local copy
$languagesArray = array_map(static function ($value) use ($delimiter) {
return preg_quote($value, $delimiter);
}, $languagesArray);
$languagesArray = array_map(static fn($value) => preg_quote((string) $value, $delimiter), $languagesArray);
sort($languagesArray);
@@ -593,7 +591,7 @@ class Language
*/
public function getBrowserLanguages($accept_langs = [])
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, no longer used', E_USER_DEPRECATED);
user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, no longer used', E_USER_DEPRECATED);
if (empty($this->http_accept_language)) {
if (empty($accept_langs) && isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
@@ -604,7 +602,7 @@ class Language
$langs = [];
foreach (explode(',', $accept_langs) as $k => $pref) {
foreach (explode(',', (string) $accept_langs) as $k => $pref) {
// split $pref again by ';q='
// and decorate the language entries by inverted position
if (false !== ($i = strpos($pref, ';q='))) {

View File

@@ -35,7 +35,7 @@ class Parsedown extends \Parsedown
$defaults = ['markdown' => $defaults];
}
$excerpts = new Excerpts($excerpts, $defaults);
user_error(__CLASS__ . '::' . __FUNCTION__ . '($page, $defaults) is deprecated since Grav 1.6.10, use new ' . __CLASS__ . '(new ' . Excerpts::class . '($page, [\'markdown\' => $defaults])) instead.', E_USER_DEPRECATED);
user_error(self::class . '::' . __FUNCTION__ . '($page, $defaults) is deprecated since Grav 1.6.10, use new ' . self::class . '(new ' . Excerpts::class . '($page, [\'markdown\' => $defaults])) instead.', E_USER_DEPRECATED);
}
$this->init($excerpts, $defaults);

View File

@@ -36,7 +36,7 @@ class ParsedownExtra extends \ParsedownExtra
$defaults = ['markdown' => $defaults];
}
$excerpts = new Excerpts($excerpts, $defaults);
user_error(__CLASS__ . '::' . __FUNCTION__ . '($page, $defaults) is deprecated since Grav 1.6.10, use new ' . __CLASS__ . '(new ' . Excerpts::class . '($page, [\'markdown\' => $defaults])) instead.', E_USER_DEPRECATED);
user_error(self::class . '::' . __FUNCTION__ . '($page, $defaults) is deprecated since Grav 1.6.10, use new ' . self::class . '(new ' . Excerpts::class . '($page, [\'markdown\' => $defaults])) instead.', E_USER_DEPRECATED);
}
parent::__construct();

View File

@@ -49,7 +49,7 @@ trait ParsedownGravTrait
$defaults = ['markdown' => $defaults];
}
$this->excerpts = new Excerpts($excerpts, $defaults);
user_error(__CLASS__ . '::' . __FUNCTION__ . '($page, $defaults) is deprecated since Grav 1.6.10, use ->init(new ' . Excerpts::class . '($page, [\'markdown\' => $defaults])) instead.', E_USER_DEPRECATED);
user_error(self::class . '::' . __FUNCTION__ . '($page, $defaults) is deprecated since Grav 1.6.10, use ->init(new ' . Excerpts::class . '($page, [\'markdown\' => $defaults])) instead.', E_USER_DEPRECATED);
} else {
$this->excerpts = $excerpts;
}
@@ -133,7 +133,7 @@ trait ParsedownGravTrait
array_splice($this->InlineTypes[$type], $index, 0, [$tag]);
}
if (strpos($this->inlineMarkerList, $type) === false) {
if (!str_contains($this->inlineMarkerList, $type)) {
$this->inlineMarkerList .= $type;
}
}
@@ -199,7 +199,7 @@ trait ParsedownGravTrait
*/
protected function blockTwigTag($line)
{
if (preg_match('/(?:{{|{%|{#)(.*)(?:}}|%}|#})/', $line['body'], $matches)) {
if (preg_match('/(?:{{|{%|{#)(.*)(?:}}|%}|#})/', (string) $line['body'], $matches)) {
return ['markup' => $line['body']];
}
@@ -212,7 +212,7 @@ trait ParsedownGravTrait
*/
protected function inlineSpecialCharacter($excerpt)
{
if ($excerpt['text'][0] === '&' && !preg_match('/^&#?\w+;/', $excerpt['text'])) {
if ($excerpt['text'][0] === '&' && !preg_match('/^&#?\w+;/', (string) $excerpt['text'])) {
return [
'markup' => '&amp;',
'extent' => 1,
@@ -235,7 +235,7 @@ trait ParsedownGravTrait
*/
protected function inlineImage($excerpt)
{
if (preg_match($this->twig_link_regex, $excerpt['text'], $matches)) {
if (preg_match($this->twig_link_regex, (string) $excerpt['text'], $matches)) {
$excerpt['text'] = str_replace($matches[1], '/', $excerpt['text']);
$excerpt = parent::inlineImage($excerpt);
$excerpt['element']['attributes']['src'] = $matches[1];
@@ -264,7 +264,7 @@ trait ParsedownGravTrait
$type = $excerpt['type'] ?? 'link';
// do some trickery to get around Parsedown requirement for valid URL if its Twig in there
if (preg_match($this->twig_link_regex, $excerpt['text'], $matches)) {
if (preg_match($this->twig_link_regex, (string) $excerpt['text'], $matches)) {
$excerpt['text'] = str_replace($matches[1], '/', $excerpt['text']);
$excerpt = parent::inlineLink($excerpt);
$excerpt['element']['attributes']['href'] = $matches[1];

View File

@@ -207,11 +207,10 @@ interface MediaObjectInterface extends \Grav\Framework\Media\Interfaces\MediaObj
* Allow any action to be called on this medium from twig or markdown
*
* @param string $method
* @param mixed $args
* @return $this
*/
#[\ReturnTypeWillChange]
public function __call($method, $args);
public function __call($method, mixed $args);
/**
* Set value by using dot notation for nested arrays/objects.
@@ -223,5 +222,5 @@ interface MediaObjectInterface extends \Grav\Framework\Media\Interfaces\MediaObj
* @param string|null $separator Separator, defaults to '.'
* @return $this
*/
public function set($name, $value, $separator = null);
public function set($name, mixed $value, $separator = null);
}

View File

@@ -97,7 +97,7 @@ trait ImageMediaTrait
}
$basename = $this->get('basename');
if (preg_match('/[a-z0-9]{40}-(.*)/', $basename, $matches)) {
if (preg_match('/[a-z0-9]{40}-(.*)/', (string) $basename, $matches)) {
$basename = $matches[1];
}
return $basename;

View File

@@ -88,7 +88,7 @@ trait MediaFileTrait
}
$path = $this->path(false);
$output = preg_replace('|^' . preg_quote(GRAV_ROOT, '|') . '|', '', $path) ?: $path;
$output = preg_replace('|^' . preg_quote(GRAV_ROOT, '|') . '|', '', (string) $path) ?: $path;
/** @var UniformResourceLocator $locator */
$locator = $this->getGrav()['locator'];

View File

@@ -182,7 +182,7 @@ trait MediaObjectTrait
// join the strings
$querystring = implode('&', $this->medium_querystring);
// explode all strings
$query_parts = explode('&', $querystring);
$query_parts = explode('&', (string) $querystring);
// Join them again now ensure the elements are unique
$querystring = implode('&', array_unique($query_parts));
@@ -598,7 +598,7 @@ trait MediaObjectTrait
* @param string|null $separator Separator, defaults to '.'
* @return mixed Value.
*/
abstract public function get($name, $default = null, $separator = null);
abstract public function get($name, mixed $default = null, $separator = null);
/**
* Set value by using dot notation for nested arrays/objects.
@@ -610,7 +610,7 @@ trait MediaObjectTrait
* @param string|null $separator Separator, defaults to '.'
* @return $this
*/
abstract public function set($name, $value, $separator = null);
abstract public function set($name, mixed $value, $separator = null);
/**
* @param string $thumb

View File

@@ -57,15 +57,15 @@ trait MediaTrait
return null;
}
if (strpos($folder, '://')) {
if (strpos((string) $folder, '://')) {
return $folder;
}
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
$user = $locator->findResource('user://');
if (strpos($folder, $user) === 0) {
return 'user://' . substr($folder, strlen($user)+1);
if (str_starts_with((string) $folder, $user)) {
return 'user://' . substr((string) $folder, strlen($user)+1);
}
return null;

View File

@@ -206,11 +206,11 @@ trait MediaUploadTrait
break;
}
$isMime = strstr($type, '/');
$isMime = strstr((string) $type, '/');
$find = str_replace(['.', '*', '+'], ['\.', '.*', '\+'], $type);
if ($isMime) {
$match = preg_match('#' . $find . '$#', $mime);
$match = preg_match('#' . $find . '$#', (string) $mime);
if (!$match) {
// TODO: translate
$errors[] = 'The MIME type "' . $mime . '" for the file "' . $filepath . '" is not an accepted.';
@@ -219,7 +219,7 @@ trait MediaUploadTrait
break;
}
} else {
$match = preg_match('#' . $find . '$#', $filename);
$match = preg_match('#' . $find . '$#', (string) $filename);
if (!$match) {
// TODO: translate
$errors[] = 'The File Extension for the file "' . $filepath . '" is not an accepted.';
@@ -286,7 +286,7 @@ trait MediaUploadTrait
if ($uploadedFile->getError() === \UPLOAD_ERR_OK) {
// Move uploaded file.
$this->doMoveUploadedFile($uploadedFile, $filename, $path);
} elseif (strpos($filename, 'original/') === 0 && !$this->fileExists($filename, $path) && $this->fileExists($basename, $path)) {
} elseif (str_starts_with($filename, 'original/') && !$this->fileExists($filename, $path) && $this->fileExists($basename, $path)) {
// Original image support: override original image if it's the same as the uploaded image.
$this->doCopy($basename, $filename, $path);
}
@@ -558,7 +558,7 @@ trait MediaUploadTrait
$fileParts = (array)$filesystem->pathinfo($filename);
foreach ($dir as $file) {
$preg_name = preg_quote($fileParts['filename'], '`');
$preg_name = preg_quote((string) $fileParts['filename'], '`');
$preg_ext = preg_quote($fileParts['extension'] ?? '.', '`');
$preg_filename = preg_quote($basename, '`');

View File

@@ -138,7 +138,7 @@ trait ThumbnailMediaTrait
$closure = [$parent, $method];
if (!is_callable($closure)) {
throw new BadMethodCallException(get_class($parent) . '::' . $method . '() not found.');
throw new BadMethodCallException($parent::class . '::' . $method . '() not found.');
}
return $closure(...$arguments);

View File

@@ -139,9 +139,7 @@ class Collection extends Iterator implements PageCollectionInterface
$array1 = $this->items;
$array2 = $collection->toArray();
$this->items = array_uintersect($array1, $array2, function ($val1, $val2) {
return strcmp($val1['slug'], $val2['slug']);
});
$this->items = array_uintersect($array1, $array2, fn($val1, $val2) => strcmp((string) $val1['slug'], (string) $val2['slug']));
return $this;
}
@@ -357,7 +355,7 @@ class Collection extends Iterator implements PageCollectionInterface
continue;
}
$date = $field ? strtotime($page->value($field)) : $page->date();
$date = $field ? strtotime((string) $page->value($field)) : $page->date();
if ((!$start || $date >= $start) && (!$end || $date <= $end)) {
$date_range[$path] = $slug;

View File

@@ -43,9 +43,8 @@ interface PageLegacyInterface
* Modify a header value directly
*
* @param string $key
* @param mixed $value
*/
public function modifyHeader($key, $value);
public function modifyHeader($key, mixed $value);
/**
* @return int
@@ -68,9 +67,8 @@ interface PageLegacyInterface
* Add an entry to the page's contentMeta array
*
* @param string $name
* @param mixed $value
*/
public function addContentMeta($name, $value);
public function addContentMeta($name, mixed $value);
/**
* Return the whole contentMeta array as it currently stands

View File

@@ -49,7 +49,7 @@ class Excerpts
// Add defaults to the configuration.
if (null === $config || !isset($config['markdown'], $config['images'])) {
$c = Grav::instance()['config'];
$config = $config ?? [];
$config ??= [];
$config += [
'markdown' => $c->get('system.pages.markdown', []),
'images' => $c->get('system.images', [])
@@ -96,13 +96,13 @@ class Excerpts
public function processLinkExcerpt(array $excerpt, string $type = 'link'): array
{
$grav = Grav::instance();
$url = htmlspecialchars_decode(rawurldecode($excerpt['element']['attributes']['href']));
$url = htmlspecialchars_decode(rawurldecode((string) $excerpt['element']['attributes']['href']));
$url_parts = $this->parseUrl($url);
// If there is a query, then parse it and build action calls.
if (isset($url_parts['query'])) {
$actions = array_reduce(
explode('&', $url_parts['query']),
explode('&', (string) $url_parts['query']),
static function ($carry, $item) {
$parts = explode('=', $item, 2);
$value = isset($parts[1]) ? rawurldecode($parts[1]) : true;
@@ -119,7 +119,7 @@ class Excerpts
$skip = [];
// Unless told to not process, go through actions.
if (array_key_exists('noprocess', $actions)) {
$skip = is_bool($actions['noprocess']) ? $actions : explode(',', $actions['noprocess']);
$skip = is_bool($actions['noprocess']) ? $actions : explode(',', (string) $actions['noprocess']);
unset($actions['noprocess']);
}
@@ -185,7 +185,7 @@ class Excerpts
*/
public function processImageExcerpt(array $excerpt): array
{
$url = htmlspecialchars_decode(urldecode($excerpt['element']['attributes']['src']));
$url = htmlspecialchars_decode(urldecode((string) $excerpt['element']['attributes']['src']));
$url_parts = $this->parseUrl($url);
$media = null;
@@ -207,7 +207,7 @@ class Excerpts
if ($local_file) {
$filename = Utils::basename($url_parts['path']);
$folder = dirname($url_parts['path']);
$folder = dirname((string) $url_parts['path']);
// Get the local path to page media if possible.
if ($this->page && $folder === $this->page->url(false, false, false)) {
@@ -268,7 +268,7 @@ class Excerpts
// if there is a query, then parse it and build action calls
if (isset($url_parts['query'])) {
$actions = array_reduce(
explode('&', $url_parts['query']),
explode('&', (string) $url_parts['query']),
static function ($carry, $item) {
$parts = explode('=', $item, 2);
$value = $parts[1] ?? null;
@@ -296,10 +296,10 @@ class Excerpts
foreach ($actions as $action) {
$matches = [];
if (preg_match('/\[(.*)\]/', $action['params'], $matches)) {
if (preg_match('/\[(.*)\]/', (string) $action['params'], $matches)) {
$args = [explode(',', $matches[1])];
} else {
$args = explode(',', $action['params']);
$args = explode(',', (string) $action['params']);
}
$medium = call_user_func_array([$medium, $action['method']], $args);

View File

@@ -152,14 +152,14 @@ class Media extends AbstractMedia
foreach ($iterator as $file => $info) {
// Ignore folders and Markdown files.
$filename = $info->getFilename();
if (!$info->isFile() || $info->getExtension() === 'md' || $filename === 'frontmatter.yaml' || $filename === 'media.json' || strpos($filename, '.') === 0) {
if (!$info->isFile() || $info->getExtension() === 'md' || $filename === 'frontmatter.yaml' || $filename === 'media.json' || str_starts_with($filename, '.')) {
continue;
}
// Find out what type we're dealing with
[$basename, $ext, $type, $extra] = $this->getFileParts($filename);
if (!in_array(strtolower($ext), $media_types, true)) {
if (!in_array(strtolower((string) $ext), $media_types, true)) {
continue;
}

View File

@@ -95,9 +95,7 @@ class ImageFile extends Image
// Target file should be younger than all the current image
// dependencies
$conditions = array(
'younger-than' => $this->getDependencies()
);
$conditions = ['younger-than' => $this->getDependencies()];
// The generating function
$generate = function ($target) use ($image, $type, $quality) {
@@ -113,7 +111,7 @@ class ImageFile extends Image
// Asking the cache for the cacheFile
try {
$perms = $config->get('system.images.cache_perms', '0755');
$perms = octdec($perms);
$perms = octdec((string) $perms);
$file = $this->getCacheSystem()->setDirectoryMode($perms)->getOrCreateFile($cacheFile, $conditions, $generate, $actual);
} catch (GenerationError $e) {
$file = $e->getNewFile();

View File

@@ -370,7 +370,7 @@ class ImageMedium extends Medium implements ImageMediaInterface, ImageManipulate
$watermark->resize($wwidth, $wheight);
// Position operations
$position = !empty($args[1]) ? explode('-', $args[1]) : ['center', 'center']; // todo change to config
$position = !empty($args[1]) ? explode('-', (string) $args[1]) : ['center', 'center']; // todo change to config
$positionY = $position[0] ?? $config->get('system.images.watermark.position_y', 'center');
$positionX = $position[1] ?? $config->get('system.images.watermark.position_x', 'center');
@@ -491,7 +491,7 @@ class ImageMedium extends Medium implements ImageMediaInterface, ImageManipulate
// Do the same call for alternative media.
$medium->__call($method, $args_copy);
}
} catch (BadFunctionCallException $e) {
} catch (BadFunctionCallException) {
}
return $this;

View File

@@ -76,16 +76,15 @@ class Link implements RenderableInterface, MediaLinkInterface
* Forward the call to the source element
*
* @param string $method
* @param mixed $args
* @return mixed
*/
#[\ReturnTypeWillChange]
public function __call($method, $args)
public function __call($method, mixed $args)
{
$object = $this->source;
$callable = [$object, $method];
if (!is_callable($callable)) {
throw new BadMethodCallException(get_class($object) . '::' . $method . '() not found.');
throw new BadMethodCallException($object::class . '::' . $method . '() not found.');
}
$object = call_user_func_array($callable, $args);

View File

@@ -99,7 +99,7 @@ class Medium extends Data implements RenderableInterface, MediaFileInterface
* @return string
*/
#[\ReturnTypeWillChange]
public function __toString()
public function __toString(): string
{
return $this->html();
}

View File

@@ -46,7 +46,7 @@ class MediumFactory
$config = Grav::instance()['config'];
$media_params = $ext ? $config->get('media.types.' . strtolower($ext)) : null;
$media_params = $ext ? $config->get('media.types.' . strtolower((string) $ext)) : null;
if (!is_array($media_params)) {
return null;
}
@@ -111,7 +111,7 @@ class MediumFactory
$config = Grav::instance()['config'];
$media_params = $ext ? $config->get('media.types.' . strtolower($ext)) : null;
$media_params = $ext ? $config->get('media.types.' . strtolower((string) $ext)) : null;
if (!is_array($media_params)) {
return null;
}
@@ -154,22 +154,15 @@ class MediumFactory
{
$type = $items['type'] ?? null;
switch ($type) {
case 'image':
return new ImageMedium($items, $blueprint);
case 'thumbnail':
return new ThumbnailImageMedium($items, $blueprint);
case 'vector':
return new VectorImageMedium($items, $blueprint);
case 'animated':
return new StaticImageMedium($items, $blueprint);
case 'video':
return new VideoMedium($items, $blueprint);
case 'audio':
return new AudioMedium($items, $blueprint);
default:
return new Medium($items, $blueprint);
}
return match ($type) {
'image' => new ImageMedium($items, $blueprint),
'thumbnail' => new ThumbnailImageMedium($items, $blueprint),
'vector' => new VectorImageMedium($items, $blueprint),
'animated' => new StaticImageMedium($items, $blueprint),
'video' => new VideoMedium($items, $blueprint),
'audio' => new AudioMedium($items, $blueprint),
default => new Medium($items, $blueprint),
};
}
/**

View File

@@ -203,14 +203,14 @@ class Page implements PageInterface
$this->home_route = $this->adjustRouteCase($config->get('system.home.alias'));
$this->filePath($file->getPathname());
$this->modified($file->getMTime());
$this->id($this->modified() . md5($this->filePath()));
$this->id($this->modified() . md5((string) $this->filePath()));
$this->routable(true);
$this->header();
$this->date();
$this->metadata();
$this->url();
$this->visible();
$this->modularTwig(strpos($this->slug(), '_') === 0);
$this->modularTwig(str_starts_with($this->slug(), '_'));
$this->setPublishState();
$this->published();
$this->urlExtension();
@@ -254,7 +254,7 @@ class Page implements PageInterface
}
}
$text_header = Grav::instance()['twig']->processString(json_encode($process_fields, JSON_UNESCAPED_UNICODE), ['page' => $this]);
$this->header((object)(json_decode($text_header, true) + $ignored_fields));
$this->header((object)(json_decode((string) $text_header, true) + $ignored_fields));
}
}
@@ -274,7 +274,7 @@ class Page implements PageInterface
$languages = $language->getLanguages();
$defaultCode = $language->getDefault();
$name = substr($this->name, 0, -strlen($this->extension()));
$name = substr((string) $this->name, 0, -strlen($this->extension()));
$translatedLanguages = [];
foreach ($languages as $languageCode) {
@@ -347,7 +347,7 @@ class Page implements PageInterface
// Reset header and content.
$this->modified = time();
$this->id($this->modified() . md5($this->filePath()));
$this->id($this->modified() . md5((string) $this->filePath()));
$this->header = null;
$this->content = null;
$this->summary = null;
@@ -375,7 +375,7 @@ class Page implements PageInterface
}
// Force content re-processing.
$this->id(time() . md5($this->filePath()));
$this->id(time() . md5((string) $this->filePath()));
}
if (!$this->frontmatter) {
$this->header();
@@ -402,7 +402,7 @@ class Page implements PageInterface
}
// Force content re-processing.
$this->id(time() . md5($this->filePath()));
$this->id(time() . md5((string) $this->filePath()));
}
if (!$this->header) {
$file = $this->file();
@@ -742,7 +742,7 @@ class Page implements PageInterface
}
// Force re-processing.
$this->id(time() . md5($this->filePath()));
$this->id(time() . md5((string) $this->filePath()));
$this->content = null;
}
// If no content, process it
@@ -842,7 +842,7 @@ class Page implements PageInterface
// Handle summary divider
$delimiter = $config->get('site.summary.delimiter', '===');
$divider_pos = mb_strpos($this->content, "<p>{$delimiter}</p>");
$divider_pos = mb_strpos((string) $this->content, "<p>{$delimiter}</p>");
if ($divider_pos !== false) {
$this->summary_size = $divider_pos;
$this->content = str_replace("<p>{$delimiter}</p>", '', $this->content);
@@ -955,8 +955,8 @@ class Page implements PageInterface
// Base64 encode any twig.
$content = preg_replace_callback(
['/({#.*?#})/mu', '/({{.*?}})/mu', '/({%.*?%})/mu'],
static function ($matches) use ($token) { return $token[0] . base64_encode($matches[1]) . $token[1]; },
$content
static fn($matches) => $token[0] . base64_encode((string) $matches[1]) . $token[1],
(string) $content
);
}
@@ -966,8 +966,8 @@ class Page implements PageInterface
// Base64 decode the encoded twig.
$content = preg_replace_callback(
['`' . $token[0] . '([A-Za-z0-9+/]+={0,2})' . $token[1] . '`mu'],
static function ($matches) { return base64_decode($matches[1]); },
$content
static fn($matches) => base64_decode((string) $matches[1]),
(string) $content
);
}
@@ -1202,7 +1202,7 @@ class Page implements PageInterface
}
$this->parent($parent);
$this->id(time() . md5($this->filePath()));
$this->id(time() . md5((string) $this->filePath()));
if ($parent->path()) {
$this->path($parent->path() . '/' . $this->folder());
@@ -1288,7 +1288,7 @@ class Page implements PageInterface
}
$post_value = $_POST['blueprint'];
$sanitized_value = htmlspecialchars(strip_tags($post_value), ENT_QUOTES, 'UTF-8');
$sanitized_value = htmlspecialchars(strip_tags((string) $post_value), ENT_QUOTES, 'UTF-8');
return $sanitized_value ?: $this->template();
}
@@ -1761,7 +1761,7 @@ class Page implements PageInterface
$this->metadata[$prop_key] = [
'name' => $prop_key,
'property' => $prop_key,
'content' => $escape ? htmlspecialchars($prop_value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $prop_value
'content' => $escape ? htmlspecialchars((string) $prop_value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $prop_value
];
}
} else {
@@ -1770,16 +1770,16 @@ class Page implements PageInterface
if (in_array($key, $header_tag_http_equivs, true)) {
$this->metadata[$key] = [
'http_equiv' => $key,
'content' => $escape ? htmlspecialchars($value, ENT_COMPAT, 'UTF-8') : $value
'content' => $escape ? htmlspecialchars((string) $value, ENT_COMPAT, 'UTF-8') : $value
];
} elseif ($key === 'charset') {
$this->metadata[$key] = ['charset' => $escape ? htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $value];
$this->metadata[$key] = ['charset' => $escape ? htmlspecialchars((string) $value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $value];
} else {
// if it's a social metadata with separator, render as property
$separator = strpos($key, ':');
$hasSeparator = $separator && $separator < strlen($key) - 1;
$entry = [
'content' => $escape ? htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $value
'content' => $escape ? htmlspecialchars((string) $value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $value
];
if ($hasSeparator && !Utils::startsWith($key, ['twitter', 'flattr','fediverse'])) {
@@ -1919,7 +1919,7 @@ class Page implements PageInterface
/** @var Uri $uri */
$uri = $grav['uri'];
$url = $uri->rootUrl($include_host) . '/' . trim($route, '/') . $this->urlExtension();
$url = $uri->rootUrl($include_host) . '/' . trim((string) $route, '/') . $this->urlExtension();
return Uri::filterPath($url);
}
@@ -2044,7 +2044,7 @@ class Page implements PageInterface
{
if (null === $this->id) {
// We need to set unique id to avoid potential cache conflicts between pages.
$var = time() . md5($this->filePath());
$var = time() . md5((string) $this->filePath());
}
if ($var !== null) {
// store unique per language
@@ -2536,7 +2536,7 @@ class Page implements PageInterface
*/
public function active()
{
$uri_path = rtrim(urldecode(Grav::instance()['uri']->path()), '/') ?: '/';
$uri_path = rtrim(urldecode((string) Grav::instance()['uri']->path()), '/') ?: '/';
$routes = Grav::instance()['pages']->routes();
return isset($routes[$uri_path]) && $routes[$uri_path] === $this->path();
@@ -2794,7 +2794,7 @@ class Page implements PageInterface
protected function cleanPath($path)
{
$lastchunk = strrchr($path, DS);
if (strpos($lastchunk, ':') !== false) {
if (str_contains($lastchunk, ':')) {
$path = str_replace($lastchunk, '', $path);
}
@@ -2827,7 +2827,7 @@ class Page implements PageInterface
// Reorder all moved pages.
foreach ($siblings as $slug => $page) {
$order = (int)trim($page->order(), '.');
$order = (int)trim((string) $page->order(), '.');
$counter++;
if ($order) {

View File

@@ -168,7 +168,7 @@ class Pages
*/
public function baseRoute($lang = null)
{
$key = $lang ?: $this->active_lang ?: 'default';
$key = ($lang ?: $this->active_lang) ?: 'default';
if (!isset($this->baseRoute[$key])) {
/** @var Language $language */
@@ -217,7 +217,7 @@ class Pages
// Start by checking that referrer came from our site.
$root = $this->grav['base_url_absolute'];
if (!is_string($referrer) || !str_starts_with($referrer, $root)) {
if (!is_string($referrer) || !str_starts_with($referrer, (string) $root)) {
return null;
}
@@ -470,7 +470,7 @@ class Pages
/** @var Uri $uri */
$uri = $this->grav['uri'];
foreach ($context['taxonomies'] as $taxonomy) {
$param = $uri->param(rawurlencode($taxonomy));
$param = $uri->param(rawurlencode((string) $taxonomy));
$items = is_string($param) ? explode(',', $param) : [];
foreach ($items as $item) {
$params['taxonomies'][$taxonomy][] = htmlspecialchars_decode(rawurldecode($item), ENT_QUOTES);
@@ -534,8 +534,8 @@ class Pages
}
// Convert non-type to type.
if (str_starts_with($type, 'non-')) {
$type = substr($type, 4);
if (str_starts_with((string) $type, 'non-')) {
$type = substr((string) $type, 4);
$filter = !$filter;
}
@@ -610,9 +610,7 @@ class Pages
if (is_array($sort_flags)) {
$sort_flags = array_map('constant', $sort_flags); //transform strings to constant value
$sort_flags = array_reduce($sort_flags, static function ($a, $b) {
return $a | $b;
}, 0); //merge constant values using bit or
$sort_flags = array_reduce($sort_flags, static fn($a, $b) => $a | $b, 0); //merge constant values using bit or
}
$collection = $collection->order($by, $dir, $custom, $sort_flags);
@@ -1013,7 +1011,7 @@ class Pages
foreach (array_reverse($site_routes, true) as $pattern => $replace) {
$pattern = '#^' . str_replace('/', '\/', ltrim($pattern, '^')) . '#';
try {
$found = preg_replace($pattern, $replace, $route);
$found = preg_replace($pattern, (string) $replace, $route);
if ($found && $found !== $route) {
$page = $this->find($found);
if ($page) {
@@ -1095,7 +1093,7 @@ class Pages
$pattern = '#^' . str_replace('/', '\/', $pattern) . '#';
try {
/** @var string $found */
$found = preg_replace($pattern, $replace, $source_url);
$found = preg_replace($pattern, (string) $replace, $source_url);
if ($found && $found !== $source_url) {
$this->grav->redirectLangSafe($found);
}
@@ -1142,7 +1140,7 @@ class Pages
try {
$blueprint = $this->blueprints->get($type);
} catch (RuntimeException $e) {
} catch (RuntimeException) {
$blueprint = $this->blueprints->get('default');
}
@@ -1254,7 +1252,7 @@ class Pages
}
if ($showFullpath) {
$option = htmlspecialchars($current->route());
$option = htmlspecialchars((string) $current->route());
} else {
$extra = $showSlug ? '(' . $current->slug() . ') ' : '';
$option = str_repeat('&mdash;-', $level). '&rtrif; ' . $extra . htmlspecialchars($current->title());
@@ -1337,7 +1335,7 @@ class Pages
$locator = $grav['locator'];
foreach ($types as $type => $paths) {
foreach ($paths as $k => $path) {
if (strpos($path, 'blueprints://') === 0) {
if (str_starts_with((string) $path, 'blueprints://')) {
unset($paths[$k]);
}
}
@@ -1393,15 +1391,11 @@ class Pages
$type = $page && $page->isModule() ? 'modular' : 'standard';
}
switch ($type) {
case 'standard':
return static::types();
case 'modular':
return static::modularTypes();
}
return [];
return match ($type) {
'standard' => static::types(),
'modular' => static::modularTypes(),
default => [],
};
}
/**
@@ -1475,13 +1469,13 @@ class Pages
} else {
$home = $home_aliases[$default];
}
} catch (ErrorException $e) {
} catch (ErrorException) {
$home = $home_aliases[$default];
}
}
}
self::$home_route = trim($home, '/');
self::$home_route = trim((string) $home, '/');
}
return self::$home_route;
@@ -1730,20 +1724,12 @@ class Pages
$language = $this->grav['language'];
// how should we check for last modified? Default is by file
switch ($this->check_method) {
case 'none':
case 'off':
$hash = 0;
break;
case 'folder':
$hash = Folder::lastModifiedFolder($pages_dirs);
break;
case 'hash':
$hash = Folder::hashAllFiles($pages_dirs);
break;
default:
$hash = Folder::lastModifiedFile($pages_dirs);
}
$hash = match ($this->check_method) {
'none', 'off' => 0,
'folder' => Folder::lastModifiedFolder($pages_dirs),
'hash' => Folder::hashAllFiles($pages_dirs),
default => Folder::lastModifiedFile($pages_dirs),
};
$this->simple_pages_hash = json_encode($pages_dirs) . $hash . $config->checksum();
$this->pages_cache_id = md5($this->simple_pages_hash . $language->getActive());
@@ -1861,9 +1847,7 @@ class Pages
// Build regular expression for all the allowed page extensions.
$page_extensions = $language->getFallbackPageExtensions();
$regex = '/^[^\.]*(' . implode('|', array_map(
static function ($str) {
return preg_quote($str, '/');
},
static fn($str) => preg_quote((string) $str, '/'),
$page_extensions
)) . ')$/';
@@ -1877,7 +1861,7 @@ class Pages
$filename = $file->getFilename();
// Ignore all hidden files if set.
if ($this->ignore_hidden && $filename && strpos($filename, '.') === 0) {
if ($this->ignore_hidden && $filename && str_starts_with($filename, '.')) {
continue;
}
@@ -2079,7 +2063,7 @@ class Pages
$header_default = null;
// do this header query work only once
if (strpos($order_by, 'header.') === 0) {
if (str_starts_with($order_by, 'header.')) {
$query = explode('|', str_replace('header.', '', $order_by), 2);
$header_query = array_shift($query) ?? '';
$header_default = array_shift($query);
@@ -2159,9 +2143,7 @@ class Pages
if ($col) {
$col->setAttribute(Collator::NUMERIC_COLLATION, Collator::ON);
if (($sort_flags & SORT_NATURAL) === SORT_NATURAL) {
$list = preg_replace_callback('~([0-9]+)\.~', static function ($number) {
return sprintf('%032d.', $number[0]);
}, $list);
$list = preg_replace_callback('~([0-9]+)\.~', static fn($number) => sprintf('%032d.', $number[0]), $list);
if (!is_array($list)) {
throw new RuntimeException('Internal Error');
}

View File

@@ -111,7 +111,7 @@ trait PageFormTrait
$name = null;
}
$name = $name ?? $form['name'] ?? $this->slug();
$name ??= $form['name'] ?? $this->slug();
$formRules = $form['rules'] ?? null;
if (!is_array($formRules)) {

View File

@@ -142,7 +142,7 @@ class Types implements \ArrayAccess, \Iterator, \Countable
{
$list = [];
foreach ($this->items as $name => $file) {
if (strpos($name, 'modular/') !== 0) {
if (!str_starts_with($name, 'modular/')) {
continue;
}
$list[$name] = ucfirst(trim(str_replace('_', ' ', Utils::basename($name))));

View File

@@ -30,8 +30,6 @@ use function is_string;
*/
class Plugin implements EventSubscriberInterface, ArrayAccess
{
/** @var string */
public $name;
/** @var array */
public $features = [];
@@ -57,7 +55,7 @@ class Plugin implements EventSubscriberInterface, ArrayAccess
$list = [];
foreach ($methods as $method) {
if (strpos($method, 'on') === 0) {
if (str_starts_with($method, 'on')) {
$list[$method] = [$method, 0];
}
}
@@ -72,9 +70,8 @@ class Plugin implements EventSubscriberInterface, ArrayAccess
* @param Grav $grav
* @param Config|null $config
*/
public function __construct($name, Grav $grav, ?Config $config = null)
public function __construct(public $name, Grav $grav, ?Config $config = null)
{
$this->name = $name;
$this->grav = $grav;
if ($config) {
@@ -156,7 +153,7 @@ class Plugin implements EventSubscriberInterface, ArrayAccess
/** @var Config $config */
$config = $this->config ?? $this->grav['config'];
if (strpos($uri->path(), $config->get('plugins.admin.route') . '/' . $plugin_route) === false) {
if (!str_contains($uri->path(), $config->get('plugins.admin.route') . '/' . $plugin_route)) {
$active = false;
} elseif (isset($uri->paths()[1]) && $uri->paths()[1] === $plugin_route) {
$active = true;
@@ -265,9 +262,9 @@ class Plugin implements EventSubscriberInterface, ArrayAccess
* @throws LogicException
*/
#[\ReturnTypeWillChange]
public function offsetSet($offset, $value)
public function offsetSet($offset, mixed $value)
{
throw new LogicException(__CLASS__ . ' blueprints cannot be modified.');
throw new LogicException(self::class . ' blueprints cannot be modified.');
}
/**
@@ -279,7 +276,7 @@ class Plugin implements EventSubscriberInterface, ArrayAccess
#[\ReturnTypeWillChange]
public function offsetUnset($offset)
{
throw new LogicException(__CLASS__ . ' blueprints cannot be modified.');
throw new LogicException(self::class . ' blueprints cannot be modified.');
}
/**
@@ -330,7 +327,7 @@ class Plugin implements EventSubscriberInterface, ArrayAccess
* @param string $type Is this 'plugins' or 'themes'
* @return Data
*/
protected function mergeConfig(PageInterface $page, $deep = false, $params = [], $type = 'plugins')
protected function mergeConfig(PageInterface $page, mixed $deep = false, $params = [], $type = 'plugins')
{
/** @var Config $config */
$config = $this->config ?? $this->grav['config'];
@@ -419,7 +416,7 @@ class Plugin implements EventSubscriberInterface, ArrayAccess
if (Utils::isAdminPlugin()) {
$page = Grav::instance()['admin']->page() ?? null;
} else {
$page = $page ?? Grav::instance()['page'] ?? null;
$page ??= Grav::instance()['page'] ?? null;
}
// Try to find var in the page headers

View File

@@ -86,7 +86,7 @@ class Plugins extends Iterator
$blueprints["plugin://{$plugin->name}/blueprints"] = $plugin->features['blueprints'];
}
if (method_exists($plugin, 'getFormFieldTypes')) {
$formFields[get_class($plugin)] = $plugin->features['formfields'] ?? 0;
$formFields[$plugin::class] = $plugin->features['formfields'] ?? 0;
}
}
}
@@ -168,7 +168,7 @@ class Plugins extends Iterator
public function add($plugin)
{
if (is_object($plugin)) {
$this->items[get_class($plugin)] = $plugin;
$this->items[$plugin::class] = $plugin;
}
}

View File

@@ -126,9 +126,7 @@ class InitializeProcessor extends ProcessorBase
// Wrap call to next handler so that debugger can profile it.
/** @var Response $response */
$response = $debugger->profile(static function () use ($handler, $request) {
return $handler->handle($request);
});
$response = $debugger->profile(static fn() => $handler->handle($request));
// Log both request and response and return the response.
return $debugger->logRequest($request, $response);
@@ -448,7 +446,7 @@ class InitializeProcessor extends ProcessorBase
try {
$session->init();
} catch (SessionException $e) {
} catch (SessionException) {
$session->init();
$message = 'Session corruption detected, restarting session...';
$this->addMessage($message);

View File

@@ -53,7 +53,7 @@ class TasksProcessor extends ProcessorBase
$this->stopTimer();
return $response;
} catch (NotFoundException $e) {
} catch (NotFoundException) {
// Task not found: Let it pass through.
}
}

View File

@@ -224,8 +224,8 @@ class Cron
public function getType()
{
$mask = preg_replace('/[^\* ]/', '-', $this->getCron());
$mask = preg_replace('/-+/', '-', $mask);
$mask = preg_replace('/[^-\*]/', '', $mask);
$mask = preg_replace('/-+/', '-', (string) $mask);
$mask = preg_replace('/[^-\*]/', '', (string) $mask);
if ($mask === '*****') {
return self::TYPE_MINUTE;
@@ -235,19 +235,19 @@ class Cron
return self::TYPE_HOUR;
}
if (substr($mask, -3) === '***') {
if (str_ends_with((string) $mask, '***')) {
return self::TYPE_DAY;
}
if (substr($mask, -3) === '-**') {
if (str_ends_with((string) $mask, '-**')) {
return self::TYPE_MONTH;
}
if (substr($mask, -3) === '**-') {
if (str_ends_with((string) $mask, '**-')) {
return self::TYPE_WEEK;
}
if (substr($mask, -2) === '-*') {
if (str_ends_with((string) $mask, '-*')) {
return self::TYPE_YEAR;
}
@@ -264,7 +264,7 @@ class Cron
$cron = trim($cron);
$cron = preg_replace('/\s+/', ' ', $cron);
// explode
$elements = explode(' ', $cron);
$elements = explode(' ', (string) $cron);
if (count($elements) !== 5) {
throw new RuntimeException('Bad number of elements');
}
@@ -415,7 +415,6 @@ class Cron
}
/**
* @param mixed $date
* @param int $min
* @param int $hour
* @param int $day
@@ -423,7 +422,7 @@ class Cron
* @param int $weekday
* @return DateTime
*/
protected function parseDate($date, &$min, &$hour, &$day, &$month, &$weekday)
protected function parseDate(mixed $date, &$min, &$hour, &$day, &$month, &$weekday)
{
if (is_numeric($date) && (int)$date == $date) {
$date = new DateTime('@' . $date);

View File

@@ -39,8 +39,6 @@ class Job
private $command;
/** @var string */
private $at;
/** @var array */
private $args = [];
/** @var bool */
private $runInBackground = true;
/** @var DateTime */
@@ -85,7 +83,7 @@ class Job
* @param array $args
* @param string|null $id
*/
public function __construct($command, $args = [], $id = null)
public function __construct($command, private $args = [], $id = null)
{
if (is_string($id)) {
$this->id = Grav::instance()['inflector']->hyphenize($id);
@@ -101,7 +99,6 @@ class Job
// initialize the directory path for lock files
$this->tempDir = sys_get_temp_dir();
$this->command = $command;
$this->args = $args;
// Set enabled state
$status = Grav::instance()['config']->get('scheduler.status');
$this->enabled = !(isset($status[$id]) && $status[$id] === 'disabled');
@@ -195,7 +192,7 @@ class Job
$this->at('* * * * *');
}
$date = $date ?? $this->creationTime;
$date ??= $this->creationTime;
return $this->executionTime->isDue($date);
}
@@ -271,9 +268,7 @@ class Job
if ($whenOverlapping) {
$this->whenOverlapping = $whenOverlapping;
} else {
$this->whenOverlapping = static function () {
return false;
};
$this->whenOverlapping = static fn() => false;
}
return $this;
@@ -410,10 +405,9 @@ class Job
/**
* Create the job lock file.
*
* @param mixed $content
* @return void
*/
private function createLockFile($content = null)
private function createLockFile(mixed $content = null)
{
if ($this->lockFile) {
if ($content === null || !is_string($content)) {

View File

@@ -244,16 +244,12 @@ class Scheduler
*/
public function getVerboseOutput($type = 'text')
{
switch ($type) {
case 'text':
return implode("\n", $this->output_schedule);
case 'html':
return implode('<br>', $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('<br>', $this->output_schedule),
'array' => $this->output_schedule,
default => throw new InvalidArgumentException('Invalid output type'),
};
}
/**
@@ -287,7 +283,7 @@ class Scheduler
public function getSchedulerCommand($php = null)
{
$phpBinaryFinder = new PhpExecutableFinder();
$php = $php ?? $phpBinaryFinder->find();
$php ??= $phpBinaryFinder->find();
$command = 'cd ' . str_replace(' ', '\ ', GRAV_ROOT) . ';' . $php . ' bin/grav scheduler';
return $command;
@@ -439,7 +435,7 @@ class Scheduler
if (is_callable($command)) {
$command = is_string($command) ? $command : 'Closure';
}
$output = trim($job->getOutput());
$output = trim((string) $job->getOutput());
$this->addSchedulerVerboseOutput("<red>Error</red>: <white>{$command}</white> → <normal>{$output}</normal>");
return $job;

View File

@@ -129,7 +129,7 @@ class Security
$list[$page->rawRoute()] = $results;
}
}
} catch (Exception $e) {
} catch (Exception) {
continue;
}
}
@@ -196,7 +196,7 @@ class Security
if (!$invalid_protocols) {
$enabled_rules['invalid_protocols'] = false;
}
$enabled_rules = array_filter($enabled_rules, static function ($val) { return !empty($val); });
$enabled_rules = array_filter($enabled_rules, static fn($val) => !empty($val));
if (!$enabled_rules) {
return null;
}
@@ -208,19 +208,17 @@ class Security
$string = urldecode($string);
// Convert Hexadecimals
$string = (string)preg_replace_callback('!(&#|\\\)[xX]([0-9a-fA-F]+);?!u', static function ($m) {
return chr(hexdec($m[2]));
}, $string);
$string = (string)preg_replace_callback('!(&#|\\\)[xX]([0-9a-fA-F]+);?!u', static fn($m) => chr(hexdec((string) $m[2])), $string);
// Clean up entities
$string = preg_replace('!(&#[0-9]+);?!u', '$1;', $string);
// Decode entities
$string = html_entity_decode($string, ENT_NOQUOTES | ENT_HTML5, 'UTF-8');
$string = html_entity_decode((string) $string, ENT_NOQUOTES | ENT_HTML5, 'UTF-8');
// Strip whitespace characters
$string = preg_replace('!\s!u', ' ', $string);
$stripped = preg_replace('!\s!u', '', $string);
$stripped = preg_replace('!\s!u', '', (string) $string);
// Set the patterns we'll test against
$patterns = [
@@ -243,7 +241,7 @@ class Security
// Iterate over rules and return label if fail
foreach ($patterns as $name => $regex) {
if (!empty($enabled_rules[$name])) {
if (preg_match($regex, $string) || preg_match($regex, $stripped) || preg_match($regex, $orig)) {
if (preg_match($regex, (string) $string) || preg_match($regex, (string) $stripped) || preg_match($regex, $orig)) {
return $name;
}
}

View File

@@ -25,8 +25,6 @@ class AssetsServiceProvider implements ServiceProviderInterface
*/
public function register(Container $container)
{
$container['assets'] = function () {
return new Assets();
};
$container['assets'] = fn() => new Assets();
}
}

View File

@@ -42,9 +42,7 @@ class ConfigServiceProvider implements ServiceProviderInterface
return $setup;
};
$container['blueprints'] = function ($c) {
return static::blueprints($c);
};
$container['blueprints'] = fn($c) => static::blueprints($c);
$container['config'] = function ($c) {
$config = static::load($c);
@@ -70,13 +68,9 @@ class ConfigServiceProvider implements ServiceProviderInterface
return MimeTypes::createFromMimes($mimes);
};
$container['languages'] = function ($c) {
return static::languages($c);
};
$container['languages'] = fn($c) => static::languages($c);
$container['language'] = function ($c) {
return new Language($c);
};
$container['language'] = fn($c) => new Language($c);
}
/**
@@ -129,9 +123,7 @@ class ConfigServiceProvider implements ServiceProviderInterface
$files += (new ConfigFileFinder)->setBase('themes')->locateInFolders($paths);
$compiled = new CompiledConfig($cache, $files, GRAV_ROOT);
$compiled->setBlueprints(function () use ($container) {
return $container['blueprints'];
});
$compiled->setBlueprints(fn() => $container['blueprints']);
$config = $compiled->name("master-{$setup->environment}")->load();
$config->environment = $setup->environment;

View File

@@ -25,8 +25,6 @@ class FilesystemServiceProvider implements ServiceProviderInterface
*/
public function register(Container $container)
{
$container['filesystem'] = function () {
return Filesystem::getInstance();
};
$container['filesystem'] = fn() => Filesystem::getInstance();
}
}

View File

@@ -25,8 +25,6 @@ class InflectorServiceProvider implements ServiceProviderInterface
*/
public function register(Container $container)
{
$container['inflector'] = function () {
return new Inflector();
};
$container['inflector'] = fn() => new Inflector();
}
}

View File

@@ -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) {

View File

@@ -73,7 +73,7 @@ class RequestServiceProvider implements ServiceProviderInterface
if (!is_array($post)) {
$post = null;
}
} catch (JsonException $e) {
} catch (JsonException) {
$post = null;
}
break 2;
@@ -86,7 +86,7 @@ class RequestServiceProvider implements ServiceProviderInterface
unset($get['_url']);
if (isset($server['QUERY_STRING'])) {
$query = $server['QUERY_STRING'];
if (strpos($query, '_url=') !== false) {
if (str_contains($query, '_url=')) {
parse_str($query, $query);
unset($query['_url']);
$server['QUERY_STRING'] = http_build_query($query);
@@ -96,8 +96,6 @@ class RequestServiceProvider implements ServiceProviderInterface
return $creator->fromArrays($server, $headers, $_COOKIE, $get, $post, $_FILES, fopen('php://input', 'rb') ?: null);
};
$container['route'] = $container->factory(function () {
return clone Uri::getCurrentRoute();
});
$container['route'] = $container->factory(fn() => clone Uri::getCurrentRoute());
}
}

View File

@@ -25,8 +25,6 @@ class SchedulerServiceProvider implements ServiceProviderInterface
*/
public function register(Container $container)
{
$container['scheduler'] = function () {
return new Scheduler();
};
$container['scheduler'] = fn() => new Scheduler();
}
}

View File

@@ -64,7 +64,7 @@ class SessionServiceProvider implements ServiceProviderInterface
// Activate admin if we're inside the admin path.
$is_admin = false;
if ($config->get('plugins.admin.enabled')) {
$admin_base = '/' . trim($config->get('plugins.admin.route'), '/');
$admin_base = '/' . trim((string) $config->get('plugins.admin.route'), '/');
// Uri::route() is not processed yet, let's quickly get what we need.
$current_route = str_replace(Uri::filterPath($uri->rootUrl(false)), '', parse_url($uri->url(true), PHP_URL_PATH));
@@ -86,7 +86,7 @@ class SessionServiceProvider implements ServiceProviderInterface
}
$session_prefix = $c['inflector']->hyphenize($config->get('system.session.name', 'grav-site'));
$session_uniqueness = $config->get('system.session.uniqueness', 'path') === 'path' ? substr(md5(GRAV_ROOT), 0, 7) : md5($config->get('security.salt'));
$session_uniqueness = $config->get('system.session.uniqueness', 'path') === 'path' ? substr(md5(GRAV_ROOT), 0, 7) : md5((string) $config->get('security.salt'));
$session_name = $session_prefix . '-' . $session_uniqueness;

View File

@@ -31,7 +31,7 @@ class Session extends \Grav\Framework\Session\Session
*/
public static function instance()
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use ->getInstance() method instead', E_USER_DEPRECATED);
user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use ->getInstance() method instead', E_USER_DEPRECATED);
return static::getInstance();
}
@@ -71,7 +71,7 @@ class Session extends \Grav\Framework\Session\Session
*/
public function all()
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use ->getAll() method instead', E_USER_DEPRECATED);
user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use ->getAll() method instead', E_USER_DEPRECATED);
return $this->getAll();
}
@@ -84,7 +84,7 @@ class Session extends \Grav\Framework\Session\Session
*/
public function started()
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use ->isStarted() method instead', E_USER_DEPRECATED);
user_error(self::class . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use ->isStarted() method instead', E_USER_DEPRECATED);
return $this->isStarted();
}
@@ -93,10 +93,9 @@ class Session extends \Grav\Framework\Session\Session
* Store something in session temporarily.
*
* @param string $name
* @param mixed $object
* @return $this
*/
public function setFlashObject($name, $object)
public function setFlashObject($name, mixed $object)
{
$this->__set($name, serialize($object));
@@ -147,14 +146,13 @@ class Session extends \Grav\Framework\Session\Session
* Store something in cookie temporarily.
*
* @param string $name
* @param mixed $object
* @param int $time
* @return $this
* @throws JsonException
*/
public function setFlashCookieObject($name, $object, $time = 60)
public function setFlashCookieObject($name, mixed $object, $time = 60)
{
setcookie($name, json_encode($object, JSON_THROW_ON_ERROR), $this->getCookieOptions($time));
setcookie($name, json_encode($object, JSON_THROW_ON_ERROR), ['expires' => $this->getCookieOptions($time)]);
return $this;
}
@@ -170,9 +168,9 @@ class Session extends \Grav\Framework\Session\Session
{
if (isset($_COOKIE[$name])) {
$cookie = $_COOKIE[$name];
setcookie($name, '', $this->getCookieOptions(-42000));
setcookie($name, '', ['expires' => $this->getCookieOptions(-42000)]);
return json_decode($cookie, false, 512, JSON_THROW_ON_ERROR);
return json_decode((string) $cookie, false, 512, JSON_THROW_ON_ERROR);
}
return null;

View File

@@ -77,7 +77,7 @@ class Themes extends Iterator
try {
$instance = $themes->load();
} catch (InvalidArgumentException $e) {
} catch (InvalidArgumentException) {
throw new RuntimeException($this->current() . ' theme could not be found');
}
@@ -377,7 +377,7 @@ class Themes extends Iterator
protected function autoloadTheme($class)
{
$prefix = 'Grav\\Theme\\';
if (false !== strpos($class, $prefix)) {
if (str_contains($class, $prefix)) {
// Remove prefix from class
$class = substr($class, strlen($prefix));
$locator = $this->grav['locator'];

View File

@@ -36,29 +36,29 @@ class FilesystemExtension extends AbstractExtension
public function getFilters()
{
return [
new TwigFilter('file_exists', [$this, 'file_exists']),
new TwigFilter('fileatime', [$this, 'fileatime']),
new TwigFilter('filectime', [$this, 'filectime']),
new TwigFilter('filemtime', [$this, 'filemtime']),
new TwigFilter('filesize', [$this, 'filesize']),
new TwigFilter('filetype', [$this, 'filetype']),
new TwigFilter('is_dir', [$this, 'is_dir']),
new TwigFilter('is_file', [$this, 'is_file']),
new TwigFilter('is_link', [$this, 'is_link']),
new TwigFilter('is_readable', [$this, 'is_readable']),
new TwigFilter('is_writable', [$this, 'is_writable']),
new TwigFilter('is_writeable', [$this, 'is_writable']),
new TwigFilter('lstat', [$this, 'lstat']),
new TwigFilter('getimagesize', [$this, 'getimagesize']),
new TwigFilter('exif_read_data', [$this, 'exif_read_data']),
new TwigFilter('read_exif_data', [$this, 'exif_read_data']),
new TwigFilter('exif_imagetype', [$this, 'exif_imagetype']),
new TwigFilter('hash_file', [$this, 'hash_file']),
new TwigFilter('hash_hmac_file', [$this, 'hash_hmac_file']),
new TwigFilter('md5_file', [$this, 'md5_file']),
new TwigFilter('sha1_file', [$this, 'sha1_file']),
new TwigFilter('get_meta_tags', [$this, 'get_meta_tags']),
new TwigFilter('pathinfo', [$this, 'pathinfo']),
new TwigFilter('file_exists', $this->file_exists(...)),
new TwigFilter('fileatime', $this->fileatime(...)),
new TwigFilter('filectime', $this->filectime(...)),
new TwigFilter('filemtime', $this->filemtime(...)),
new TwigFilter('filesize', $this->filesize(...)),
new TwigFilter('filetype', $this->filetype(...)),
new TwigFilter('is_dir', $this->is_dir(...)),
new TwigFilter('is_file', $this->is_file(...)),
new TwigFilter('is_link', $this->is_link(...)),
new TwigFilter('is_readable', $this->is_readable(...)),
new TwigFilter('is_writable', $this->is_writable(...)),
new TwigFilter('is_writeable', $this->is_writable(...)),
new TwigFilter('lstat', $this->lstat(...)),
new TwigFilter('getimagesize', $this->getimagesize(...)),
new TwigFilter('exif_read_data', $this->exif_read_data(...)),
new TwigFilter('read_exif_data', $this->exif_read_data(...)),
new TwigFilter('exif_imagetype', $this->exif_imagetype(...)),
new TwigFilter('hash_file', $this->hash_file(...)),
new TwigFilter('hash_hmac_file', $this->hash_hmac_file(...)),
new TwigFilter('md5_file', $this->md5_file(...)),
new TwigFilter('sha1_file', $this->sha1_file(...)),
new TwigFilter('get_meta_tags', $this->get_meta_tags(...)),
new TwigFilter('pathinfo', $this->pathinfo(...)),
];
}
@@ -70,29 +70,29 @@ class FilesystemExtension extends AbstractExtension
public function getFunctions()
{
return [
new TwigFunction('file_exists', [$this, 'file_exists']),
new TwigFunction('fileatime', [$this, 'fileatime']),
new TwigFunction('filectime', [$this, 'filectime']),
new TwigFunction('filemtime', [$this, 'filemtime']),
new TwigFunction('filesize', [$this, 'filesize']),
new TwigFunction('filetype', [$this, 'filetype']),
new TwigFunction('is_dir', [$this, 'is_dir']),
new TwigFunction('is_file', [$this, 'is_file']),
new TwigFunction('is_link', [$this, 'is_link']),
new TwigFunction('is_readable', [$this, 'is_readable']),
new TwigFunction('is_writable', [$this, 'is_writable']),
new TwigFunction('is_writeable', [$this, 'is_writable']),
new TwigFunction('lstat', [$this, 'lstat']),
new TwigFunction('getimagesize', [$this, 'getimagesize']),
new TwigFunction('exif_read_data', [$this, 'exif_read_data']),
new TwigFunction('read_exif_data', [$this, 'exif_read_data']),
new TwigFunction('exif_imagetype', [$this, 'exif_imagetype']),
new TwigFunction('hash_file', [$this, 'hash_file']),
new TwigFunction('hash_hmac_file', [$this, 'hash_hmac_file']),
new TwigFunction('md5_file', [$this, 'md5_file']),
new TwigFunction('sha1_file', [$this, 'sha1_file']),
new TwigFunction('get_meta_tags', [$this, 'get_meta_tags']),
new TwigFunction('pathinfo', [$this, 'pathinfo']),
new TwigFunction('file_exists', $this->file_exists(...)),
new TwigFunction('fileatime', $this->fileatime(...)),
new TwigFunction('filectime', $this->filectime(...)),
new TwigFunction('filemtime', $this->filemtime(...)),
new TwigFunction('filesize', $this->filesize(...)),
new TwigFunction('filetype', $this->filetype(...)),
new TwigFunction('is_dir', $this->is_dir(...)),
new TwigFunction('is_file', $this->is_file(...)),
new TwigFunction('is_link', $this->is_link(...)),
new TwigFunction('is_readable', $this->is_readable(...)),
new TwigFunction('is_writable', $this->is_writable(...)),
new TwigFunction('is_writeable', $this->is_writable(...)),
new TwigFunction('lstat', $this->lstat(...)),
new TwigFunction('getimagesize', $this->getimagesize(...)),
new TwigFunction('exif_read_data', $this->exif_read_data(...)),
new TwigFunction('read_exif_data', $this->exif_read_data(...)),
new TwigFunction('exif_imagetype', $this->exif_imagetype(...)),
new TwigFunction('hash_file', $this->hash_file(...)),
new TwigFunction('hash_hmac_file', $this->hash_hmac_file(...)),
new TwigFunction('md5_file', $this->md5_file(...)),
new TwigFunction('sha1_file', $this->sha1_file(...)),
new TwigFunction('get_meta_tags', $this->get_meta_tags(...)),
new TwigFunction('pathinfo', $this->pathinfo(...)),
];
}

View File

@@ -109,72 +109,72 @@ class GravExtension extends AbstractExtension implements GlobalsInterface
public function getFilters(): array
{
return [
new TwigFilter('*ize', [$this, 'inflectorFilter']),
new TwigFilter('absolute_url', [$this, 'absoluteUrlFilter']),
new TwigFilter('contains', [$this, 'containsFilter']),
new TwigFilter('chunk_split', [$this, 'chunkSplitFilter']),
new TwigFilter('nicenumber', [$this, 'niceNumberFunc']),
new TwigFilter('nicefilesize', [$this, 'niceFilesizeFunc']),
new TwigFilter('nicetime', [$this, 'nicetimeFunc']),
new TwigFilter('defined', [$this, 'definedDefaultFilter']),
new TwigFilter('ends_with', [$this, 'endsWithFilter']),
new TwigFilter('fieldName', [$this, 'fieldNameFilter']),
new TwigFilter('parent_field', [$this, 'fieldParentFilter']),
new TwigFilter('ksort', [$this, 'ksortFilter']),
new TwigFilter('ltrim', [$this, 'ltrimFilter']),
new TwigFilter('markdown', [$this, 'markdownFunction'], ['needs_context' => true, 'is_safe' => ['html']]),
new TwigFilter('md5', [$this, 'md5Filter']),
new TwigFilter('base32_encode', [$this, 'base32EncodeFilter']),
new TwigFilter('base32_decode', [$this, 'base32DecodeFilter']),
new TwigFilter('base64_encode', [$this, 'base64EncodeFilter']),
new TwigFilter('base64_decode', [$this, 'base64DecodeFilter']),
new TwigFilter('randomize', [$this, 'randomizeFilter']),
new TwigFilter('modulus', [$this, 'modulusFilter']),
new TwigFilter('rtrim', [$this, 'rtrimFilter']),
new TwigFilter('pad', [$this, 'padFilter']),
new TwigFilter('regex_replace', [$this, 'regexReplace']),
new TwigFilter('safe_email', [$this, 'safeEmailFilter'], ['is_safe' => ['html']]),
new TwigFilter('safe_truncate', [Utils::class, 'safeTruncate']),
new TwigFilter('safe_truncate_html', [Utils::class, 'safeTruncateHTML']),
new TwigFilter('sort_by_key', [$this, 'sortByKeyFilter']),
new TwigFilter('starts_with', [$this, 'startsWithFilter']),
new TwigFilter('truncate', [Utils::class, 'truncate']),
new TwigFilter('truncate_html', [Utils::class, 'truncateHTML']),
new TwigFilter('json_decode', [$this, 'jsonDecodeFilter']),
new TwigFilter('*ize', $this->inflectorFilter(...)),
new TwigFilter('absolute_url', $this->absoluteUrlFilter(...)),
new TwigFilter('contains', $this->containsFilter(...)),
new TwigFilter('chunk_split', $this->chunkSplitFilter(...)),
new TwigFilter('nicenumber', $this->niceNumberFunc(...)),
new TwigFilter('nicefilesize', $this->niceFilesizeFunc(...)),
new TwigFilter('nicetime', $this->nicetimeFunc(...)),
new TwigFilter('defined', $this->definedDefaultFilter(...)),
new TwigFilter('ends_with', $this->endsWithFilter(...)),
new TwigFilter('fieldName', $this->fieldNameFilter(...)),
new TwigFilter('parent_field', $this->fieldParentFilter(...)),
new TwigFilter('ksort', $this->ksortFilter(...)),
new TwigFilter('ltrim', $this->ltrimFilter(...)),
new TwigFilter('markdown', $this->markdownFunction(...), ['needs_context' => true, 'is_safe' => ['html']]),
new TwigFilter('md5', $this->md5Filter(...)),
new TwigFilter('base32_encode', $this->base32EncodeFilter(...)),
new TwigFilter('base32_decode', $this->base32DecodeFilter(...)),
new TwigFilter('base64_encode', $this->base64EncodeFilter(...)),
new TwigFilter('base64_decode', $this->base64DecodeFilter(...)),
new TwigFilter('randomize', $this->randomizeFilter(...)),
new TwigFilter('modulus', $this->modulusFilter(...)),
new TwigFilter('rtrim', $this->rtrimFilter(...)),
new TwigFilter('pad', $this->padFilter(...)),
new TwigFilter('regex_replace', $this->regexReplace(...)),
new TwigFilter('safe_email', $this->safeEmailFilter(...), ['is_safe' => ['html']]),
new TwigFilter('safe_truncate', Utils::safeTruncate(...)),
new TwigFilter('safe_truncate_html', Utils::safeTruncateHTML(...)),
new TwigFilter('sort_by_key', $this->sortByKeyFilter(...)),
new TwigFilter('starts_with', $this->startsWithFilter(...)),
new TwigFilter('truncate', Utils::truncate(...)),
new TwigFilter('truncate_html', Utils::truncateHTML(...)),
new TwigFilter('json_decode', $this->jsonDecodeFilter(...)),
new TwigFilter('array_unique', 'array_unique'),
new TwigFilter('basename', 'basename'),
new TwigFilter('dirname', 'dirname'),
new TwigFilter('print_r', [$this, 'print_r']),
new TwigFilter('yaml_encode', [$this, 'yamlEncodeFilter']),
new TwigFilter('yaml_decode', [$this, 'yamlDecodeFilter']),
new TwigFilter('nicecron', [$this, 'niceCronFilter']),
new TwigFilter('replace_last', [$this, 'replaceLastFilter']),
new TwigFilter('print_r', $this->print_r(...)),
new TwigFilter('yaml_encode', $this->yamlEncodeFilter(...)),
new TwigFilter('yaml_decode', $this->yamlDecodeFilter(...)),
new TwigFilter('nicecron', $this->niceCronFilter(...)),
new TwigFilter('replace_last', $this->replaceLastFilter(...)),
// Translations
new TwigFilter('t', [$this, 'translate'], ['needs_environment' => true]),
new TwigFilter('tl', [$this, 'translateLanguage']),
new TwigFilter('ta', [$this, 'translateArray']),
new TwigFilter('t', $this->translate(...), ['needs_environment' => true]),
new TwigFilter('tl', $this->translateLanguage(...)),
new TwigFilter('ta', $this->translateArray(...)),
// Casting values
new TwigFilter('string', [$this, 'stringFilter']),
new TwigFilter('int', [$this, 'intFilter'], ['is_safe' => ['all']]),
new TwigFilter('bool', [$this, 'boolFilter']),
new TwigFilter('float', [$this, 'floatFilter'], ['is_safe' => ['all']]),
new TwigFilter('array', [$this, 'arrayFilter']),
new TwigFilter('yaml', [$this, 'yamlFilter']),
new TwigFilter('string', $this->stringFilter(...)),
new TwigFilter('int', $this->intFilter(...), ['is_safe' => ['all']]),
new TwigFilter('bool', $this->boolFilter(...)),
new TwigFilter('float', $this->floatFilter(...), ['is_safe' => ['all']]),
new TwigFilter('array', $this->arrayFilter(...)),
new TwigFilter('yaml', $this->yamlFilter(...)),
// Object Types
new TwigFilter('get_type', [$this, 'getTypeFunc']),
new TwigFilter('of_type', [$this, 'ofTypeFunc']),
new TwigFilter('get_type', $this->getTypeFunc(...)),
new TwigFilter('of_type', $this->ofTypeFunc(...)),
// PHP methods
new TwigFilter('count', 'count'),
new TwigFilter('array_diff', 'array_diff'),
// Security fixes
new TwigFilter('filter', [$this, 'filterFunc'], ['needs_environment' => true]),
new TwigFilter('map', [$this, 'mapFunc'], ['needs_environment' => true]),
new TwigFilter('reduce', [$this, 'reduceFunc'], ['needs_environment' => true]),
new TwigFilter('filter', $this->filterFunc(...), ['needs_environment' => true]),
new TwigFilter('map', $this->mapFunc(...), ['needs_environment' => true]),
new TwigFilter('reduce', $this->reduceFunc(...), ['needs_environment' => true]),
];
}
@@ -186,59 +186,59 @@ class GravExtension extends AbstractExtension implements GlobalsInterface
public function getFunctions(): array
{
return [
new TwigFunction('array', [$this, 'arrayFilter']),
new TwigFunction('array_key_value', [$this, 'arrayKeyValueFunc']),
new TwigFunction('array', $this->arrayFilter(...)),
new TwigFunction('array_key_value', $this->arrayKeyValueFunc(...)),
new TwigFunction('array_key_exists', 'array_key_exists'),
new TwigFunction('array_unique', 'array_unique'),
new TwigFunction('array_intersect', [$this, 'arrayIntersectFunc']),
new TwigFunction('array_intersect', $this->arrayIntersectFunc(...)),
new TwigFunction('array_diff', 'array_diff'),
new TwigFunction('authorize', [$this, 'authorize']),
new TwigFunction('debug', [$this, 'dump'], ['needs_context' => true, 'needs_environment' => true]),
new TwigFunction('dump', [$this, 'dump'], ['needs_context' => true, 'needs_environment' => true]),
new TwigFunction('vardump', [$this, 'vardumpFunc']),
new TwigFunction('print_r', [$this, 'print_r']),
new TwigFunction('authorize', $this->authorize(...)),
new TwigFunction('debug', $this->dump(...), ['needs_context' => true, 'needs_environment' => true]),
new TwigFunction('dump', $this->dump(...), ['needs_context' => true, 'needs_environment' => true]),
new TwigFunction('vardump', $this->vardumpFunc(...)),
new TwigFunction('print_r', $this->print_r(...)),
new TwigFunction('http_response_code', 'http_response_code'),
new TwigFunction('evaluate', [$this, 'evaluateStringFunc'], ['needs_context' => true]),
new TwigFunction('evaluate_twig', [$this, 'evaluateTwigFunc'], ['needs_context' => true]),
new TwigFunction('gist', [$this, 'gistFunc']),
new TwigFunction('nonce_field', [$this, 'nonceFieldFunc']),
new TwigFunction('evaluate', $this->evaluateStringFunc(...), ['needs_context' => true]),
new TwigFunction('evaluate_twig', $this->evaluateTwigFunc(...), ['needs_context' => true]),
new TwigFunction('gist', $this->gistFunc(...)),
new TwigFunction('nonce_field', $this->nonceFieldFunc(...)),
new TwigFunction('pathinfo', 'pathinfo'),
new TwigFunction('parseurl', 'parse_url'),
new TwigFunction('random_string', [$this, 'randomStringFunc']),
new TwigFunction('repeat', [$this, 'repeatFunc']),
new TwigFunction('regex_replace', [$this, 'regexReplace']),
new TwigFunction('regex_filter', [$this, 'regexFilter']),
new TwigFunction('regex_match', [$this, 'regexMatch']),
new TwigFunction('regex_split', [$this, 'regexSplit']),
new TwigFunction('string', [$this, 'stringFilter']),
new TwigFunction('url', [$this, 'urlFunc']),
new TwigFunction('json_decode', [$this, 'jsonDecodeFilter']),
new TwigFunction('get_cookie', [$this, 'getCookie']),
new TwigFunction('redirect_me', [$this, 'redirectFunc']),
new TwigFunction('range', [$this, 'rangeFunc']),
new TwigFunction('isajaxrequest', [$this, 'isAjaxFunc']),
new TwigFunction('exif', [$this, 'exifFunc']),
new TwigFunction('media_directory', [$this, 'mediaDirFunc']),
new TwigFunction('body_class', [$this, 'bodyClassFunc'], ['needs_context' => true]),
new TwigFunction('theme_var', [$this, 'themeVarFunc'], ['needs_context' => true]),
new TwigFunction('header_var', [$this, 'pageHeaderVarFunc'], ['needs_context' => true]),
new TwigFunction('read_file', [$this, 'readFileFunc']),
new TwigFunction('nicenumber', [$this, 'niceNumberFunc']),
new TwigFunction('nicefilesize', [$this, 'niceFilesizeFunc']),
new TwigFunction('nicetime', [$this, 'nicetimeFunc']),
new TwigFunction('cron', [$this, 'cronFunc']),
new TwigFunction('svg_image', [$this, 'svgImageFunction']),
new TwigFunction('xss', [$this, 'xssFunc']),
new TwigFunction('unique_id', [$this, 'uniqueId']),
new TwigFunction('random_string', $this->randomStringFunc(...)),
new TwigFunction('repeat', $this->repeatFunc(...)),
new TwigFunction('regex_replace', $this->regexReplace(...)),
new TwigFunction('regex_filter', $this->regexFilter(...)),
new TwigFunction('regex_match', $this->regexMatch(...)),
new TwigFunction('regex_split', $this->regexSplit(...)),
new TwigFunction('string', $this->stringFilter(...)),
new TwigFunction('url', $this->urlFunc(...)),
new TwigFunction('json_decode', $this->jsonDecodeFilter(...)),
new TwigFunction('get_cookie', $this->getCookie(...)),
new TwigFunction('redirect_me', $this->redirectFunc(...)),
new TwigFunction('range', $this->rangeFunc(...)),
new TwigFunction('isajaxrequest', $this->isAjaxFunc(...)),
new TwigFunction('exif', $this->exifFunc(...)),
new TwigFunction('media_directory', $this->mediaDirFunc(...)),
new TwigFunction('body_class', $this->bodyClassFunc(...), ['needs_context' => true]),
new TwigFunction('theme_var', $this->themeVarFunc(...), ['needs_context' => true]),
new TwigFunction('header_var', $this->pageHeaderVarFunc(...), ['needs_context' => true]),
new TwigFunction('read_file', $this->readFileFunc(...)),
new TwigFunction('nicenumber', $this->niceNumberFunc(...)),
new TwigFunction('nicefilesize', $this->niceFilesizeFunc(...)),
new TwigFunction('nicetime', $this->nicetimeFunc(...)),
new TwigFunction('cron', $this->cronFunc(...)),
new TwigFunction('svg_image', $this->svgImageFunction(...)),
new TwigFunction('xss', $this->xssFunc(...)),
new TwigFunction('unique_id', $this->uniqueId(...)),
// Translations
new TwigFunction('t', [$this, 'translate'], ['needs_environment' => true]),
new TwigFunction('tl', [$this, 'translateLanguage']),
new TwigFunction('ta', [$this, 'translateArray']),
new TwigFunction('t', $this->translate(...), ['needs_environment' => true]),
new TwigFunction('tl', $this->translateLanguage(...)),
new TwigFunction('ta', $this->translateArray(...)),
// Object Types
new TwigFunction('get_type', [$this, 'getTypeFunc']),
new TwigFunction('of_type', [$this, 'ofTypeFunc']),
new TwigFunction('get_type', $this->getTypeFunc(...)),
new TwigFunction('of_type', $this->ofTypeFunc(...)),
// PHP methods
new TwigFunction('is_numeric', 'is_numeric'),
@@ -253,9 +253,9 @@ class GravExtension extends AbstractExtension implements GlobalsInterface
new TwigFunction('parse_url', 'parse_url'),
// Security fixes
new TwigFunction('filter', [$this, 'filterFunc'], ['needs_environment' => true]),
new TwigFunction('map', [$this, 'mapFunc'], ['needs_environment' => true]),
new TwigFunction('reduce', [$this, 'reduceFunc'], ['needs_environment' => true]),
new TwigFunction('filter', $this->filterFunc(...), ['needs_environment' => true]),
new TwigFunction('map', $this->mapFunc(...), ['needs_environment' => true]),
new TwigFunction('reduce', $this->reduceFunc(...), ['needs_environment' => true]),
];
}
@@ -278,10 +278,9 @@ class GravExtension extends AbstractExtension implements GlobalsInterface
}
/**
* @param mixed $var
* @return string
*/
public function print_r($var)
public function print_r(mixed $var)
{
return print_r($var, true);
}
@@ -548,7 +547,7 @@ class GravExtension extends AbstractExtension implements GlobalsInterface
return $haystack;
}
return (strpos($haystack, (string) $needle) !== false);
return (str_contains($haystack, (string) $needle));
}
/**
@@ -700,9 +699,7 @@ class GravExtension extends AbstractExtension implements GlobalsInterface
}
$results = Security::detectXssFromArray($data);
$results_parts = array_map(static function ($value, $key) {
return $key.': \''.$value . '\'';
}, array_values($results), array_keys($results));
$results_parts = array_map(static fn($value, $key) => $key.': \''.$value . '\'', array_values($results), array_keys($results));
return implode(', ', $results_parts);
}
@@ -766,11 +763,10 @@ class GravExtension extends AbstractExtension implements GlobalsInterface
}
/**
* @param mixed $value
* @param null $default
* @return mixed|null
*/
public function definedDefaultFilter($value, $default = null)
public function definedDefaultFilter(mixed $value, $default = null)
{
return $value ?? $default;
}
@@ -798,10 +794,9 @@ class GravExtension extends AbstractExtension implements GlobalsInterface
/**
* Returns a string from a value. If the value is array, return it json encoded
*
* @param mixed $value
* @return string
*/
public function stringFilter($value)
public function stringFilter(mixed $value)
{
// Format the array as a string
if (is_array($value)) {
@@ -820,10 +815,9 @@ class GravExtension extends AbstractExtension implements GlobalsInterface
/**
* Casts input to int.
*
* @param mixed $input
* @return int
*/
public function intFilter($input)
public function intFilter(mixed $input)
{
return (int) $input;
}
@@ -831,10 +825,9 @@ class GravExtension extends AbstractExtension implements GlobalsInterface
/**
* Casts input to bool.
*
* @param mixed $input
* @return bool
*/
public function boolFilter($input)
public function boolFilter(mixed $input)
{
return (bool) $input;
}
@@ -842,10 +835,9 @@ class GravExtension extends AbstractExtension implements GlobalsInterface
/**
* Casts input to float.
*
* @param mixed $input
* @return float
*/
public function floatFilter($input)
public function floatFilter(mixed $input)
{
return (float) $input;
}
@@ -853,10 +845,9 @@ class GravExtension extends AbstractExtension implements GlobalsInterface
/**
* Casts input to array.
*
* @param mixed $input
* @return array
*/
public function arrayFilter($input)
public function arrayFilter(mixed $input)
{
if (is_array($input)) {
return $input;
@@ -1034,7 +1025,7 @@ class GravExtension extends AbstractExtension implements GlobalsInterface
if (method_exists($value, 'toArray')) {
$data[$key] = $value->toArray();
} else {
$data[$key] = 'Object (' . get_class($value) . ')';
$data[$key] = 'Object (' . $value::class . ')';
}
} else {
$data[$key] = $value;
@@ -1102,7 +1093,7 @@ class GravExtension extends AbstractExtension implements GlobalsInterface
public function arrayKeyValueFunc($key, $val, $current_array = null)
{
if (empty($current_array)) {
return array($key => $val);
return [$key => $val];
}
$current_array[$key] = $val;
@@ -1337,7 +1328,7 @@ class GravExtension extends AbstractExtension implements GlobalsInterface
{
return (
!empty($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest');
&& strtolower((string) $_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest');
}
/**
@@ -1422,10 +1413,9 @@ class GravExtension extends AbstractExtension implements GlobalsInterface
/**
* Dump a variable to the browser
*
* @param mixed $var
* @return void
*/
public function vardumpFunc($var)
public function vardumpFunc(mixed $var)
{
dump($var);
}
@@ -1497,7 +1487,7 @@ class GravExtension extends AbstractExtension implements GlobalsInterface
*/
public function themeVarFunc($context, $var, $default = null, $page = null, $exists = false)
{
$page = $page ?? $context['page'] ?? Grav::instance()['page'] ?? null;
$page ??= $context['page'] ?? Grav::instance()['page'] ?? null;
// Try to find var in the page headers
if ($page instanceof PageInterface && $page->exists()) {
@@ -1591,7 +1581,7 @@ class GravExtension extends AbstractExtension implements GlobalsInterface
//Strip style if needed
if ($strip_style) {
$svg = preg_replace('/<style.*<\/style>/s', '', $svg);
$svg = preg_replace('/<style.*<\/style>/s', '', (string) $svg);
}
//Look for existing class
@@ -1602,7 +1592,7 @@ class GravExtension extends AbstractExtension implements GlobalsInterface
return str_replace($matches[1], "class=\"$new_classes\"", $matches[0]);
}
return $matches[0];
}, $svg
}, (string) $svg
);
// no matches found just add the class
@@ -1611,7 +1601,7 @@ class GravExtension extends AbstractExtension implements GlobalsInterface
$svg = str_replace('<svg ', "<svg class=\"$classes\" ", $svg);
}
return trim($svg);
return trim((string) $svg);
}
return null;
@@ -1654,10 +1644,9 @@ class GravExtension extends AbstractExtension implements GlobalsInterface
/**
* Function/Filter to return the type of variable
*
* @param mixed $var
* @return string
*/
public function getTypeFunc($var)
public function getTypeFunc(mixed $var)
{
return gettype($var);
}
@@ -1665,45 +1654,25 @@ class GravExtension extends AbstractExtension implements GlobalsInterface
/**
* Function/Filter to test type of variable
*
* @param mixed $var
* @param string|null $typeTest
* @param string|null $className
* @return bool
*/
public function ofTypeFunc($var, $typeTest = null, $className = null)
public function ofTypeFunc(mixed $var, $typeTest = null, $className = null)
{
switch ($typeTest) {
default:
return false;
case 'array':
return is_array($var);
case 'bool':
return is_bool($var);
case 'class':
return is_object($var) === true && get_class($var) === $className;
case 'float':
return is_float($var);
case 'int':
return is_int($var);
case 'numeric':
return is_numeric($var);
case 'object':
return is_object($var);
case 'scalar':
return is_scalar($var);
case 'string':
return is_string($var);
}
return match ($typeTest) {
'array' => is_array($var),
'bool' => is_bool($var),
'class' => is_object($var) === true && $var::class === $className,
'float' => is_float($var),
'int' => is_int($var),
'numeric' => is_numeric($var),
'object' => is_object($var),
'scalar' => is_scalar($var),
'string' => is_string($var),
default => false,
};
}
/**

View File

@@ -55,7 +55,7 @@ class TwigTokenParserCache extends AbstractTokenParser
$stream->expect(Token::BLOCK_END_TYPE);
// Parse the content inside the cache block
$body = $this->parser->subparse([$this, 'decideCacheEnd'], true);
$body = $this->parser->subparse($this->decideCacheEnd(...), true);
$stream->expect(Token::BLOCK_END_TYPE);

View File

@@ -35,7 +35,7 @@ class TwigTokenParserMarkdown extends AbstractTokenParser
{
$lineno = $token->getLine();
$this->parser->getStream()->expect(Token::BLOCK_END_TYPE);
$body = $this->parser->subparse([$this, 'decideMarkdownEnd'], true);
$body = $this->parser->subparse($this->decideMarkdownEnd(...), true);
$this->parser->getStream()->expect(Token::BLOCK_END_TYPE);
return new TwigNodeMarkdown($body, $lineno, $this->getTag());
}

View File

@@ -48,7 +48,7 @@ class TwigTokenParserScript extends AbstractTokenParser
$content = null;
if ($file === null) {
$content = $this->parser->subparse([$this, 'decideBlockEnd'], true);
$content = $this->parser->subparse($this->decideBlockEnd(...), true);
$stream->expect(Token::BLOCK_END_TYPE);
}

View File

@@ -41,7 +41,7 @@ class TwigTokenParserStyle extends AbstractTokenParser
$content = null;
if (!$file) {
$content = $this->parser->subparse([$this, 'decideBlockEnd'], true);
$content = $this->parser->subparse($this->decideBlockEnd(...), true);
$stream->expect(Token::BLOCK_END_TYPE);
}

View File

@@ -74,7 +74,7 @@ class TwigTokenParserSwitch extends AbstractTokenParser
}
$stream->expect(Token::BLOCK_END_TYPE);
$body = $this->parser->subparse([$this, 'decideIfFork']);
$body = $this->parser->subparse($this->decideIfFork(...));
$cases[] = new Node([
'values' => new Node($values),
'body' => $body
@@ -83,7 +83,7 @@ class TwigTokenParserSwitch extends AbstractTokenParser
case 'default':
$stream->expect(Token::BLOCK_END_TYPE);
$default = $this->parser->subparse([$this, 'decideIfEnd']);
$default = $this->parser->subparse($this->decideIfEnd(...));
break;
case 'endswitch':

Some files were not shown because too many files have changed in this diff Show More