Replace StaticRectorStrings with Stringy class, remove CamelCaseFunctionNamingToUnderscoreRector to avoid naming rules (#5882)

This commit is contained in:
Tomas Votruba 2021-03-17 20:59:18 +01:00 committed by GitHub
parent 2be6607854
commit 69e66cbf1f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
22 changed files with 87 additions and 323 deletions

View File

@ -30,6 +30,7 @@
"ext-json": "*",
"composer/semver": "^3.2",
"composer/xdebug-handler": "^1.4",
"danielstjules/stringy": "^3.1",
"doctrine/annotations": "^1.12",
"doctrine/inflector": "^2.0",
"jean85/pretty-package-versions": "^1.5.1|^2.0.1",

View File

@ -19,7 +19,6 @@ use Rector\CodingStyle\Rector\FuncCall\CallUserFuncCallToVariadicRector;
use Rector\CodingStyle\Rector\FuncCall\ConsistentImplodeRector;
use Rector\CodingStyle\Rector\FuncCall\ConsistentPregDelimiterRector;
use Rector\CodingStyle\Rector\FuncCall\VersionCompareFuncCallToConstantRector;
use Rector\CodingStyle\Rector\Function_\CamelCaseFunctionNamingToUnderscoreRector;
use Rector\CodingStyle\Rector\If_\NullableCompareToNullRector;
use Rector\CodingStyle\Rector\Include_\FollowRequireByDirRector;
use Rector\CodingStyle\Rector\MethodCall\UseMessageVariableForSprintfInSymfonyStyleRector;
@ -74,7 +73,6 @@ return static function (ContainerConfigurator $containerConfigurator): void {
],
]]);
$services->set(CamelCaseFunctionNamingToUnderscoreRector::class);
$services->set(SplitGroupedUseImportsRector::class);
$services->set(RemoveDoubleUnderscoreInMethodNameRector::class);
$services->set(PostIncDecToPreIncDecRector::class);

View File

@ -6,11 +6,11 @@ namespace Rector\Set;
use Nette\Utils\Strings;
use Rector\Core\Exception\ShouldNotHappenException;
use Rector\Core\Util\StaticRectorStrings;
use Rector\Set\Contract\SetListInterface;
use Rector\Set\ValueObject\DowngradeSetList;
use Rector\Set\ValueObject\SetList;
use ReflectionClass;
use Stringy\Stringy;
use Symplify\SetConfigResolver\Exception\SetNotFoundException;
use Symplify\SetConfigResolver\Provider\AbstractSetProvider;
use Symplify\SetConfigResolver\ValueObject\Set;
@ -84,7 +84,8 @@ final class RectorSetProvider extends AbstractSetProvider
throw new ShouldNotHappenException($message);
}
$setName = StaticRectorStrings::constantToDashes($name);
$stringy = new Stringy($name);
$setName = (string) $stringy->dasherize();
// remove `-` before numbers
$setName = Strings::replace($setName, self::DASH_NUMBER_REGEX, '$1');

View File

@ -563,3 +563,16 @@ parameters:
- '*NodeVisitor.php'
- '#Class with base "NodeComparator" name is already used in "Symplify\\PHPStanRules\\Printer\\NodeComparator", "Rector\\Core\\PhpParser\\Comparing\\NodeComparator"\. Use unique name to make classes easy to recognize#'
-
message: '#Property with protected modifier is not allowed\. Use interface contract method instead#'
paths:
- packages/BetterPhpDocParser/PhpDocNodeFactory/AbstractPhpDocNodeFactory.php
# @todo fix in symplify
-
message: '#Do not use chained method calls\. Put each on separated lines#'
paths:
- rules/Symfony/ConstantNameAndValueMatcher.php
- rules/Privatization/Rector/Class_/ChangeReadOnlyVariableWithDefaultValueToConstantRector.php
- rules/Privatization/Naming/ConstantNaming.php

View File

@ -1,34 +0,0 @@
<?php
declare(strict_types=1);
namespace Rector\Tests\CodingStyle\Rector\Function_\CamelCaseFunctionNamingToUnderscoreRector;
use Iterator;
use Rector\CodingStyle\Rector\Function_\CamelCaseFunctionNamingToUnderscoreRector;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;
use Symplify\SmartFileSystem\SmartFileInfo;
final class CamelCaseFunctionNamingToUnderscoreRectorTest extends AbstractRectorTestCase
{
/**
* @dataProvider provideData()
*/
public function test(SmartFileInfo $fileInfo): void
{
$this->doTestFileInfo($fileInfo);
}
/**
* @return Iterator<SmartFileInfo>
*/
public function provideData(): Iterator
{
return $this->yieldFilesFromDirectory(__DIR__ . '/Fixture');
}
protected function getRectorClass(): string
{
return CamelCaseFunctionNamingToUnderscoreRector::class;
}
}

View File

@ -1,23 +0,0 @@
<?php
namespace Rector\Tests\CodingStyle\Rector\Function_\CamelCaseFunctionNamingToUnderscoreRector\Fixture;
function someCamelCaseFunction()
{
}
someCamelCaseFunction();
?>
-----
<?php
namespace Rector\Tests\CodingStyle\Rector\Function_\CamelCaseFunctionNamingToUnderscoreRector\Fixture;
function some_camel_case_function()
{
}
some_camel_case_function();
?>

View File

@ -1,11 +0,0 @@
<?php
namespace Rector\Tests\CodingStyle\Rector\Function_\CamelCaseFunctionNamingToUnderscoreRector\Fixture;
class SkipIsA
{
public function run()
{
return is_a($this, self::class);
}
}

View File

@ -19,7 +19,7 @@ class KeepPresenterName
/** @var string $presenterPart */
$presenterPart = Strings::substring($presenterPart, 0, -Strings::length('Presenter'));
$presenterPart = StaticRectorStrings::camelCaseToDashes($presenterPart);
$presenterPart = StaticRectorStrings::anything($presenterPart);
$match = (array) Strings::match($this->getName($classMethod), '#^(action|render)(?<short_action_name>.*?$)#sm');
$actionPart = lcfirst($match['short_action_name']);

View File

@ -12,8 +12,8 @@ use PhpParser\Node\Stmt\ClassLike;
use PhpParser\Node\Stmt\Property;
use PhpParser\Node\Stmt\PropertyProperty;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\Util\StaticRectorStrings;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Stringy\Stringy;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
@ -26,7 +26,7 @@ final class ChangeSnakedFixtureNameToPascalRector extends AbstractRector
{
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Changes $fixtues style from snake_case to PascalCase.', [
return new RuleDefinition('Changes $fixtures style from snake_case to PascalCase.', [
new CodeSample(
<<<'CODE_SAMPLE'
class SomeTest
@ -109,7 +109,8 @@ CODE_SAMPLE
$pascalCaseTableParts = array_map(
function (string $token): string {
return StaticRectorStrings::underscoreToPascalCase($token);
$stringy = new Stringy($token);
return (string) $stringy->upperCamelize();
},
$tableParts
);

View File

@ -9,8 +9,8 @@ use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use PhpParser\Node\Stmt\ClassLike;
use PhpParser\Node\Stmt\Function_;
use Rector\Core\Util\StaticRectorStrings;
use Rector\Testing\PHPUnit\StaticPHPUnitEnvironment;
use Stringy\Stringy;
use Symplify\SmartFileSystem\SmartFileInfo;
final class ClassNaming
@ -68,7 +68,8 @@ final class ClassNaming
$basenameWithoutSuffix = Strings::replace($basenameWithoutSuffix, self::INPUT_HASH_NAMING_REGEX, '');
}
return StaticRectorStrings::underscoreToPascalCase($basenameWithoutSuffix);
$stringy = new Stringy($basenameWithoutSuffix);
return (string) $stringy->upperCamelize();
}
/**
@ -77,7 +78,9 @@ final class ClassNaming
public function createMethodNameFromFunction(Function_ $function): string
{
$functionName = (string) $function->name;
return StaticRectorStrings::underscoreToCamelCase($functionName);
$stringy = new Stringy($functionName);
return (string) $stringy->camelize();
}
public function replaceSuffix(string $content, string $oldSuffix, string $newSuffix): string

View File

@ -1,97 +0,0 @@
<?php
declare(strict_types=1);
namespace Rector\CodingStyle\Rector\Function_;
use Nette\Utils\Strings;
use PhpParser\Node;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use PhpParser\Node\Stmt\Function_;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\Util\StaticRectorStrings;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @see \Rector\Tests\CodingStyle\Rector\Function_\CamelCaseFunctionNamingToUnderscoreRector\CamelCaseFunctionNamingToUnderscoreRectorTest
*/
final class CamelCaseFunctionNamingToUnderscoreRector extends AbstractRector
{
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Change CamelCase naming of functions to under_score naming',
[
new CodeSample(
<<<'CODE_SAMPLE'
function someCamelCaseFunction()
{
}
someCamelCaseFunction();
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
function some_camel_case_function()
{
}
some_camel_case_function();
CODE_SAMPLE
),
]);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [Function_::class, FuncCall::class];
}
/**
* @param Function_|FuncCall $node
*/
public function refactor(Node $node): ?Node
{
$shortName = $this->resolveShortName($node);
if ($shortName === null) {
return null;
}
$underscoredName = StaticRectorStrings::camelCaseToUnderscore($shortName);
if ($underscoredName === $shortName) {
return null;
}
if ($node instanceof FuncCall) {
$node->name = new Name($underscoredName);
} elseif ($node instanceof Function_) {
$node->name = new Identifier($underscoredName);
}
return $node;
}
/**
* @param Function_|FuncCall $node
*/
private function resolveShortName(Node $node): ?string
{
$functionOrFuncCallName = $this->getName($node);
if ($functionOrFuncCallName === null) {
return null;
}
$shortName = Strings::after($functionOrFuncCallName, '\\', -1);
if ($shortName === null) {
return $functionOrFuncCallName;
}
return $shortName;
}
}

View File

@ -5,13 +5,15 @@ declare(strict_types=1);
namespace Rector\NetteCodeQuality\Naming;
use Nette\Utils\Strings;
use Rector\Core\Util\StaticRectorStrings;
use Stringy\Stringy;
final class NetteControlNaming
{
public function createVariableName(string $shortName): string
{
$variableName = StaticRectorStrings::underscoreToCamelCase($shortName);
$stringy = new Stringy($shortName);
$variableName = (string) $stringy->camelize();
if (Strings::endsWith($variableName, 'Form')) {
return $variableName;
}
@ -21,6 +23,9 @@ final class NetteControlNaming
public function createCreateComponentClassMethodName(string $shortName): string
{
return 'createComponent' . StaticRectorStrings::underscoreToPascalCase($shortName);
$stringy = new Stringy($shortName);
$componentName = (string) $stringy->upperCamelize();
return 'createComponent' . $componentName;
}
}

View File

@ -26,9 +26,9 @@ use PHPStan\Type\Type;
use Rector\Core\Exception\NotImplementedYetException;
use Rector\Core\PhpParser\Node\Value\ValueResolver;
use Rector\Core\Util\StaticInstanceOf;
use Rector\Core\Util\StaticRectorStrings;
use Rector\NodeNameResolver\NodeNameResolver;
use Rector\NodeTypeResolver\NodeTypeResolver;
use Stringy\Stringy;
final class VariableNaming
{
@ -76,7 +76,8 @@ final class VariableNaming
$variableName = lcfirst($shortClassName);
}
return StaticRectorStrings::underscoreToCamelCase($variableName);
$stringy = new Stringy($variableName);
return (string) $stringy->camelize();
}
public function resolveFromNodeWithScopeCountAndFallbackName(
@ -211,7 +212,8 @@ final class VariableNaming
$valueName = $this->nodeNameResolver->getName($arrayDimFetch->var);
$dimName = $this->valueResolver->getValue($arrayDimFetch->dim);
$dimName = StaticRectorStrings::underscoreToPascalCase($dimName);
$stringy = new Stringy($dimName);
$dimName = (string) $stringy->upperCamelize();
return $valueName . $dimName;
}

View File

@ -15,11 +15,11 @@ use PHPStan\Type\ObjectType;
use Rector\BetterPhpDocParser\ValueObject\PhpDocNode\Symfony\SymfonyRouteTagValueNode;
use Rector\BetterPhpDocParser\ValueObjectFactory\PhpDocNode\Symfony\SymfonyRouteTagValueNodeFactory;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\Util\StaticRectorStrings;
use Rector\NetteToSymfony\Route\RouteInfoFactory;
use Rector\NetteToSymfony\Routing\ExplicitRouteAnnotationDecorator;
use Rector\NetteToSymfony\ValueObject\RouteInfo;
use Rector\TypeDeclaration\TypeInferer\ReturnTypeInferer;
use Stringy\Stringy;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
@ -319,7 +319,9 @@ CODE_SAMPLE
$presenterPart = Strings::after($presenterName, '\\', -1);
$presenterPart = Strings::substring($presenterPart, 0, -Strings::length('Presenter'));
$presenterPart = StaticRectorStrings::camelCaseToDashes($presenterPart);
$stringy = new Stringy($presenterPart);
$presenterPart = (string) $stringy->dasherize();
$match = (array) Strings::match($this->getName($classMethod), self::ACTION_RENDER_NAME_MATCHING_REGEX);
$actionPart = lcfirst($match['short_action_name']);

View File

@ -5,8 +5,8 @@ declare(strict_types=1);
namespace Rector\Privatization\Naming;
use PhpParser\Node\Stmt\PropertyProperty;
use Rector\Core\Util\StaticRectorStrings;
use Rector\NodeNameResolver\NodeNameResolver;
use Stringy\Stringy;
final class ConstantNaming
{
@ -23,8 +23,9 @@ final class ConstantNaming
public function createFromProperty(PropertyProperty $propertyProperty): string
{
$propertyName = $this->nodeNameResolver->getName($propertyProperty);
$constantName = StaticRectorStrings::camelCaseToUnderscore($propertyName);
return strtoupper($constantName);
$stringy = new Stringy($propertyName);
return (string) $stringy->underscored()
->toUpperCase();
}
}

View File

@ -19,9 +19,9 @@ use Rector\BetterPhpDocParser\PhpDocManipulator\VarAnnotationManipulator;
use Rector\Core\Exception\ShouldNotHappenException;
use Rector\Core\NodeManipulator\ClassMethodAssignManipulator;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\Util\StaticRectorStrings;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\PostRector\Collector\PropertyToAddCollector;
use Stringy\Stringy;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
@ -288,8 +288,8 @@ CODE_SAMPLE
throw new ShouldNotHappenException();
}
$constantName = StaticRectorStrings::camelCaseToUnderscore($variableName);
return strtoupper($constantName);
$stringy = new Stringy($variableName);
return (string) $stringy->underscored()
->toUpperCase();
}
}

View File

@ -262,6 +262,7 @@ CODE_SAMPLE
function (string $value): string {
return StaticRectorStrings::camelCaseToUnderscore($value);
},
$parts
);

View File

@ -7,8 +7,8 @@ namespace Rector\Symfony;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr\ClassConstFetch;
use Rector\Core\PhpParser\Node\Value\ValueResolver;
use Rector\Core\Util\StaticRectorStrings;
use Rector\Symfony\ValueObject\ConstantNameAndValue;
use Stringy\Stringy;
final class ConstantNameAndValueMatcher
{
@ -33,7 +33,9 @@ final class ConstantNameAndValueMatcher
return null;
}
$constantName = StaticRectorStrings::camelCaseToConstant($argumentValue);
$stringy = new Stringy($argumentValue);
$constantName = (string) $stringy->underscored()
->toUpperCase();
if (! ctype_alpha($constantName[0])) {
$constantName = $prefixForNumeric . $constantName;

View File

@ -13,8 +13,8 @@ use PhpParser\Node\Stmt\Return_;
use PHPStan\Type\ObjectType;
use Rector\Core\Exception\ShouldNotHappenException;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\Util\StaticRectorStrings;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Stringy\Stringy;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
@ -89,7 +89,9 @@ CODE_SAMPLE
$shortClassName = (string) Strings::before($shortClassName, 'Type');
}
$underscoredClassShortName = StaticRectorStrings::camelCaseToUnderscore($shortClassName);
$stringy = new Stringy($shortClassName);
$underscoredClassShortName = (string) $stringy->underscored();
if ($underscoredClassShortName !== $returnedValue) {
return null;
}

View File

@ -11,18 +11,30 @@ use Nette\Utils\Strings;
*/
final class StaticRectorStrings
{
/**
* @var string
* @see https://regex101.com/r/imzxhG/1
*/
private const UNDERSCORE_REGEX = '#_#';
/**
* @var string
* @see https://regex101.com/r/4w2of2/2
*/
private const CAMEL_CASE_SPLIT_REGEX = '#([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)#';
/**
* From: utf-8 to: UTF_8
*/
public static function camelCaseToUnderscore(string $input): string
{
if ($input === strtolower($input)) {
return $input;
}
$matches = Strings::matchAll($input, self::CAMEL_CASE_SPLIT_REGEX);
$parts = [];
foreach ($matches as $match) {
$parts[] = $match[0] === strtoupper($match[0]) ? strtolower($match[0]) : lcfirst($match[0]);
}
return implode('_', $parts);
}
/**
* @param string[] $array
*/
@ -37,43 +49,6 @@ final class StaticRectorStrings
return false;
}
public static function dashesToCamelCase(string $input): string
{
$parts = explode('-', $input);
$uppercasedParts = array_map('ucfirst', $parts);
return implode('', $uppercasedParts);
}
public static function camelCaseToDashes(string $input): string
{
return self::camelCaseToGlue($input, '-');
}
public static function camelCaseToUnderscore(string $input): string
{
return self::camelCaseToGlue($input, '_');
}
public static function underscoreToPascalCase(string $input): string
{
$parts = explode('_', $input);
$uppercasedParts = array_map('ucfirst', $parts);
return implode('', $uppercasedParts);
}
public static function underscoreToCamelCase(string $input): string
{
$input = self::underscoreToPascalCase($input);
return lcfirst($input);
}
public static function uppercaseUnderscoreToCamelCase(string $input): string
{
$input = strtolower($input);
return self::underscoreToCamelCase($input);
}
/**
* @param string[] $prefixesToRemove
*/
@ -101,37 +76,4 @@ final class StaticRectorStrings
return $value;
}
public static function camelToConstant(string $input): string
{
$underscore = self::camelCaseToGlue($input, '_');
return strtoupper($underscore);
}
public static function constantToDashes(string $string): string
{
$string = strtolower($string);
return Strings::replace($string, self::UNDERSCORE_REGEX, '-');
}
public static function camelCaseToConstant(string $input): string
{
$result = self::camelCaseToUnderscore($input);
return strtoupper($result);
}
private static function camelCaseToGlue(string $input, string $glue): string
{
if ($input === strtolower($input)) {
return $input;
}
$matches = Strings::matchAll($input, self::CAMEL_CASE_SPLIT_REGEX);
$parts = [];
foreach ($matches as $match) {
$parts[] = $match[0] === strtoupper($match[0]) ? strtolower($match[0]) : lcfirst($match[0]);
}
return implode($glue, $parts);
}
}

View File

@ -6,53 +6,9 @@ namespace Rector\Core\Tests\Util;
use Iterator;
use PHPUnit\Framework\TestCase;
use Rector\Core\Util\StaticRectorStrings;
final class StaticRectorStringsTest extends TestCase
{
/**
* @dataProvider provideDataForDashesToCamelCase()
*/
public function testDashesToCamelCase(string $content, string $expected): void
{
$this->assertSame($expected, StaticRectorStrings::dashesToCamelCase($content));
}
public function provideDataForDashesToCamelCase(): Iterator
{
yield ['simple-test', 'SimpleTest'];
yield ['easy', 'Easy'];
}
/**
* @dataProvider provideDataForCamelCaseToUnderscore()
*/
public function testCamelCaseToUnderscore(string $content, string $expected): void
{
$this->assertSame($expected, StaticRectorStrings::camelCaseToUnderscore($content));
}
public function provideDataForCamelCaseToUnderscore(): Iterator
{
yield ['simpleTest', 'simple_test'];
yield ['easy', 'easy'];
yield ['HTML', 'html'];
yield ['simpleXML', 'simple_xml'];
yield ['PDFLoad', 'pdf_load'];
yield ['startMIDDLELast', 'start_middle_last'];
yield ['AString', 'a_string'];
yield ['Some4Numbers234', 'some4_numbers234'];
yield ['TEST123String', 'test123_string'];
}
/**
* @dataProvider provideDataForUnderscoreToCamelCase()
*/
public function testUnderscoreToCamelCase(string $content, string $expected): void
{
$this->assertSame($expected, StaticRectorStrings::underscoreToCamelCase($content));
}
/**
* @return Iterator<string[]>
*/
@ -61,14 +17,6 @@ final class StaticRectorStringsTest extends TestCase
yield ['simple_test', 'simpleTest'];
}
/**
* @dataProvider provideDataForUnderscoreToPascalCase()
*/
public function testUnderscoreToPascalCase(string $content, string $expected): void
{
$this->assertSame($expected, StaticRectorStrings::underscoreToPascalCase($content));
}
/**
* @return Iterator<string[]>
*/

View File

@ -1,4 +1,11 @@
services:
-
class: Symplify\PHPStanRules\ObjectCalisthenics\Rules\NoChainMethodCallRule
tags: [phpstan.rules.rule]
arguments:
allowedChainTypes:
- Stringy\Stringy
-
class: Symplify\PHPStanRules\Rules\NoInheritanceRule
tags: [phpstan.rules.rule]