rector casting clarity

Signed-off-by: Andy Miller <rhuk@mac.com>
This commit is contained in:
Andy Miller
2025-09-20 22:49:21 -06:00
parent 22de638e52
commit 51ddb3984c
27 changed files with 50 additions and 65 deletions

View File

@@ -1,30 +1,16 @@
<?php
use Rector\Config\RectorConfig;
use Rector\Set\ValueObject\LevelSetList;
use Rector\Set\ValueObject\CodeQualitySetList;
use Rector\Set\ValueObject\DeadCodeSetList;
use Rector\Set\ValueObject\TypeDeclarationSetList;
use Rector\ValueObject\PhpVersion;
return RectorConfig::configure()
->withSkip([
__DIR__ . '/vendor',
])
->withPaths([
__DIR__,
__DIR__
])
// 8.x language upgrades — stack these once and move on
->withSets([
LevelSetList::UP_TO_PHP_84, // includes 8.2, 8.3, 8.4 language rules in one go [oai_citation:2‡DEV Community](https://dev.to/robertobutti/why-you-should-upgrade-to-php-84-or-at-least-php-8x-1ab0?utm_source=chatgpt.com)
CodeQualitySetList::UP_TO_CODE_QUALITY, // safe, general polish (early returns, etc.) [oai_citation:3‡Rector](https://getrector.com/documentation/levels?utm_source=chatgpt.com)
DeadCodeSetList::DEAD_CODE, // remove unused code
TypeDeclarationSetList::UP_TO_TYPE_DECLARATION, // add missing types where inferable
])
// (Optional) Pin a few “important for 8.4” rules explicitly
->withPhpSets(php82: true)
->withPhpVersion(Rector\ValueObject\PhpVersion::PHP_84)
->withRules([
Rector\Php84\Rector\Param\ExplicitNullableParamTypeRector::class, // `?T` requirement for nullable params in 8.4 [oai_citation:4‡DEV Community](https://dev.to/gromnan/fix-php-84-deprecation-implicitly-marking-parameter-as-nullable-is-deprecated-the-explicit-nullable-type-must-be-used-instead-5gp3?utm_source=chatgpt.com)
Rector\Php84\Rector\FuncCall\AddEscapeArgumentRector::class, // add `escape` to CSV funcs in 8.4 [oai_citation:5‡Rector](https://getrector.com/find-rule?rectorSet=php-php-84&utm_source=chatgpt.com)
Rector\Php84\Rector\MethodCall\NewMethodCallWithoutParenthesesRector::class, // 8.4 new() parentheses tweak [oai_citation:6‡Rector](https://getrector.com/find-rule?rectorSet=php-php-84&utm_source=chatgpt.com)
Rector\Php84\Rector\Param\ExplicitNullableParamTypeRector::class,
]);

View File

@@ -170,9 +170,9 @@ trait AssetUtilsTrait
}
if (in_array($key, $no_key, true)) {
$element = htmlentities($value, ENT_QUOTES, 'UTF-8', false);
$element = htmlentities((string) $value, ENT_QUOTES, 'UTF-8', false);
} else {
$element = $key . '="' . htmlentities($value, ENT_QUOTES, 'UTF-8', false) . '"';
$element = $key . '="' . htmlentities((string) $value, ENT_QUOTES, 'UTF-8', false) . '"';
}
$html .= ' ' . $element;

View File

@@ -142,7 +142,7 @@ class Blueprint extends BlueprintForm
{
foreach ($this->dynamic as $key => $data) {
// Locate field.
$path = explode('/', $key);
$path = explode('/', (string) $key);
$current = &$this->items;
foreach ($path as $field) {

View File

@@ -623,7 +623,7 @@ class Debugger
$table = [];
foreach ($timings as $key => $timing) {
$parts = explode('==>', $key);
$parts = explode('==>', (string) $key);
$method = $this->parseProfilerCall(array_pop($parts));
$context = $this->parseProfilerCall(array_pop($parts));
@@ -924,7 +924,6 @@ class Debugger
if ($object instanceof TemplateWrapper) {
$reflection = new ReflectionObject($object);
$property = $reflection->getProperty('template');
$property->setAccessible(true);
$object = $property->getValue($object);
}

View File

@@ -36,7 +36,7 @@ trait CompiledFile
$filename = $this->filename;
// If nothing has been loaded, attempt to get pre-compiled version of the file first.
if ($var === null && $this->raw === null && $this->content === null) {
$key = md5($filename);
$key = md5((string) $filename);
$file = PhpFile::instance(CACHE_DIR . "compiled/files/{$key}{$this->extension}.php");
$modified = $this->modified();

View File

@@ -28,7 +28,7 @@ class FormFlash extends FrameworkFormFlash
{
$fields = [];
foreach ($this->files as $field => $files) {
if (strpos($field, '/')) {
if (strpos((string) $field, '/')) {
continue;
}
foreach ($files as $file) {

View File

@@ -119,7 +119,7 @@ class GPM extends Iterator
if ($type_installed === false) {
continue;
}
$methodInstallableType = 'getInstalled' . ucfirst($type);
$methodInstallableType = 'getInstalled' . ucfirst((string) $type);
$to_install = $this->$methodInstallableType();
$items[$type] = $to_install;
$items['total'] += count($to_install);
@@ -279,7 +279,7 @@ class GPM extends Iterator
if ($type_updatable === false) {
continue;
}
$methodUpdatableType = 'getUpdatable' . ucfirst($type);
$methodUpdatableType = 'getUpdatable' . ucfirst((string) $type);
$to_update = $this->$methodUpdatableType();
$items[$type] = $to_update;
$items['total'] += count($to_update);

View File

@@ -82,7 +82,7 @@ class GravCore extends AbstractPackageCollection
$diffLog = [];
foreach ((array)$this->data['changelog'] as $version => $changelog) {
preg_match("/[\w\-\.]+/", $version, $cleanVersion);
preg_match("/[\w\-\.]+/", (string) $version, $cleanVersion);
if (!$cleanVersion || version_compare($diff, $cleanVersion[0], '>=')) {
continue;

View File

@@ -52,7 +52,7 @@ class Package extends BasePackage implements \JsonSerializable
$diffLog = [];
foreach ((array)$this->data['changelog'] as $version => $changelog) {
preg_match("/[\w\-.]+/", $version, $cleanVersion);
preg_match("/[\w\-.]+/", (string) $version, $cleanVersion);
if (!$cleanVersion || version_compare($diff, $cleanVersion[0], '>=')) {
continue;

View File

@@ -505,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 (str_starts_with($key, 'Grav-Internal-')) {
if (str_starts_with((string) $key, 'Grav-Internal-')) {
continue;
}
foreach ($values as $i => $value) {

View File

@@ -60,7 +60,7 @@ class Truncator
$words = $currentWordPosition[2];
$curNode->nodeValue = substr(
$curNode->nodeValue,
(string) $curNode->nodeValue,
0,
$words[$offset][1] + strlen((string) $words[$offset][0])
);
@@ -110,7 +110,7 @@ class Truncator
// If we have exceeded the limit, we want to delete the remainder of this document.
if ($letters->key() >= $limit) {
$currentText = $letters->currentTextPosition();
$currentText[0]->nodeValue = mb_substr($currentText[0]->nodeValue, 0, $currentText[1] + 1);
$currentText[0]->nodeValue = mb_substr((string) $currentText[0]->nodeValue, 0, $currentText[1] + 1);
self::removeProceedingNodes($currentText[0], $container);
if (!empty($ellipsis)) {
@@ -231,7 +231,7 @@ class Truncator
}
} else {
// Append to current node
$domNode->nodeValue = rtrim($domNode->nodeValue) . $ellipsis;
$domNode->nodeValue = rtrim((string) $domNode->nodeValue) . $ellipsis;
}
}

View File

@@ -126,7 +126,7 @@ class Inflector
if (is_array(static::$irregular)) {
foreach (static::$irregular as $_plural => $_singular) {
if (preg_match('/(' . $_singular . ')$/i', $word, $arr)) {
return preg_replace('/(' . $_singular . ')$/i', substr($arr[0], 0, 1) . substr($_plural, 1), $word);
return preg_replace('/(' . $_singular . ')$/i', substr($arr[0], 0, 1) . substr((string) $_plural, 1), $word);
}
}
}

View File

@@ -1752,7 +1752,7 @@ class Page implements PageInterface
// Build an array of meta objects..
foreach ((array)$metadata as $key => $value) {
// Lowercase the key
$key = strtolower($key);
$key = strtolower((string) $key);
// If this is a property type metadata: "og", "twitter", "facebook" etc
// Backward compatibility for nested arrays in metas
if (is_array($value)) {

View File

@@ -1009,7 +1009,7 @@ class Pages
} else {
// Use reverse order because of B/C (previously matched multiple and returned the last match).
foreach (array_reverse($site_routes, true) as $pattern => $replace) {
$pattern = '#^' . str_replace('/', '\/', ltrim($pattern, '^')) . '#';
$pattern = '#^' . str_replace('/', '\/', ltrim((string) $pattern, '^')) . '#';
try {
$found = preg_replace($pattern, (string) $replace, $route);
if ($found && $found !== $route) {
@@ -1089,7 +1089,7 @@ class Pages
$site_redirects = $config->get('site.redirects');
if (is_array($site_redirects)) {
foreach ((array)$site_redirects as $pattern => $replace) {
$pattern = ltrim($pattern, '^');
$pattern = ltrim((string) $pattern, '^');
$pattern = '#^' . str_replace('/', '\/', $pattern) . '#';
try {
/** @var string $found */

View File

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

View File

@@ -205,14 +205,14 @@ class InitializeProcessor extends ProcessorBase
$keys = $aliases = [];
$env = $_ENV + $_SERVER;
foreach ($env as $key => $value) {
if (!str_starts_with($key, $prefix)) {
if (!str_starts_with((string) $key, $prefix)) {
continue;
}
if (str_starts_with($key, $cPrefix)) {
$key = str_replace('__', '.', substr($key, $cLen));
if (str_starts_with((string) $key, $cPrefix)) {
$key = str_replace('__', '.', substr((string) $key, $cLen));
$keys[$key] = $value;
} elseif (str_starts_with($key, $aPrefix)) {
$key = substr($key, $aLen);
} elseif (str_starts_with((string) $key, $aPrefix)) {
$key = substr((string) $key, $aLen);
$aliases[$key] = $value;
}
}

View File

@@ -154,7 +154,7 @@ class Twig
$twig_paths = array_merge($twig_paths, $locator->findResources('theme://'.$prefix.'templates'));
$namespace = trim($prefix, '/');
$namespace = trim((string) $prefix, '/');
$this->loader->setPaths($twig_paths, $namespace);
}

View File

@@ -970,7 +970,7 @@ class Uri implements \Stringable
}
foreach ($parts as $name => $value) {
$parts[$name] = rawurldecode($value);
$parts[$name] = rawurldecode((string) $value);
}
if (!isset($parts['path'])) {
@@ -1453,8 +1453,8 @@ class Uri implements \Stringable
if (!function_exists('getallheaders')) {
$headers = [];
foreach ($_SERVER as $name => $value) {
if (str_starts_with($name, 'HTTP_')) {
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
if (str_starts_with((string) $name, 'HTTP_')) {
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr((string) $name, 5)))))] = $value;
}
}
return $headers;

View File

@@ -1264,7 +1264,7 @@ abstract class Utils
{
$newArray = [];
foreach ($array as $key => $value) {
$dots = explode($separator, $key);
$dots = explode($separator, (string) $key);
if (count($dots) > 1) {
$last = &$newArray[$dots[0]];
foreach ($dots as $k => $dot) {
@@ -1834,7 +1834,7 @@ abstract class Utils
}
foreach ($parts as $name => $value) {
$parts[$name] = urldecode($value);
$parts[$name] = urldecode((string) $value);
}
return $parts;

View File

@@ -181,7 +181,7 @@ class IndexCommand extends GpmCommand
{
$list = $this->gpm->{'getUpdatable' . ucfirst($package->package_type)}();
$package = $list[$package->slug] ?? $package;
$type = ucfirst(preg_replace('/s$/', '', $package->package_type));
$type = ucfirst(preg_replace('/s$/', '', (string) $package->package_type));
$updatable = $this->gpm->{'is' . $type . 'Updatable'}($package->slug);
$installed = $this->gpm->{'is' . $type . 'Installed'}($package->slug);
$local = $this->gpm->{'getInstalled' . $type}($package->slug);
@@ -266,21 +266,21 @@ class IndexCommand extends GpmCommand
// Filtering updatables only
if ($filter && ($this->options['installed-only'] || $this->options['enabled'] || $this->options['disabled'])) {
$method = ucfirst(preg_replace('/s$/', '', $package->package_type));
$method = ucfirst(preg_replace('/s$/', '', (string) $package->package_type));
$function = 'is' . $method . 'Installed';
$filter = $this->gpm->{$function}($package->slug);
}
// Filtering updatables only
if ($filter && $this->options['updates-only']) {
$method = ucfirst(preg_replace('/s$/', '', $package->package_type));
$method = ucfirst(preg_replace('/s$/', '', (string) $package->package_type));
$function = 'is' . $method . 'Updatable';
$filter = $this->gpm->{$function}($package->slug);
}
// Filtering enabled only
if ($filter && $this->options['enabled']) {
$method = ucfirst(preg_replace('/s$/', '', $package->package_type));
$method = ucfirst(preg_replace('/s$/', '', (string) $package->package_type));
// Check if packaged is enabled.
$function = 'is' . $method . 'Enabled';
@@ -289,7 +289,7 @@ class IndexCommand extends GpmCommand
// Filtering disabled only
if ($filter && $this->options['disabled']) {
$method = ucfirst(preg_replace('/s$/', '', $package->package_type));
$method = ucfirst(preg_replace('/s$/', '', (string) $package->package_type));
// Check if package is disabled.
$function = 'is' . $method . 'Enabled';

View File

@@ -83,11 +83,11 @@ class InfoCommand extends GpmCommand
return 1;
}
$io->writeln("Found package <cyan>'{$input->getArgument('package')}'</cyan> under the '<green>" . ucfirst($foundPackage->package_type) . "</green>' section");
$io->writeln("Found package <cyan>'{$input->getArgument('package')}'</cyan> under the '<green>" . ucfirst((string) $foundPackage->package_type) . "</green>' section");
$io->newLine();
$io->writeln("<cyan>{$foundPackage->name}</cyan> [{$foundPackage->slug}]");
$io->writeln(str_repeat('-', strlen($foundPackage->name) + strlen($foundPackage->slug) + 3));
$io->writeln('<white>' . strip_tags($foundPackage->description_plain) . '</white>');
$io->writeln(str_repeat('-', strlen($foundPackage->name) + strlen((string) $foundPackage->slug) + 3));
$io->writeln('<white>' . strip_tags((string) $foundPackage->description_plain) . '</white>');
$io->newLine();
$packageURL = '';
@@ -131,7 +131,7 @@ class InfoCommand extends GpmCommand
}
}
$type = rtrim($foundPackage->package_type, 's');
$type = rtrim((string) $foundPackage->package_type, 's');
$updatable = $this->gpm->{'is' . $type . 'Updatable'}($foundPackage->slug);
$installed = $this->gpm->{'is' . $type . 'Installed'}($foundPackage->slug);

View File

@@ -191,7 +191,7 @@ class UpdateCommand extends GpmCommand
// index
str_pad((string)$index++, 2, '0', STR_PAD_LEFT) . '. ' .
// name
'<cyan>' . str_pad($package->name, 15) . '</cyan> ' .
'<cyan>' . str_pad((string) $package->name, 15) . '</cyan> ' .
// version
"[v<magenta>{$package->version}</magenta> -> v<green>{$package->available}</green>]"
);

View File

@@ -61,7 +61,7 @@ class PluginListCommand extends ConsoleCommand
$index++;
$num = str_pad((string)$index, 2, '0', STR_PAD_LEFT);
$io->writeln(' ' . $num . '. <red>' . str_pad($name, 15) . "</red> <white>{$bin} {$name} list</white>");
$io->writeln(' ' . $num . '. <red>' . str_pad((string) $name, 15) . "</red> <white>{$bin} {$name} list</white>");
}
return 0;

View File

@@ -233,7 +233,7 @@ class FlexObject implements FlexObjectInterface, FlexAuthorizeInterface, \String
// Inject back elements which are missing in the filesystem.
$data = $this->getBlueprint()->flattenData($current);
foreach ($data as $property => $value) {
if (!str_contains($property, '.')) {
if (!str_contains((string) $property, '.')) {
$this->defProperty($property, $value);
} else {
$this->defNestedProperty($property, $value);

View File

@@ -195,7 +195,7 @@ class FlexPageCollection extends FlexCollection
$last = null;
$order = 0;
foreach ($keys as $folder => $key) {
preg_match(FlexPageIndex::ORDER_PREFIX_REGEX, $folder, $test);
preg_match(FlexPageIndex::ORDER_PREFIX_REGEX, (string) $folder, $test);
$test = $test[0] ?? null;
if ($test && $test > $order) {
$order = $test;

View File

@@ -635,7 +635,7 @@ trait PageLegacyTrait
// Build an array of meta objects..
foreach ($metadata as $key => $value) {
// Lowercase the key
$key = strtolower($key);
$key = strtolower((string) $key);
// If this is a property type metadata: "og", "twitter", "facebook" etc
// Backward compatibility for nested arrays in metas

View File

@@ -306,7 +306,7 @@ class FormFlash implements FormFlashInterface
{
$list = [];
foreach ($this->files as $field => $values) {
if (!$includeOriginal && strpos($field, '/')) {
if (!$includeOriginal && strpos((string) $field, '/')) {
continue;
}
$list[$field] = $this->getFilesByField($field);