PHP code example of amashukov / rector-php-rules

1. Go to this page and download the library: Download amashukov/rector-php-rules library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

amashukov / rector-php-rules example snippets




declare(strict_types=1);

use Amashukov\RectorRules\NoArrayAssertContainsInTestsRector;
use Amashukov\RectorRules\NoAssertCallInSrcRector;
use Amashukov\RectorRules\NoAssertInsideIfInFunctionalTestsRector;
use Amashukov\RectorRules\NoCommentsOutsideInterfaceMethodDocBlockRector;
use Amashukov\RectorRules\NoDirectDbMutationInFunctionalTestsRector;
use Amashukov\RectorRules\NoDirectDispatchInFunctionalTestsRector;
use Amashukov\RectorRules\NoEnvironmentCheckInSrcRector;
use Amashukov\RectorRules\NoExistenceOnlyAssertionsInTestsRector;
use Amashukov\RectorRules\NoNullCoalesceNewFallbackRector;
use Amashukov\RectorRules\NoSilentFallbackRector;
use Amashukov\RectorRules\NoPhpstanIgnoreRector;
use Amashukov\RectorRules\NoSuperglobalAccessRector;
use Amashukov\RectorRules\NoTodoCommentRector;
use Amashukov\RectorRules\NoTypeOnlyAssertionsInTestsRector;
use Amashukov\RectorRules\RequirePsrClockInterfaceRector;
use Amashukov\RectorRules\Yaml\YamlCommentStripper;
use Amashukov\RectorRules\Yaml\YamlCommentStripperInterface;
use Amashukov\RectorRules\Yaml\YamlNoCommentsChecker;
use Amashukov\RectorRules\Yaml\YamlNoCommentsCheckerInterface;
use Amashukov\RectorRules\Yaml\YamlNoCommentsRector;
use Rector\Config\RectorConfig;

return RectorConfig::configure()
    ->registerService(YamlNoCommentsChecker::class, YamlNoCommentsCheckerInterface::class)
    ->registerService(YamlCommentStripper::class, YamlCommentStripperInterface::class)
    ->withPaths([__DIR__ . '/src', __DIR__ . '/tests'])
    ->withRules([
        NoCommentsOutsideInterfaceMethodDocBlockRector::class,
        NoPhpstanIgnoreRector::class,
        NoSuperglobalAccessRector::class,
        NoEnvironmentCheckInSrcRector::class,
        NoAssertCallInSrcRector::class,
        NoAssertInsideIfInFunctionalTestsRector::class,
        NoArrayAssertContainsInTestsRector::class,
        NoTypeOnlyAssertionsInTestsRector::class,
        NoExistenceOnlyAssertionsInTestsRector::class,
        RequirePsrClockInterfaceRector::class,
        NoDirectDbMutationInFunctionalTestsRector::class,
        NoDirectDispatchInFunctionalTestsRector::class,
        NoNullCoalesceNewFallbackRector::class,
        NoSilentFallbackRector::class,
        NoTodoCommentRector::class,
    ])
    ->withConfiguredRule(YamlNoCommentsRector::class, [
        YamlNoCommentsRector::PATHS => [__DIR__ . '/config'],
    ]);

// BAD
final class Foo
{
    /** why this constant exists */
    private const int X = 1;

    /**
     * Multi-line prose about what doX does.
     */
    public function doX(): void
    {
        // step 1 — fetch
        $this->y();
    }
}

// GOOD
final class Foo
{
    private const int X = 1;

    public function doX(): void
    {
        $this->y();
    }
}

// BAD
// @phpstan-ignore-next-line
$foo->bar();

// GOOD
if ($foo instanceof Bar) {
    $foo->bar();
}

// BAD
$apiKey = $_ENV['API_KEY'] ?? getenv('API_KEY');

// GOOD
$apiKey = $this->apiKey; // injected by DI from container configuration

// BAD
if ('test' !== ($_ENV['APP_ENV'] ?? '')) {
    return new JsonResponse(['error' => 'not_found'], 404);
}

// GOOD
// gate the route at the config layer (env-scoped route loader / DI compiler pass) instead.

// BAD
\assert($value instanceof Foo || $value instanceof Bar);
$value->doThing();

// GOOD
if (!$value instanceof Foo && !$value instanceof Bar) {
    throw new \LogicException(sprintf('unsupported %s', $value::class));
}
$value->doThing();

// BAD
if (Status::READY === $entity->getStatus()) {
    $entity = $this->advance($entity);
    self::assertNotNull($entity);
}

// GOOD
$entity = $this->driveReadyToActive($entity);
self::assertSame(Status::ACTIVE, $entity->getStatus());

// BAD
self::assertContains($entity->getStatus(), [Status::READY, Status::DONE]);

// GOOD
// pin the production path so it reaches ONE deterministic state, then:
self::assertSame(Status::DONE, $entity->getStatus());

// BAD
self::assertIsArray($body['data']);
self::assertIsString($json['id']);

// GOOD
self::assertSame(['enabled' => true, 'count' => 3], $body['data']);
self::assertSame('a1b2c3d4-...', $json['id']);

// BAD
self::assertNotNull($entity->getCompletedAt());
self::assertNotEmpty($body['items']);
self::assertArrayHasKey('id', $body);

// GOOD
self::assertSame('2026-05-21T12:00:00+00:00', $entity->getCompletedAt()?->format(DateTimeInterface::ATOM));
self::assertSame(3, count($body['items']));
self::assertSame('a1b2c3d4-...', $body['id']);

// BAD
$age = time() - (int) $stored;
$expires = new DateTimeImmutable('+1 day');

// GOOD
$age = $this->clock->now()->getTimestamp() - (int) $stored;
$expires = $this->clock->now()->modify('+1 day');

// BAD
$em->remove($entity);
$em->flush();

// GOOD
$this->client->request('POST', '/api/entity/' . $entity->getId() . '/cancel');

// BAD
$container->get('event_dispatcher')->dispatch(new MyEvent(...));

// GOOD
// Mock the outbound adapter; let the real dispatcher emit the event end-to-end.

// BAD
public function __construct(?Clock $clock = null)
{
    $this->clock = $clock ?? new SystemClock();
}

// GOOD
public function __construct(private readonly Clock $clock)
{
}

// BAD
$env  = $_ENV['APP_ENV'] ?? 'dev';
$port = $config['port'] ?? 8080;
$items ??= [];
$name = isset($user['name']) ? $user['name'] : 'anonymous';
$title = $row['title'] ?: 'Untitled';

// GOOD
$env  = self::has no name');
}
$name = $user['name'];

->withSkip([
    NoSilentFallbackRector::class => [__DIR__ . '/src/Entity'],
])

// BAD
// TODO(@alice): switch to the pooled client once PROJ-123 lands
$client = new Client();

// GOOD
$client = new PooledClient();

use Amashukov\RectorRules\Yaml\YamlCommentStripper;
use Amashukov\RectorRules\Yaml\YamlCommentStripperInterface;
use Amashukov\RectorRules\Yaml\YamlNoCommentsChecker;
use Amashukov\RectorRules\Yaml\YamlNoCommentsCheckerInterface;
use Amashukov\RectorRules\Yaml\YamlNoCommentsRector;
use Rector\Config\RectorConfig;

return RectorConfig::configure()
    ->registerService(YamlNoCommentsChecker::class, YamlNoCommentsCheckerInterface::class)
    ->registerService(YamlCommentStripper::class, YamlCommentStripperInterface::class)
    ->withConfiguredRule(YamlNoCommentsRector::class, [
        YamlNoCommentsRector::PATHS => [__DIR__ . '/config'],
        // Optional. Default: ['yaml', 'yml']
        // YamlNoCommentsRector::EXTENSIONS => ['yaml', 'yml', 'neon'],
    ]);