[PHP 8.0] Add nette utils strings replace, static fixes (#4741)

Co-authored-by: rector-bot <tomas@getrector.org>
This commit is contained in:
Tomas Votruba 2020-12-01 14:52:24 +01:00 committed by GitHub
parent bb69160bd8
commit 2030badc19
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
36 changed files with 127 additions and 52 deletions

View File

@ -2,6 +2,8 @@
declare(strict_types=1);
use Rector\Generic\Rector\ClassMethod\ArgumentAdderRector;
use Rector\Generic\ValueObject\ArgumentAdder;
use Rector\Php80\Rector\Catch_\RemoveUnusedVariableInCatchRector;
use Rector\Php80\Rector\Class_\AnnotationToAttributeRector;
use Rector\Php80\Rector\Class_\ClassPropertyAssignToConstructorPromotionRector;
@ -15,6 +17,7 @@ use Rector\Php80\Rector\NotIdentical\StrContainsRector;
use Rector\Php80\Rector\Switch_\ChangeSwitchToMatchRector;
use Rector\Php80\Rector\Ternary\GetDebugTypeRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
@ -42,4 +45,12 @@ return static function (ContainerConfigurator $containerConfigurator): void {
$services->set(ClassPropertyAssignToConstructorPromotionRector::class);
$services->set(ChangeSwitchToMatchRector::class);
// nette\utils and Strings::replace()
$services->set(ArgumentAdderRector::class)
->call('configure', [[
ArgumentAdderRector::ADDED_ARGUMENTS => ValueObjectInliner::inline([
new ArgumentAdder('Nette\Utils\Strings', 'replace', 2, 'replacement', ''),
]),
]]);
};

View File

@ -41,7 +41,7 @@ trait ArrayPartPhpDocTagPrinterTrait
// should unquote
if ($this->isValueWithoutQuotes($key, $tagValueNodeConfiguration)) {
$content = Strings::replace($content, '#"#');
$content = Strings::replace($content, '#"#', '');
}
if ($tagValueNodeConfiguration->getOriginalContent() !== null && $key !== null) {

View File

@ -7,6 +7,7 @@ namespace Rector\BetterPhpDocParser\ValueObject\PhpDocNode\Doctrine\Class_;
use Rector\BetterPhpDocParser\Contract\PhpDocNode\SilentKeyNodeInterface;
use Rector\BetterPhpDocParser\ValueObject\OpeningAndClosingSpace;
use Rector\BetterPhpDocParser\ValueObject\PhpDocNode\Doctrine\AbstractDoctrineTagValueNode;
use Rector\Core\Exception\ShouldNotHappenException;
final class TableTagValueNode extends AbstractDoctrineTagValueNode implements SilentKeyNodeInterface
{
@ -31,12 +32,12 @@ final class TableTagValueNode extends AbstractDoctrineTagValueNode implements Si
private $uniqueConstraints = [];
/**
* @var OpeningAndClosingSpace
* @var OpeningAndClosingSpace|null
*/
private $indexesOpeningAndClosingSpace;
/**
* @var OpeningAndClosingSpace
* @var OpeningAndClosingSpace|null
*/
private $uniqueConstraintsOpeningAndClosingSpace;
@ -54,8 +55,8 @@ final class TableTagValueNode extends AbstractDoctrineTagValueNode implements Si
?string $originalContent = null,
bool $haveIndexesFinalComma = false,
bool $haveUniqueConstraintsFinalComma = false,
OpeningAndClosingSpace $indexesOpeningAndClosingSpace,
OpeningAndClosingSpace $uniqueConstraintsOpeningAndClosingSpace
?OpeningAndClosingSpace $indexesOpeningAndClosingSpace = null,
?OpeningAndClosingSpace $uniqueConstraintsOpeningAndClosingSpace = null
) {
$this->items['name'] = $name;
$this->items['schema'] = $schema;
@ -101,6 +102,10 @@ final class TableTagValueNode extends AbstractDoctrineTagValueNode implements Si
private function addCustomItems(array $items): array
{
if ($this->indexes !== []) {
if ($this->indexesOpeningAndClosingSpace === null) {
throw new ShouldNotHappenException();
}
$items['indexes'] = $this->printNestedTag(
$this->indexes,
$this->haveIndexesFinalComma,
@ -110,6 +115,10 @@ final class TableTagValueNode extends AbstractDoctrineTagValueNode implements Si
}
if ($this->uniqueConstraints !== []) {
if ($this->uniqueConstraintsOpeningAndClosingSpace === null) {
throw new ShouldNotHappenException();
}
$items['uniqueConstraints'] = $this->printNestedTag(
$this->uniqueConstraints,
$this->haveUniqueConstraintsFinalComma,

View File

@ -6,6 +6,7 @@ namespace Rector\BetterPhpDocParser\ValueObject\PhpDocNode\Doctrine\Property_;
use Rector\BetterPhpDocParser\ValueObject\OpeningAndClosingSpace;
use Rector\BetterPhpDocParser\ValueObject\PhpDocNode\Doctrine\AbstractDoctrineTagValueNode;
use Rector\Core\Exception\ShouldNotHappenException;
use Rector\PhpAttribute\Contract\ManyPhpAttributableTagNodeInterface;
use Rector\PhpAttribute\Contract\PhpAttributableTagNodeInterface;
@ -37,12 +38,12 @@ final class JoinTableTagValueNode extends AbstractDoctrineTagValueNode implement
private $inverseJoinColumns = [];
/**
* @var OpeningAndClosingSpace
* @var OpeningAndClosingSpace|null
*/
private $inverseJoinColumnsOpeningAndClosingSpace;
/**
* @var OpeningAndClosingSpace
* @var OpeningAndClosingSpace|null
*/
private $joinColumnsOpeningAndClosingSpace;
@ -61,8 +62,8 @@ final class JoinTableTagValueNode extends AbstractDoctrineTagValueNode implement
array $joinColumns = [],
array $inverseJoinColumns = [],
?string $originalContent = null,
OpeningAndClosingSpace $joinColumnsOpeningAndClosingSpace,
OpeningAndClosingSpace $inverseJoinColumnsOpeningAndClosingSpace
?OpeningAndClosingSpace $joinColumnsOpeningAndClosingSpace = null,
?OpeningAndClosingSpace $inverseJoinColumnsOpeningAndClosingSpace = null
) {
$this->name = $name;
$this->schema = $schema;
@ -150,6 +151,10 @@ final class JoinTableTagValueNode extends AbstractDoctrineTagValueNode implement
$items = [];
if ($this->joinColumns !== []) {
if ($this->joinColumnsOpeningAndClosingSpace === null) {
throw new ShouldNotHappenException();
}
$items[$joinColumnsKey] = $this->printNestedTag(
$this->joinColumns,
false,
@ -159,6 +164,10 @@ final class JoinTableTagValueNode extends AbstractDoctrineTagValueNode implement
}
if ($this->inverseJoinColumns !== []) {
if ($this->inverseJoinColumnsOpeningAndClosingSpace === null) {
throw new ShouldNotHappenException();
}
$items[$inverseJoinColumnsKey] = $this->printNestedTag(
$this->inverseJoinColumns,
false,

View File

@ -170,7 +170,7 @@ final class ConsoleOutputFormatter implements OutputFormatterInterface
private function normalizePathsToRelativeWithLine(string $errorMessage): string
{
$errorMessage = Strings::replace($errorMessage, '#' . preg_quote(getcwd(), '#') . '/#');
$errorMessage = Strings::replace($errorMessage, '#' . preg_quote(getcwd(), '#') . '/#', '');
return $errorMessage = Strings::replace($errorMessage, self::ON_LINE_REGEX, ':');
}

View File

@ -43,7 +43,7 @@ final class MarkdownDifferAndFormatter
$diff = $this->markdownDiffer->diff($old, $new);
// remove first line, just meta info added by UnifiedDiffOutputBuilder
$diff = Strings::replace($diff, self::METADATA_REGEX);
$diff = Strings::replace($diff, self::METADATA_REGEX, '');
return $this->removeTrailingWhitespaces($diff);
}

View File

@ -42,7 +42,9 @@ final class ClassChildAnalyzer
return false;
}
$classParents = class_parents($className);
/** @var string[] $classParents */
$classParents = (array) class_parents($className);
foreach ($classParents as $classParent) {
$parentReflectionClass = new ReflectionClass($classParent);
$constructMethodReflection = $parentReflectionClass->getConstructor();

View File

@ -136,15 +136,16 @@ final class ParsedClassConstFetchNodeCollector
{
$reflectionClass = new ReflectionClass($className);
$currentClassConstants = array_keys($reflectionClass->getConstants());
$constants = (array) $reflectionClass->getConstants();
$currentClassConstants = array_keys($constants);
$parentClassReflection = $reflectionClass->getParentClass();
if (! $parentClassReflection) {
return $currentClassConstants;
}
$parentClassConstants = array_keys($parentClassReflection->getConstants());
$parentClassConstants = array_keys($constants);
return array_diff($currentClassConstants, $parentClassConstants);
}
}

View File

@ -61,7 +61,7 @@ final class PHPStanServicesFactory
// Note: We need a unique file per process if rector runs in parallel
$pid = getmypid();
$temporaryPHPStanNeon = $currentWorkingDirectory . '/rector-temp-phpstan' . $pid . '.neon';
$clearedPhpstanNeonContent = Strings::replace($phpstanNeonContent, self::BLEEDING_EDGE_REGEX);
$clearedPhpstanNeonContent = Strings::replace($phpstanNeonContent, self::BLEEDING_EDGE_REGEX, '');
$smartFileSystem->dumpFile($temporaryPHPStanNeon, $clearedPhpstanNeonContent);
$additionalConfigFiles[] = $temporaryPHPStanNeon;

View File

@ -220,6 +220,6 @@ final class DocBlockManipulator
private function removeSpacesAndAsterisks(string $content): string
{
return Strings::replace($content, self::SPACE_OR_ASTERISK_REGEX);
return Strings::replace($content, self::SPACE_OR_ASTERISK_REGEX, '');
}
}

View File

@ -73,7 +73,7 @@ final class RectorSetProvider extends AbstractSetProvider
private function hydrateSetsFromConstants(ReflectionClass $setListReflectionClass): void
{
foreach ($setListReflectionClass->getConstants() as $name => $setPath) {
foreach ((array) $setListReflectionClass->getConstants() as $name => $setPath) {
if (! file_exists($setPath)) {
$message = sprintf('Set path "%s" was not found', $name);
throw new ShouldNotHappenException($message);

View File

@ -42,7 +42,9 @@ final class ClassMethodVendorLockResolver extends AbstractNodeVendorLockResolver
/** @var string $className */
$className = $classMethod->getAttribute(AttributeKey::CLASS_NAME);
$classParents = class_parents($className);
/** @var string[] $classParents */
$classParents = (array) class_parents($className);
foreach ($classParents as $classParent) {
if (! class_exists($classParent)) {
continue;

View File

@ -57,7 +57,8 @@ final class ClassMethodVisibilityVendorLockResolver extends AbstractNodeVendorLo
private function hasParentMethod(string $className, string $methodName): bool
{
$parentClasses = class_parents($className);
/** @var string[] $parentClasses */
$parentClasses = (array) class_parents($className);
foreach ($parentClasses as $parentClass) {
if (! method_exists($parentClass, $methodName)) {
@ -94,7 +95,8 @@ final class ClassMethodVisibilityVendorLockResolver extends AbstractNodeVendorLo
*/
private function getInterfaceMethodNames(string $className): array
{
$interfaces = class_implements($className);
/** @var string[] $interfaces */
$interfaces = (array) class_implements($className);
$interfaceMethods = [];
foreach ($interfaces as $interface) {

View File

@ -40,7 +40,8 @@ final class PropertyVisibilityVendorLockResolver extends AbstractNodeVendorLockR
private function hasParentProperty(string $className, string $propertyName): bool
{
$parentClasses = class_parents($className);
/** @var string[] $parentClasses */
$parentClasses = (array) class_parents($className);
foreach ($parentClasses as $parentClass) {
if (! property_exists($parentClass, $propertyName)) {

View File

@ -762,3 +762,9 @@ parameters:
# skip for final method, that cannot be overriden without static reflection
- '#Class "Rector\\Nette\\Rector\\Class_\\MoveFinalGetUserToCheckRequirementsClassMethodRector" is missing @see annotation with test case class reference#'
# Symfony spl file info false positive
- '#Parameter \#2 \$mode of method Symfony\\Component\\Filesystem\\Filesystem\:\:chmod\(\) expects int, int\|false given#'
- '#Parameter \#1 \$callback of function set_error_handler expects \(callable\(int, string, string, int, array\)\: bool\)\|null, \(array&callable\(\)\: mixed\)\|\(callable\(\)\: mixed&object\)\|\(callable\(\)\: mixed&string\) given#'
- '#Method Rector\\Privatization\\VisibilityGuard\\ClassMethodVisibilityGuard\:\:getParentClasses\(\) should return array<class\-string\> but returns array<int\|string, class\-string\|false\>#'
- '#Method Rector\\Privatization\\Rector\\Property\\PrivatizeFinalClassPropertyRector\:\:getParentClasses\(\) should return array<class\-string\> but returns array<int\|string, class\-string\|false\>#'

View File

@ -58,7 +58,7 @@ final class CakePHPFullyQualifiedClassNameResolver
// Chop Lib out as locations moves those files to the top level.
// But only if Lib is not the last folder.
if (Strings::match($pseudoNamespace, self::LIB_NAMESPACE_PART_REGEX)) {
$pseudoNamespace = Strings::replace($pseudoNamespace, '#\\\\Lib#');
$pseudoNamespace = Strings::replace($pseudoNamespace, '#\\\\Lib#', '');
}
// B. is Cake native class?

View File

@ -71,7 +71,7 @@ final class ClassNaming
// remove PHPUnit fixture file prefix
if (StaticPHPUnitEnvironment::isPHPUnitRun()) {
$basenameWithoutSuffix = Strings::replace($basenameWithoutSuffix, self::INPUT_HASH_NAMING_REGEX);
$basenameWithoutSuffix = Strings::replace($basenameWithoutSuffix, self::INPUT_HASH_NAMING_REGEX, '');
}
return StaticRectorStrings::underscoreToPascalCase($basenameWithoutSuffix);

View File

@ -89,7 +89,9 @@ CODE_SAMPLE
if ($this->shouldAddEmptyLine($currentStmtVariableName, $node, $key)) {
$hasChanged = true;
// insert newline before
array_splice($node->stmts, $key, 0, [new Nop()]);
$stmts = (array) $node->stmts;
array_splice($stmts, $key, 0, [new Nop()]);
$node->stmts = $stmts;
}
$this->previousPreviousStmtVariableName = $this->previousStmtVariableName;

View File

@ -99,7 +99,8 @@ final class ClassUnusedPrivateClassMethodResolver
/** @var string $className */
$className = $this->nodeNameResolver->getName($class);
$interfaces = class_implements($className);
/** @var string[] $interfaces */
$interfaces = (array) class_implements($className);
$interfaceMethods = [];
foreach ($interfaces as $interface) {
@ -119,7 +120,8 @@ final class ClassUnusedPrivateClassMethodResolver
return $unusedMethods;
}
$parentClasses = class_parents($class);
/** @var string[] $parentClasses */
$parentClasses = (array) class_parents($class);
$parentAbstractMethods = [];

View File

@ -110,7 +110,7 @@ final class EntityUuidNodeFactory
return;
}
$clearedDocCommentText = Strings::replace($docComment->getText(), self::ORM_VAR_DOC_LINE_REGEX);
$clearedDocCommentText = Strings::replace($docComment->getText(), self::ORM_VAR_DOC_LINE_REGEX, '');
$node->setDocComment(new Doc($clearedDocCommentText));
}

View File

@ -68,7 +68,7 @@ final class RegexMatcher
private function createPatternWithoutE(string $pattern, string $delimiter, string $modifiers): string
{
$modifiersWithoutE = Strings::replace($modifiers, '#e#');
$modifiersWithoutE = Strings::replace($modifiers, '#e#', '');
return Strings::before($pattern, $delimiter, -1) . $delimiter . $modifiersWithoutE;
}

View File

@ -113,6 +113,6 @@ CODE_SAMPLE
/** @var string $className */
$className = $this->getName($class);
return class_parents($className);
return (array) class_parents($className);
}
}

View File

@ -46,6 +46,6 @@ final class ClassMethodVisibilityGuard
/** @var string $className */
$className = $this->nodeNameResolver->getName($class);
return class_parents($className);
return (array) class_parents($className);
}
}

View File

@ -51,6 +51,6 @@ final class FileInfoDeletionAnalyzer
public function clearNameFromTestingPrefix(string $name): string
{
return Strings::replace($name, self::TESTING_PREFIX_REGEX);
return Strings::replace($name, self::TESTING_PREFIX_REGEX, '');
}
}

View File

@ -155,7 +155,9 @@ CODE_SAMPLE
return array_filter(
get_declared_classes(),
function (string $className) use ($interfaceName): bool {
return in_array($interfaceName, class_implements($className), true);
/** @var string[] $classImplements */
$classImplements = (array) class_implements($className);
return in_array($interfaceName, $classImplements, true);
}
);
}

View File

@ -90,7 +90,7 @@ final class TemplateGuesser
$bundle = $this->resolveBundle($class, $namespace);
$controller = $this->resolveController($class);
$action = Strings::replace($method, self::ACTION_MATCH_REGEX);
$action = Strings::replace($method, self::ACTION_MATCH_REGEX, '');
$fullPath = '';
if ($bundle !== '') {
@ -112,7 +112,7 @@ final class TemplateGuesser
}
$bundle = Strings::match($namespace, self::BUNDLE_NAME_MATCHING_REGEX)['bundle'] ?? '';
$bundle = Strings::replace($bundle, self::BUNDLE_SUFFIX_REGEX);
$bundle = Strings::replace($bundle, self::BUNDLE_SUFFIX_REGEX, '');
return $bundle !== '' ? '@' . $bundle : '';
}

View File

@ -112,7 +112,8 @@ CODE_SAMPLE
*/
private function getClassDirectInterfaces(string $typeName): array
{
$interfaceNames = class_implements($typeName);
/** @var string[] $interfaceNames */
$interfaceNames = (array) class_implements($typeName);
foreach ($interfaceNames as $possibleDirectInterfaceName) {
foreach ($interfaceNames as $key => $interfaceName) {
@ -143,7 +144,7 @@ CODE_SAMPLE
foreach ($interfaceNames as $key => $interfaceName) {
$implementations = [];
foreach ($classes as $class) {
$interfacesImplementedByClass = class_implements($class);
$interfacesImplementedByClass = (array) class_implements($class);
if (! in_array($interfaceName, $interfacesImplementedByClass, true)) {
continue;
}

View File

@ -40,7 +40,8 @@ final class ServiceMap
return null;
}
$interfaces = class_implements($class);
/** @var string[] $interfaces */
$interfaces = (array) class_implements($class);
foreach ($interfaces as $interface) {
// return first interface

View File

@ -21,7 +21,8 @@ final class FilesystemTweaker
foreach ($directories as $directory) {
// is fnmatch for directories
if (Strings::contains($directory, '*')) {
$absoluteDirectories = array_merge($absoluteDirectories, glob($directory, GLOB_ONLYDIR));
$foundDirectories = $this->foundDirectoriesInGlob($directory);
$absoluteDirectories = array_merge($absoluteDirectories, $foundDirectories);
} else {
// is classic directory
$this->ensureDirectoryExists($directory);
@ -32,6 +33,24 @@ final class FilesystemTweaker
return $absoluteDirectories;
}
/**
* @return string[]
*/
private function foundDirectoriesInGlob(string $directory): array
{
$foundDirectories = [];
foreach ((array) glob($directory, GLOB_ONLYDIR) as $foundDirectory) {
if (! is_string($foundDirectory)) {
continue;
}
$foundDirectories[] = $foundDirectory;
}
return $foundDirectories;
}
private function ensureDirectoryExists(string $directory): void
{
if (file_exists($directory)) {

View File

@ -61,7 +61,7 @@ final class TypeAnalyzer
$singleType = strtolower($singleType);
// remove [] from arrays
$singleType = Strings::replace($singleType, self::SQUARE_BRACKET_REGEX);
$singleType = Strings::replace($singleType, self::SQUARE_BRACKET_REGEX, '');
if (in_array($singleType, array_merge($this->phpSupportedTypes, self::EXTRA_TYPES), true)) {
return true;

View File

@ -188,7 +188,8 @@ final class ClassDependencyManipulator
*/
private function getParentClassPublicAndProtectedPropertyReflections(string $className): array
{
$parentClassNames = class_parents($className);
/** @var string[] $parentClassNames */
$parentClassNames = (array) class_parents($className);
$propertyReflections = [];

View File

@ -74,8 +74,9 @@ final class ClassManipulator
}
}
$implementedInterfaces = class_implements($class);
$implementedInterfaces = (array) class_implements($class);
foreach ($implementedInterfaces as $implementedInterface) {
/** @var string $implementedInterface */
if (method_exists($implementedInterface, $method)) {
return true;
}

View File

@ -121,8 +121,10 @@ final class ClassMethodManipulator
return true;
}
$implementedInterfaces = class_implements($class);
$implementedInterfaces = (array) class_implements($class);
foreach ($implementedInterfaces as $implementedInterface) {
/** @var string $implementedInterface */
if (method_exists($implementedInterface, $methodName)) {
return true;
}
@ -177,7 +179,8 @@ final class ClassMethodManipulator
private function isMethodInParent(string $class, string $method): bool
{
foreach (class_parents($class) as $parentClass) {
foreach ((array) class_parents($class) as $parentClass) {
/** @var string $parentClass */
if (method_exists($parentClass, $method)) {
return true;
}

View File

@ -67,7 +67,7 @@ final class IdentifierManipulator
if ($name === null) {
return;
}
$newName = Strings::replace($name, sprintf('#%s$#', $suffixToRemove));
$newName = Strings::replace($name, sprintf('#%s$#', $suffixToRemove), '');
$node->name = new Identifier($newName);
}

View File

@ -95,7 +95,7 @@ final class BetterStandardPrinter extends Standard
/**
* @param mixed[] $options
*/
public function __construct(CommentRemover $commentRemover, array $options = [], ContentPatcher $contentPatcher)
public function __construct(CommentRemover $commentRemover, ContentPatcher $contentPatcher, array $options = [])
{
parent::__construct($options);
@ -336,7 +336,7 @@ final class BetterStandardPrinter extends Standard
return $content;
}
return Strings::replace($content, self::EXTRA_SPACE_BEFORE_NOP_REGEX);
return Strings::replace($content, self::EXTRA_SPACE_BEFORE_NOP_REGEX, '');
}
/**
@ -485,7 +485,7 @@ final class BetterStandardPrinter extends Standard
{
$declareString = parent::pStmt_Declare($declare);
return Strings::replace($declareString, '#\s+#');
return Strings::replace($declareString, '#\s+#', '');
}
/**

View File

@ -32,15 +32,15 @@ final class CommentRemover
public function remove(string $content): string
{
// remove /** ... */
$content = Strings::replace($content, self::START_COMMENT_REGEX);
$content = Strings::replace($content, self::START_COMMENT_REGEX, '');
// remove /* ... */
$content = Strings::replace($content, self::START_COMMENT_REGEX);
$content = Strings::replace($content, self::START_COMMENT_REGEX, '');
// remove # ...
$content = Strings::replace($content, self::START_GRID_COMMENT_REGEX);
$content = Strings::replace($content, self::START_GRID_COMMENT_REGEX, '');
// remove // ...
return Strings::replace($content, self::START_DOUBLE_SLASH_COMMENT_REGEX);
return Strings::replace($content, self::START_DOUBLE_SLASH_COMMENT_REGEX, '');
}
}