Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

require __DIR__ . '/../Source/src/SomeClass.php';

$someClass = new \App\SomeClass();

?>
-----
<?php

$someClass = new \App\SomeClass();

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

$result = require __DIR__ . '/../Source/src/SomeClass.php';

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

require __DIR__ . '/../Source/src/TwoClasses.php';

$twoClasses = new \App\TwoClasses();

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

require __DIR__ . '/../Source/outside/LooseClass.php';

$looseClass = new \Outside\LooseClass();

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

declare(strict_types=1);

namespace Rector\Tests\DeadCode\Rector\Expression\RemovePsr4AutoloadedIncludeRector;

use Iterator;
use PHPUnit\Framework\Attributes\DataProvider;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;

final class RemovePsr4AutoloadedIncludeRectorTest extends AbstractRectorTestCase
{
#[DataProvider('provideData')]
public function test(string $filePath): void
{
$this->doTestFile($filePath);
}

public static function provideData(): Iterator
{
return self::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,7 @@
{
"autoload": {
"psr-4": {
"App\\": "src"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

declare(strict_types=1);

namespace Outside;

final class LooseClass
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

declare(strict_types=1);

namespace App;

final class SomeClass
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

declare(strict_types=1);

namespace App;

final class TwoClasses
{
}

final class SecondClass
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\DeadCode\Rector\Expression\RemovePsr4AutoloadedIncludeRector;

return RectorConfig::configure()
->withConfiguredRule(RemovePsr4AutoloadedIncludeRector::class, [
RemovePsr4AutoloadedIncludeRector::COMPOSER_JSON_PATH => __DIR__ . '/../Source/composer.json',
]);
214 changes: 214 additions & 0 deletions rules/DeadCode/Rector/Expression/RemovePsr4AutoloadedIncludeRector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
<?php

declare(strict_types=1);

namespace Rector\DeadCode\Rector\Expression;

use PhpParser\Node;
use PhpParser\Node\Expr\BinaryOp\Concat;
use PhpParser\Node\Expr\Include_;
use PhpParser\Node\Scalar\MagicConst\Dir;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt\ClassLike;
use PhpParser\Node\Stmt\Expression;
use PhpParser\NodeVisitor;
use Rector\Contract\Rector\ConfigurableRectorInterface;
use Rector\FileSystem\JsonFileSystem;
use Rector\PhpParser\Node\BetterNodeFinder;
use Rector\PhpParser\Parser\RectorParser;
use Rector\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;

/**
* @see \Rector\Tests\DeadCode\Rector\Expression\RemovePsr4AutoloadedIncludeRector\RemovePsr4AutoloadedIncludeRectorTest
*/
final class RemovePsr4AutoloadedIncludeRector extends AbstractRector implements ConfigurableRectorInterface
{
/**
* @api
*/
public const string COMPOSER_JSON_PATH = 'composer_json_path';

private ?string $composerJsonPath = null;

/**
* @var array<array{string, string}>|null list of [namespace prefix, absolute directory] pairs
*/
private ?array $psr4Prefixes = null;

public function __construct(
private readonly RectorParser $rectorParser,
private readonly BetterNodeFinder $betterNodeFinder
) {
}

/**
* @param array<string, mixed> $configuration
*/
public function configure(array $configuration): void
{
$composerJsonPath = $configuration[self::COMPOSER_JSON_PATH] ?? null;
$this->composerJsonPath = is_string($composerJsonPath) ? $composerJsonPath : null;
}

public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Remove include/require of a file that is already autoloaded via composer.json PSR-4',
[
new ConfiguredCodeSample(
<<<'CODE_SAMPLE'
require __DIR__ . '/src/SomeClass.php';

$someClass = new App\SomeClass();
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
$someClass = new App\SomeClass();
CODE_SAMPLE
,
[
self::COMPOSER_JSON_PATH => 'composer.json',
]
),
]
);
}

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

/**
* @param Expression $node
*/
public function refactor(Node $node): int|null
{
if (! $node->expr instanceof Include_) {
return null;
}

$includedFilePath = $this->resolveIncludedFilePath($node->expr);
if ($includedFilePath === null) {
return null;
}

if (! $this->isAutoloadedViaPsr4($includedFilePath)) {
return null;
}

return NodeVisitor::REMOVE_NODE;
}

private function resolveIncludedFilePath(Include_ $include): ?string
{
$currentDirectory = dirname($this->file->getFilePath());

// __DIR__ . '/relative/path.php'
if ($include->expr instanceof Concat && $include->expr->left instanceof Dir && $include->expr->right instanceof String_) {
return $this->realPath($currentDirectory . $include->expr->right->value);
}

if (! $include->expr instanceof String_) {
return null;
}

$rawPath = $include->expr->value;

// absolute path
if (str_starts_with($rawPath, '/')) {
return $this->realPath($rawPath);
}

return $this->realPath($currentDirectory . '/' . $rawPath);
}

private function realPath(string $path): ?string
{
if (! is_file($path)) {
return null;
}

return realpath($path);
}

private function isAutoloadedViaPsr4(string $includedFilePath): bool
{
$declaredClassName = $this->resolveSingleDeclaredClassName($includedFilePath);
if ($declaredClassName === null) {
return false;
}

foreach ($this->providePsr4Prefixes() as [$namespacePrefix, $directory]) {
if (! str_starts_with($declaredClassName, $namespacePrefix)) {
continue;
}

$relativeClassName = substr($declaredClassName, strlen($namespacePrefix));
$expectedFilePath = $this->realPath($directory . '/' . str_replace('\\', '/', $relativeClassName) . '.php');

if ($expectedFilePath === $includedFilePath) {
return true;
}
}

return false;
}

private function resolveSingleDeclaredClassName(string $filePath): ?string
{
$stmts = $this->rectorParser->parseFile($filePath);

$classLikes = $this->betterNodeFinder->findInstanceOf($stmts, ClassLike::class);

// require must define exactly one class, or removing it would drop the other definitions
if (count($classLikes) !== 1) {
return null;
}

// RichParser resolves names, so this is already the fully-qualified class name
return $this->getName($classLikes[0]);
}

/**
* @return array<array{string, string}> list of [namespace prefix, absolute directory] pairs
*/
private function providePsr4Prefixes(): array
{
if ($this->psr4Prefixes !== null) {
return $this->psr4Prefixes;
}

$composerJsonPath = $this->composerJsonPath ?? getcwd() . '/composer.json';
if (! is_file($composerJsonPath)) {
return $this->psr4Prefixes = [];
}

$composerJson = JsonFileSystem::readFilePath($composerJsonPath);
$rootDirectory = dirname($composerJsonPath);

$psr4Prefixes = [];
foreach (['autoload', 'autoload-dev'] as $autoloadSection) {
$psr4 = $composerJson[$autoloadSection]['psr-4'] ?? [];
if (! is_array($psr4)) {
continue;
}

foreach ($psr4 as $namespacePrefix => $directories) {
foreach ((array) $directories as $directory) {
$psr4Prefixes[] = [
(string) $namespacePrefix,
$rootDirectory . '/' . rtrim((string) $directory, '/'),
];
}
}
}

return $this->psr4Prefixes = $psr4Prefixes;
}
}
3 changes: 3 additions & 0 deletions structarmed.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
// no namespace on purpose
__DIR__ . '/rules-tests/Php70/Rector/ClassMethod/Php4ConstructorRector/Source/ParentClass.php',

// multiple classes in one file on purpose, to test the skip
__DIR__ . '/rules-tests/DeadCode/Rector/Expression/RemovePsr4AutoloadedIncludeRector/Source/src/TwoClasses.php',

// simulate under phpstan.phar
__DIR__ . '/rules-tests/Php71/Rector/FuncCall/RemoveExtraParametersRector/Source/phpstan.phar',
],
Expand Down
Loading