Skip to content

Commit

Permalink
[CodingStyle] Add DataProviderArrayItemsNewlinedRector (#3271)
Browse files Browse the repository at this point in the history
  • Loading branch information
TomasVotruba committed Jan 10, 2023
1 parent e8dd953 commit 58c8f17
Show file tree
Hide file tree
Showing 16 changed files with 281 additions and 26 deletions.
4 changes: 2 additions & 2 deletions packages/ChangesReporting/Output/ConsoleOutputFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,8 @@ private function reportRemovedFilesAndNodes(ProcessResult $processResult): void
private function normalizePathsToRelativeWithLine(string $errorMessage): string
{
$regex = '#' . preg_quote(getcwd(), '#') . '/#';
$errorMessage = Strings::replace($errorMessage, $regex, '');
return Strings::replace($errorMessage, self::ON_LINE_REGEX, ':');
$errorMessage = Strings::replace($errorMessage, $regex);
return Strings::replace($errorMessage, self::ON_LINE_REGEX);
}

private function reportRemovedNodes(ProcessResult $processResult): void
Expand Down
6 changes: 6 additions & 0 deletions packages/NodeTypeResolver/Node/AttributeKey.php
Original file line number Diff line number Diff line change
Expand Up @@ -186,4 +186,10 @@ final class AttributeKey
* @var string
*/
public const DOC_LABEL = 'docLabel';

/**
* Prints array in newlined fastion, one item per line
* @var string
*/
public const NEWLINED_ARRAY_PRINT = 'newlined_array_print';
}
3 changes: 3 additions & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -877,3 +877,6 @@ parameters:
-
message: '#"Tests" namespace cannot be used outside of "tests" directory#'
path: utils-tests

# trusted items
- '#Parameter \#1 \$nodes of method PhpParser\\PrettyPrinterAbstract\:\:pCommaSeparatedMultiline\(\) expects array<PhpParser\\Node>, array<PhpParser\\Node\\Expr\\ArrayItem\|null> given#'
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\CodingStyle\Rector\ClassMethod\DataProviderArrayItemsNewlinedRector;

use Iterator;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;

final class DataProviderArrayItemsNewlinedRectorTest extends AbstractRectorTestCase
{
/**
* @dataProvider provideData()
*/
public function test(string $filePath): void
{
$this->doTestFile($filePath);
}

/**
* @return Iterator<string>
*/
public function provideData(): Iterator
{
return $this->yieldFilesFromDirectory(__DIR__ . '/Fixture');
}

public function provideConfigFilePath(): string
{
return __DIR__ . '/config/configured_rule.php';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace Rector\Tests\CodingStyle\Rector\ClassMethod\DataProviderArrayItemsNewlinedRector\Fixture;

use PHPUnit\Framework\TestCase;

final class SkipNoArray extends TestCase
{
public function provideData(): array
{
return 'content' . 8;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace Rector\Tests\CodingStyle\Rector\ClassMethod\DataProviderArrayItemsNewlinedRector\Fixture;

final class SkipNonPhpUnit
{
public function provideData(): array
{
return [['content', 8], ['content123', 11]];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

namespace Rector\Tests\CodingStyle\Rector\ClassMethod\DataProviderArrayItemsNewlinedRector\Fixture;

use PHPUnit\Framework\TestCase;

final class ImageBinaryTest extends TestCase
{
/**
* @dataProvider provideData()
*/
public function testGetBytesSize(string $content, int $number): void
{
// ...
}

public function provideData(): array
{
return [['content', 8], ['content123', 11]];
}
}

?>
-----
<?php

namespace Rector\Tests\CodingStyle\Rector\ClassMethod\DataProviderArrayItemsNewlinedRector\Fixture;

use PHPUnit\Framework\TestCase;

final class ImageBinaryTest extends TestCase
{
/**
* @dataProvider provideData()
*/
public function testGetBytesSize(string $content, int $number): void
{
// ...
}

public function provideData(): array
{
return [
['content', 8],
['content123', 11],
];
}
}

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

declare(strict_types=1);

use Rector\CodingStyle\Rector\ClassMethod\DataProviderArrayItemsNewlinedRector;
use Rector\Config\RectorConfig;

return static function (RectorConfig $rectorConfig): void {
$rectorConfig->rule(DataProviderArrayItemsNewlinedRector::class);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
<?php

declare(strict_types=1);

namespace Rector\CodingStyle\Rector\ClassMethod;

use PhpParser\Node;
use PhpParser\Node\Expr\Array_;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Return_;
use Rector\Core\Rector\AbstractRector;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\PHPUnit\NodeAnalyzer\TestsNodeAnalyzer;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;

/**
* @see \Rector\Tests\CodingStyle\Rector\ClassMethod\DataProviderArrayItemsNewlinedRector\DataProviderArrayItemsNewlinedRectorTest
*/
final class DataProviderArrayItemsNewlinedRector extends AbstractRector
{
public function __construct(
private readonly TestsNodeAnalyzer $testsNodeAnalyzer
) {
}

public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Change data provider in PHPUnit test case to newline per item', [
new CodeSample(
<<<'CODE_SAMPLE'
use PHPUnit\Framework\TestCase;
final class ImageBinaryTest extends TestCase
{
/**
* @dataProvider provideData()
*/
public function testGetBytesSize(string $content, int $number): void
{
// ...
}
public function provideData(): array
{
return [['content', 8], ['content123', 11]];
}
}
CODE_SAMPLE

,
<<<'CODE_SAMPLE'
use PHPUnit\Framework\TestCase;
final class ImageBinaryTest extends TestCase
{
/**
* @dataProvider provideData()
*/
public function testGetBytesSize(string $content, int $number): void
{
// ...
}
public function provideData(): array
{
return [
['content', 8],
['content123', 11]
];
}
}
CODE_SAMPLE
),
]);
}

/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [ClassMethod::class];
}

/**
* @param ClassMethod $node
*/
public function refactor(Node $node): ?Node
{
if (! $node->isPublic()) {
return null;
}

if (! $this->testsNodeAnalyzer->isInTestClass($node)) {
return null;
}

// skip test methods
if ($this->isName($node, 'test*')) {
return null;
}

// find array in data provider - must contain a return node

/** @var Return_[] $returns */
$returns = $this->betterNodeFinder->findInstanceOf((array) $node->stmts, Return_::class);

$hasChanged = false;

foreach ($returns as $return) {
if (! $return->expr instanceof Array_) {
continue;
}

$array = $return->expr;
if ($array->items === []) {
continue;
}

// ensure newlined printed
$array->setAttribute(AttributeKey::NEWLINED_ARRAY_PRINT, true);

// invoke reprint
$array->setAttribute(AttributeKey::ORIGINAL_NODE, null);

$hasChanged = true;
}

if ($hasChanged) {
return $node;
}

return null;
}
}
14 changes: 1 addition & 13 deletions rules/Naming/Naming/PropertyNaming.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,18 +123,6 @@ public function fqnToVariableName(ThisType | ObjectType | string $objectType): s
return $this->prolongIfTooShort($variableName, $className);
}

/**
* @api symfony
* @see https://stackoverflow.com/a/2792045/1348344
*/
public function underscoreToName(string $underscoreName): string
{
$uppercaseWords = ucwords($underscoreName, '_');
$pascalCaseName = str_replace('_', '', $uppercaseWords);

return lcfirst($pascalCaseName);
}

private function resolveShortClassName(string $className): string
{
if (\str_contains($className, '\\')) {
Expand Down Expand Up @@ -273,7 +261,7 @@ private function normalizeShortClassName(string $shortClassName): string
}

// remove "_"
$shortClassName = Strings::replace($shortClassName, '#_#', '');
$shortClassName = Strings::replace($shortClassName, '#_#');
return $this->normalizeUpperCase($shortClassName);
}

Expand Down
2 changes: 1 addition & 1 deletion rules/PSR4/FileInfoAnalyzer/FileInfoDeletionAnalyzer.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,6 @@ public function isClassLikeAndFileInfoMatch(File $file, ClassLike $classLike): b

private function clearNameFromTestingPrefix(string $name): string
{
return Strings::replace($name, self::TESTING_PREFIX_REGEX, '');
return Strings::replace($name, self::TESTING_PREFIX_REGEX);
}
}
2 changes: 1 addition & 1 deletion rules/Php55/RegexMatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ private function resolveModifiers(string $modifiersCandidate): string

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;
}
Expand Down
9 changes: 2 additions & 7 deletions rules/Php73/Rector/String_/SensitiveHereNowDocRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,6 @@ final class SensitiveHereNowDocRector extends AbstractRector implements MinPhpVe
*/
private const WRAP_SUFFIX = '_WRAP';

/**
* @var string
*/
private const ATTRIBUTE_DOC_LABEL = 'docLabel';

public function provideMinPhpVersion(): int
{
return PhpVersionFeature::SENSITIVE_HERE_NOW_DOC;
Expand Down Expand Up @@ -76,13 +71,13 @@ public function refactor(Node $node): ?Node

// the doc label is not in the string → ok
/** @var string $docLabel */
$docLabel = $node->getAttribute(self::ATTRIBUTE_DOC_LABEL);
$docLabel = $node->getAttribute(AttributeKey::DOC_LABEL);

if (! \str_contains($node->value, $docLabel)) {
return null;
}

$node->setAttribute(self::ATTRIBUTE_DOC_LABEL, $this->uniquateDocLabel($node->value, $docLabel));
$node->setAttribute(AttributeKey::DOC_LABEL, $this->uniquateDocLabel($node->value, $docLabel));

// invoke redraw
$node->setAttribute(AttributeKey::ORIGINAL_NODE, null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ private function shouldSkipPropertyType(Type $propertyType): bool
if ($propertyType instanceof MixedType) {
return true;
}

return $this->isDoctrineCollectionType($propertyType);
}
}
11 changes: 9 additions & 2 deletions src/PhpParser/Printer/BetterStandardPrinter.php
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ protected function pArray(
return $content;
}

return Strings::replace($content, self::EXTRA_SPACE_BEFORE_NOP_REGEX, '');
return Strings::replace($content, self::EXTRA_SPACE_BEFORE_NOP_REGEX);
}

/**
Expand Down Expand Up @@ -313,6 +313,13 @@ protected function pExpr_Array(Array_ $array): string
$array->setAttribute(AttributeKey::KIND, Array_::KIND_SHORT);
}

if ($array->getAttribute(AttributeKey::NEWLINED_ARRAY_PRINT) === true) {
$printedArray = '[';
$printedArray .= $this->pCommaSeparatedMultiline($array->items, true);

return $printedArray . ($this->nl . ']');
}

return parent::pExpr_Array($array);
}

Expand Down Expand Up @@ -372,7 +379,7 @@ protected function pStmt_Declare(Declare_ $declare): string
{
$declareString = parent::pStmt_Declare($declare);

return Strings::replace($declareString, '#\s+#', '');
return Strings::replace($declareString, '#\s+#');
}

protected function pExpr_Ternary(Ternary $ternary): string
Expand Down
Loading

0 comments on commit 58c8f17

Please sign in to comment.