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
22 changes: 22 additions & 0 deletions .github/workflows/e2e_with_cache.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,25 @@ jobs:
# this tests that a 2nd run with cache and "--dry-run" gives same results, see https://github.com/rectorphp/rector-src/pull/3614#issuecomment-1507742338
- run: php ../e2eTestRunnerWithCache.php
working-directory: ${{ matrix.directory }}

cache_meta_extension:
runs-on: ubuntu-latest
timeout-minutes: 3

name: End to end test - e2e/cache-meta-extension

steps:
- uses: actions/checkout@v4

- uses: shivammathur/setup-php@v2
with:
php-version: '8.3'
coverage: none

- run: composer install --ansi

- run: composer install --ansi
working-directory: e2e/cache-meta-extension

- run: php e2eTestRunnerCacheInvalidation.php
working-directory: e2e/cache-meta-extension
1 change: 1 addition & 0 deletions e2e/cache-meta-extension/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/vendor
12 changes: 12 additions & 0 deletions e2e/cache-meta-extension/composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"require": {
"php": "^8.1"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"minimum-stability": "dev",
"prefer-stable": true
}
66 changes: 66 additions & 0 deletions e2e/cache-meta-extension/e2eTestRunnerCacheInvalidation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
#!/usr/bin/env php
<?php

// Tests that CacheMetaExtensionInterface invalidates cache when the hash changes.
//
// Step 1: Run Rector with enabled.txt=false and --clear-cache → no changes, cache populated
// Step 2: Change enabled.txt to true → cache invalidated → rule triggers → changes reported

use Rector\Console\Formatter\ColorConsoleDiffFormatter;
use Rector\Console\Style\SymfonyStyleFactory;
use Rector\Differ\DefaultDiffer;
use Rector\Util\Reflection\PrivatesAccessor;
use Symfony\Component\Console\Command\Command;

$projectRoot = __DIR__ .'/..';
$rectorBin = $projectRoot . '/../bin/rector';
$autoloadFile = $projectRoot . '/../vendor/autoload.php';

require_once __DIR__ . '/../../vendor/autoload.php';

$symfonyStyleFactory = new SymfonyStyleFactory(new PrivatesAccessor());
$symfonyStyle = $symfonyStyleFactory->create();

$e2eCommand = 'php '. $rectorBin .' process --dry-run --no-ansi -a '. $autoloadFile;

// Step 1: enabled=false, clear cache → no changes
file_put_contents(__DIR__ . '/enabled.txt', "false\n");

$output = [];
exec($e2eCommand . ' --clear-cache', $output, $exitCode);
$outputString = trim(implode("\n", $output));

if (! str_contains($outputString, '[OK] Rector is done!')) {
$symfonyStyle->error('Step 1 failed: Expected no changes with enabled=false');
$symfonyStyle->writeln($outputString);
exit(Command::FAILURE);
}

$symfonyStyle->success('Step 1 passed: No changes with enabled=false');

// Step 2: enabled=true, no --clear-cache → cache meta invalidated → rule triggers
file_put_contents(__DIR__ . '/enabled.txt', "true\n");

$output = [];
exec($e2eCommand, $output, $exitCode);
$outputString = trim(implode("\n", $output));
$outputString = str_replace(__DIR__, '.', $outputString);

$expectedOutput = trim((string) file_get_contents(__DIR__ . '/expected-output.diff'));

// Restore enabled.txt
file_put_contents(__DIR__ . '/enabled.txt', "false\n");

if ($outputString === $expectedOutput) {
$symfonyStyle->success('Step 2 passed: Cache invalidated, rule triggered');
exit(Command::SUCCESS);
}

$symfonyStyle->error('Step 2 failed: Expected cache invalidation to trigger the rule');

$defaultDiffer = new DefaultDiffer();
$colorConsoleDiffFormatter = new ColorConsoleDiffFormatter();
$diff = $colorConsoleDiffFormatter->format($defaultDiffer->diff($outputString, $expectedOutput));
$symfonyStyle->writeln($diff);

exit(Command::FAILURE);
1 change: 1 addition & 0 deletions e2e/cache-meta-extension/enabled.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
false
21 changes: 21 additions & 0 deletions e2e/cache-meta-extension/expected-output.diff
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
1 file with changes
===================

1) src/DeadConstructor.php:2

---------- begin diff ----------
@@ @@

final class DeadConstructor
{
- public function __construct()
- {
- }
}
----------- end diff -----------

Applied rules:
* ConditionalEmptyConstructorRector


[OK] 1 file would have been changed (dry-run) by Rector
21 changes: 21 additions & 0 deletions e2e/cache-meta-extension/rector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

declare(strict_types=1);

use App\ConditionalEmptyConstructorRector;
use App\EnabledFlagCacheMetaExtension;
use Rector\Caching\ValueObject\Storage\FileCacheStorage;
use Rector\Config\RectorConfig;

require_once __DIR__ . '/vendor/autoload.php';

return static function (RectorConfig $rectorConfig): void {
$rectorConfig->cacheClass(FileCacheStorage::class);

$rectorConfig->paths([
__DIR__ . '/src/DeadConstructor.php',
]);

$rectorConfig->rule(ConditionalEmptyConstructorRector::class);
$rectorConfig->cacheMetaExtension(EnabledFlagCacheMetaExtension::class);
};
86 changes: 86 additions & 0 deletions e2e/cache-meta-extension/src/ConditionalEmptyConstructorRector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
<?php

declare(strict_types=1);

namespace App;

use PhpParser\Node;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use Rector\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;

/**
* Removes empty constructors only when enabled.txt contains "true".
* Used to test CacheMetaExtensionInterface e2e.
*/
final class ConditionalEmptyConstructorRector extends AbstractRector
{
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Remove empty constructors conditionally', [
new CodeSample(
<<<'CODE_SAMPLE'
class SomeClass
{
public function __construct()
{
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
class SomeClass
{
}
CODE_SAMPLE
),
]);
}

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

/**
* @param Class_ $node
*/
public function refactor(Node $node): ?Class_
{
$enabled = trim((string) file_get_contents(__DIR__ . '/../enabled.txt'));

if ($enabled !== 'true') {
return null;
}

$hasChanged = false;

foreach ($node->stmts as $key => $stmt) {
if (! $stmt instanceof ClassMethod) {
continue;
}

if (! $this->isName($stmt, '__construct')) {
continue;
}

if ($stmt->stmts !== null && $stmt->stmts !== []) {
continue;
}

unset($node->stmts[$key]);
$hasChanged = true;
}

if ($hasChanged) {
return $node;
}

return null;
}
}
8 changes: 8 additions & 0 deletions e2e/cache-meta-extension/src/DeadConstructor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

final class DeadConstructor
{
public function __construct()
{
}
}
20 changes: 20 additions & 0 deletions e2e/cache-meta-extension/src/EnabledFlagCacheMetaExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

declare(strict_types=1);

namespace App;

use Rector\Caching\Contract\CacheMetaExtensionInterface;

final class EnabledFlagCacheMetaExtension implements CacheMetaExtensionInterface
{
public function getKey(): string
{
return 'enabled-flag';
}

public function getHash(): string
{
return (string) file_get_contents(__DIR__ . '/../enabled.txt');
}
}
22 changes: 21 additions & 1 deletion src/Caching/Config/FileHashComputer.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Rector\Caching\Config;

use Rector\Application\VersionResolver;
use Rector\Caching\Contract\CacheMetaExtensionInterface;
use Rector\Configuration\Parameter\SimpleParameterProvider;
use Rector\Exception\ShouldNotHappenException;

Expand All @@ -13,12 +14,31 @@
*/
final class FileHashComputer
{
/**
* @param CacheMetaExtensionInterface[] $cacheMetaExtensions
*/
public function __construct(
private readonly array $cacheMetaExtensions = []
) {
}

public function compute(string $filePath): string
{
$this->ensureIsPhp($filePath);

$parametersHash = SimpleParameterProvider::hash();
return sha1($filePath . $parametersHash . VersionResolver::PACKAGE_VERSION);
$extensionHash = $this->computeExtensionHash();
return sha1($filePath . $parametersHash . $extensionHash . VersionResolver::PACKAGE_VERSION);
}

private function computeExtensionHash(): string
{
$extensionHash = '';
foreach ($this->cacheMetaExtensions as $cacheMetaExtension) {
$extensionHash .= $cacheMetaExtension->getKey() . ':' . $cacheMetaExtension->getHash();
}

return $extensionHash;
}

private function ensureIsPhp(string $filePath): void
Expand Down
26 changes: 26 additions & 0 deletions src/Caching/Contract/CacheMetaExtensionInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

namespace Rector\Caching\Contract;

/**
* Allows extensions to provide additional metadata for cache invalidation.
* When any extension's hash changes, all cached files are reprocessed.
*
* @api
*/
interface CacheMetaExtensionInterface
{
/**
* Returns unique key for this cache meta entry.
* This describes the source of the metadata.
*/
public function getKey(): string;

/**
* Returns hash of the cache meta entry.
* This represents the current state of the additional meta source.
*/
public function getHash(): string;
}
12 changes: 12 additions & 0 deletions src/Config/RectorConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Illuminate\Container\Container;
use Override;
use Rector\Caching\Contract\CacheMetaExtensionInterface;
use Rector\Caching\Contract\ValueObject\Storage\CacheStorageInterface;
use Rector\Configuration\Option;
use Rector\Configuration\Parameter\SimpleParameterProvider;
Expand Down Expand Up @@ -360,6 +361,17 @@ public function cacheClass(string $cacheClass): void
SimpleParameterProvider::setParameter(Option::CACHE_CLASS, $cacheClass);
}

/**
* @param class-string<CacheMetaExtensionInterface> $cacheMetaExtensionClass
*/
public function cacheMetaExtension(string $cacheMetaExtensionClass): void
{
Assert::isAOf($cacheMetaExtensionClass, CacheMetaExtensionInterface::class);

$this->singleton($cacheMetaExtensionClass);
$this->tag($cacheMetaExtensionClass, CacheMetaExtensionInterface::class);
}

/**
* @see https://github.com/nikic/PHP-Parser/issues/723#issuecomment-712401963
*/
Expand Down
Loading
Loading