Skip to content

Latest commit

 

History

History
4881 lines (3479 loc) · 71.2 KB

rules_overview.md

File metadata and controls

4881 lines (3479 loc) · 71.2 KB

129 Rules Overview

AnnotateRegexClassConstWithRegexLinkRule

Add regex101.com link to that shows the regex in practise, so it will be easier to maintain in case of bug/extension in the future

class SomeClass
{
    private const COMPLICATED_REGEX = '#some_complicated_stu|ff#';
}


class SomeClass
{
    /**
     * @see https://regex101.com/r/SZr0X5/12
     */
    private const COMPLICATED_REGEX = '#some_complicated_stu|ff#';
}

👍


BoolishClassMethodPrefixRule

Method "%s()" returns bool type, so the name should start with is/has/was...

class SomeClass
{
    public function old(): bool
    {
        return $this->age > 100;
    }
}


class SomeClass
{
    public function isOld(): bool
    {
        return $this->age > 100;
    }
}

👍


CheckAttributteArgumentClassExistsRule

Class was not found

#[SomeAttribute(firstName: 'MissingClass::class')]
class SomeClass
{
}


#[SomeAttribute(firstName: ExistingClass::class)]
class SomeClass
{
}

👍


CheckClassNamespaceFollowPsr4Rule

Class like namespace "%s" does not follow PSR-4 configuration in composer.json

// defined "Foo\Bar" namespace in composer.json > autoload > psr-4
namespace Foo;

class Baz
{
}


// defined "Foo\Bar" namespace in composer.json > autoload > psr-4
namespace Foo\Bar;

class Baz
{
}

👍


CheckConstantExpressionDefinedInConstructOrSetupRule

Move constant expression to __construct(), setUp() method or constant

class SomeClass
{
    public function someMethod()
    {
        $mainPath = getcwd() . '/absolute_path';
        return __DIR__ . $mainPath;
    }
}


class SomeClass
{
    private $mainPath;

    public function __construct()
    {
        $this->mainPath = getcwd() . '/absolute_path';
    }

    public function someMethod()
    {
        return $this->mainPath;
    }
}

👍


CheckNotTestsNamespaceOutsideTestsDirectoryRule

"*Test.php" file cannot be located outside "Tests" namespace

// file: "SomeTest.php
namespace App;

class SomeTest
{
}


// file: "SomeTest.php
namespace App\Tests;

class SomeTest
{
}

👍


CheckReferencedClassInAnnotationRule

Class "%s" used in annotation is missing

/**
 * @SomeAnnotation(value=MissingClass::class)
 */
class SomeClass
{
}


/**
 * @SomeAnnotation(value=ExistingClass::class)
 */
class SomeClass
{
}

👍


CheckRequiredInterfaceInContractNamespaceRule

Interface must be located in "Contract" namespace

namespace App\Repository;

interface ProductRepositoryInterface
{
}


namespace App\Contract\Repository;

interface ProductRepositoryInterface
{
}

👍


CheckRequiredMethodNamingRule

Autowired/inject method name "%s()" must respect "autowire/inject(*)" name

use Symfony\Contracts\Service\Attribute\Required;

final class SomeClass
{
    #[Required]
    public function install(...)
    {
        // ...
    }
}


use Symfony\Contracts\Service\Attribute\Required;

final class SomeClass
{
    #[Required]
    public function autowire(...)
    {
        // ...
    }
}

👍


CheckSprinfMatchingTypesRule

sprintf() call mask types does not match provided arguments types

echo sprintf('My name is %s and I have %d children', 10, 'Tomas');


echo sprintf('My name is %s and I have %d children', 'Tomas', 10);

👍


CheckTypehintCallerTypeRule

Parameter %d should use "%s" type as the only type passed to this method

use PhpParser\Node;
use PhpParser\Node\Expr\MethodCall;

class SomeClass
{
    public function run(MethodCall $node)
    {
        $this->isCheck($node);
    }

    private function isCheck(Node $node)
    {
    }
}


use PhpParser\Node\Expr\MethodCall;

class SomeClass
{
    public function run(MethodCall $node)
    {
        $this->isCheck($node);
    }

    private function isCheck(MethodCall $node)
    {
    }
}

👍


ClassNameRespectsParentSuffixRule

Class should have suffix "%s" to respect parent type

🔧 configure it!

services:
    -
        class: Symplify\PHPStanRules\Rules\ClassNameRespectsParentSuffixRule
        tags: [phpstan.rules.rule]
        arguments:
            parentClasses:
                - Symfony\Component\Console\Command\Command

class Some extends Command
{
}


class SomeCommand extends Command
{
}

👍


ConstantMapRuleRule

Static constant map should be extracted from this method

class SomeClass
{
    public function run($value)
    {
        if ($value instanceof SomeType) {
            return 100;
        }

        if ($value instanceof AnotherType) {
            return 1000;
        }

        return 200;
    }
}


class SomeClass
{
    /**
     * @var array<string, int>
     */
    private const TYPE_TO_VALUE = [
        SomeType::class => 100,
        AnotherType::class => 1000,
    ];

    public function run($value)
    {
        foreach (self::TYPE_TO_VALUE as $type => $value) {
            if (is_a($value, $type, true)) {
                return $value;
            }
        }

        return 200;
    }
}

👍


DifferentMethodNameToParameterRule

Method name should be different to its parameter name, in a verb form

class SomeClass
{
    public function apple(string $apple)
    {
        // ...
    }
}


class SomeClass
{
    public function eatApple(string $apple)
    {
        // ...
    }
}

👍


DifferentMethodNameToReturnTypeRule

Method name should be different to its return type, in a verb form

class SomeClass
{
    public function apple(): Apple
    {
        // ...
    }
}


class SomeClass
{
    public function getApple(): Apple
    {
        // ...
    }
}

👍


EmbeddedEnumClassConstSpotterRule

Constants "%s" should be extract to standalone enum class

🔧 configure it!

services:
    -
        class: Symplify\PHPStanRules\Rules\Enum\EmbeddedEnumClassConstSpotterRule
        tags: [phpstan.rules.rule]
        arguments:
            parentTypes:
                - AbstractObject

class SomeProduct extends AbstractObject
{
    public const STATUS_ENABLED = 1;

    public const STATUS_DISABLED = 0;
}


class SomeProduct extends AbstractObject
{
}

class SomeStatus
{
    public const ENABLED = 1;

    public const DISABLED = 0;
}

👍


EnumSpotterRule

The string value "%s" is repeated %d times. Refactor to enum to avoid typos and make clear allowed values

$this->addFlash('info', 'Some message');
$this->addFlash('info', 'Another message');


$this->addFlash(FlashType::INFO, 'Some message');
$this->addFlash(FlashType::INFO, 'Another message');

👍


ExclusiveDependencyRule

Dependency of specific type can be used only in specific class types

🔧 configure it!

services:
    -
        class: Symplify\PHPStanRules\Rules\ExclusiveDependencyRule
        tags: [phpstan.rules.rule]
        arguments:
            allowedExclusiveDependencyInTypes:
                Doctrine\ORM\EntityManager:
                    - *Repository

                Doctrine\ORM\EntityManagerInterface:
                    - *Repository

final class CheckboxController
{
    public function __construct(
        private EntityManagerInterface $entityManager
    ) {
    }
}


final class CheckboxRepository
{
    public function __construct(
        private EntityManagerInterface $entityManager
    ) {
    }
}

👍


ExclusiveNamespaceRule

Exclusive namespace can only contain classes of specific type, nothing else

🔧 configure it!

services:
    -
        class: Symplify\PHPStanRules\Rules\ExclusiveNamespaceRule
        tags: [phpstan.rules.rule]
        arguments:
            namespaceParts:
                - Presenter

namespace App\Presenter;

class SomeRepository
{
}


namespace App\Presenter;

class SomePresenter
{
}

👍


ExplicitMethodCallOverMagicGetSetRule

Instead of magic property "%s" access use direct explicit "%s->%s()" method call

class MagicCallsObject
{
    // adds magic __get() and __set() methods
    use \Nette\SmartObject;

    private $name;

    public function getName()
    {
        return $this->name;
    }
}

$magicObject = new MagicObject();
// magic re-directed to method
$magicObject->name;


class MagicCallsObject
{
    // adds magic __get() and __set() methods
    use \Nette\SmartObject;

    private $name;

    public function getName()
    {
        return $this->name;
    }
}

$magicObject = new MagicObject();
// explicit
$magicObject->getName();

👍


ForbiddenAnonymousClassRule

Anonymous class is not allowed.

new class {};


class SomeClass
{

}

new SomeClass;

👍


ForbiddenArrayDestructRule

Array destruct is not allowed. Use value object to pass data instead

final class SomeClass
{
    public function run(): void
    {
        [$firstValue, $secondValue] = $this->getRandomData();
    }
}


final class SomeClass
{
    public function run(): void
    {
        $valueObject = $this->getValueObject();
        $firstValue = $valueObject->getFirstValue();
        $secondValue = $valueObject->getSecondValue();
    }
}

👍


ForbiddenArrayMethodCallRule

Array method calls [$this, "method"] are not allowed. Use explicit method instead to help PhpStorm, PHPStan and Rector understand your code

usort($items, [$this, "method"]);


usort($items, function (array $apples) {
    return $this->method($apples);
};

👍


ForbiddenArrayWithStringKeysRule

Array with keys is not allowed. Use value object to pass data instead

final class SomeClass
{
    public function run()
    {
        return [
            'name' => 'John',
            'surname' => 'Dope',
        ];
    }
}


final class SomeClass
{
    public function run()
    {
        return new Person('John', 'Dope');
    }
}

👍


ForbiddenAttributteArgumentRule

Attribute key "%s" cannot be used

🔧 configure it!

services:
    -
        class: Symplify\PHPStanRules\Rules\ForbiddenAttributteArgumentRule
        tags: [phpstan.rules.rule]
        arguments:
            argumentsByAttributes:
                Doctrine\ORM\Mapping\Entity:
                    - repositoryClass

use Doctrine\ORM\Mapping\Entity;

#[Entity(repositoryClass: SomeRepository::class)]
class SomeClass
{
}


use Doctrine\ORM\Mapping\Entity;

#[Entity]
class SomeClass
{
}

👍


ForbiddenClassConstRule

Constants in this class are not allowed, move them to custom Enum class instead

🔧 configure it!

services:
    -
        class: Symplify\PHPStanRules\Rules\Enum\ForbiddenClassConstRule
        tags: [phpstan.rules.rule]
        arguments:
            classTypes:
                - AbstractEntity

final class Product extends AbstractEntity
{
    public const TYPE_HIDDEN = 0;

    public const TYPE_VISIBLE = 1;
}


final class Product extends AbstractEntity
{
}

class ProductVisibility extends Enum
{
    public const HIDDEN = 0;

    public const VISIBLE = 1;
}

👍


ForbiddenComplexForeachIfExprRule

foreach(), while(), for() or if() cannot contain a complex expression. Extract it to a new variable on a line before

foreach ($this->getData($arg) as $key => $item) {
    // ...
}


$data = $this->getData($arg);
foreach ($arg as $key => $item) {
    // ...
}

👍


ForbiddenComplexFuncCallRule

Do not use "%s" function with complex content, make it more readable with extracted method or single-line statement

🔧 configure it!

services:
    -
        class: Symplify\PHPStanRules\Rules\ForbiddenComplexFuncCallRule
        tags: [phpstan.rules.rule]
        arguments:
            forbiddenComplexFunctions:
                - array_filter

            maximumStmtCount: 2

$filteredElements = array_filter($elemnets, function ($item) {
    if ($item) {
        return true;
    }

    if ($item === null) {
        return true;
    }

    return false;
};


$filteredElements = array_filter($elemnets, function ($item) {
    return $item instanceof KeepItSimple;
};

👍


ForbiddenDependencyByTypeRule

Object instance of "%s" is forbidden to be passed to constructor

🔧 configure it!

services:
    -
        class: Symplify\PHPStanRules\Rules\ForbiddenDependencyByTypeRule
        tags: [phpstan.rules.rule]
        arguments:
            forbiddenTypes:
                - EntityManager

class SomeClass
{
    public function __construct(
        private EntityManager $entityManager
    ) {
        // ...
    }
}


class SomeClass
{
    public function __construct(
        private ProductRepository $productRepository
    ) {
        // ...
    }
}

👍


ForbiddenForeachEmptyMissingArrayRule

Foreach over empty missing array is not allowed. Use isset check early instead.

final class SomeClass
{
    public function run(): void
    {
        foreach ($data ?? [] as $value) {
            // ...
        }
    }
}


final class SomeClass
{
    public function run(): void
    {
        if (! isset($data)) {
            return;
        }

        foreach ($data as $value) {
            // ...
        }
    }
}

👍


ForbiddenFuncCallRule

Function "%s()" cannot be used/left in the code

🔧 configure it!

services:
    -
        class: Symplify\PHPStanRules\Rules\ForbiddenFuncCallRule
        tags: [phpstan.rules.rule]
        arguments:
            forbiddenFunctions:
                - eval

class SomeClass
{
    return eval('...');
}


class SomeClass
{
    return echo '...';
}

👍


services:
    -
        class: Symplify\PHPStanRules\Rules\ForbiddenFuncCallRule
        tags: [phpstan.rules.rule]
        arguments:
            forbiddenFunctions:
                dump: seems you missed some debugging function

class SomeClass
{
    dump('hello world');
    return true;
}


class SomeClass
{
    return true;
}

👍


ForbiddenInlineClassMethodRule

Method "%s()" only calling another method call and has no added value. Use the inlined call instead

class SomeClass
{
    public function run()
    {
        return $this->away();
    }

    private function away()
    {
        return mt_rand(0, 100);
    }
}


class SomeClass
{
    public function run()
    {
        return mt_rand(0, 100);
    }
}

👍


ForbiddenMethodCallOnNewRule

Method call on new expression is not allowed.

(new SomeClass())->run();


$someClass = new SomeClass();
$someClass->run();

👍


ForbiddenMultipleClassLikeInOneFileRule

Multiple class/interface/trait is not allowed in single file

// src/SomeClass.php
class SomeClass
{
}

interface SomeInterface
{
}


// src/SomeClass.php
class SomeClass
{
}

// src/SomeInterface.php
interface SomeInterface
{
}

👍


ForbiddenNamedArgumentsRule

Named arguments do not add any value here. Use normal arguments in the same order

return strlen(string: 'name');


return strlen('name');

👍


ForbiddenNestedCallInAssertMethodCallRule

Decouple method call in assert to standalone line to make test core more readable

use PHPUnit\Framework\TestCase;

final class SomeClass extends TestCase
{
    public function test()
    {
        $this->assertSame('oooo', $this->someMethodCall());
    }
}


use PHPUnit\Framework\TestCase;

final class SomeClass extends TestCase
{
    public function test()
    {
        $result = $this->someMethodCall();
        $this->assertSame('oooo', $result);
    }
}

👍


ForbiddenNestedForeachWithEmptyStatementRule

Nested foreach with empty statement is not allowed

$collectedFileErrors = [];

foreach ($errors as $fileErrors) {
    foreach ($fileErrors as $fileError) {
        $collectedFileErrors[] = $fileError;
    }
}


$collectedFileErrors = [];

foreach ($fileErrors as $fileError) {
    $collectedFileErrors[] = $fileError;
}

👍


ForbiddenNodeRule

"%s" is forbidden to use

🔧 configure it!

services:
    -
        class: Symplify\PHPStanRules\Rules\ForbiddenNodeRule
        tags: [phpstan.rules.rule]
        arguments:
            forbiddenNodes:
                - PhpParser\Node\Expr\ErrorSuppress

return @strlen('...');


return strlen('...');

👍


ForbiddenNullableParameterRule

Parameter "%s" cannot be nullable

🔧 configure it!

services:
    -
        class: Symplify\PHPStanRules\Rules\ForbiddenNullableParameterRule
        tags: [phpstan.rules.rule]
        arguments:
            forbiddenTypes:
                - PhpParser\Node

            allowedTypes:
                - PhpParser\Node\Scalar\String_

use PhpParser\Node;

class SomeClass
{
    public function run(?Node $node = null): void
    {
    }
}


use PhpParser\Node;

class SomeClass
{
    public function run(Node $node): void
    {
    }
}

👍


ForbiddenParamTypeRemovalRule

Removing parent param type is forbidden

interface RectorInterface
{
    public function refactor(Node $node);
}

final class SomeRector implements RectorInterface
{
    public function refactor($node)
    {
    }
}


interface RectorInterface
{
    public function refactor(Node $node);
}

final class SomeRector implements RectorInterface
{
    public function refactor(Node $node)
    {
    }
}

👍


ForbiddenPrivateMethodByTypeRule

Private method in is not allowed here - it should only delegate to others. Decouple the private method to a new service class

🔧 configure it!

services:
    -
        class: Symplify\PHPStanRules\Rules\ForbiddenPrivateMethodByTypeRule
        tags: [phpstan.rules.rule]
        arguments:
            forbiddenTypes:
                - Command

class SomeCommand extends Command
{
    public function run()
    {
        $this->somePrivateMethod();
    }

    private function somePrivateMethod()
    {
        // ...
    }
}


class SomeCommand extends Command
{
    /**
     * @var ExternalService
     */
    private $externalService;

    public function __construct(ExternalService $externalService)
    {
        $this->externalService = $externalService;
    }

    public function run()
    {
        $this->externalService->someMethod();
    }
}

👍


ForbiddenProtectedPropertyRule

Property with protected modifier is not allowed. Use interface contract method instead

class SomeClass
{
    protected $repository;
}


class SomeClass implements RepositoryAwareInterface
{
    public function getRepository()
    {
        // ....
    }
}

👍


ForbiddenReturnValueOfIncludeOnceRule

Cannot return include_once/require_once

class SomeClass
{
    public function run()
    {
        return require_once 'Test.php';
    }
}


class SomeClass
{
    public function run()
    {
        require_once 'Test.php';
    }
}

👍


ForbiddenSameNamedAssignRule

Variables "%s" are overridden. This can lead to unwanted bugs, please pick a different name to avoid it.

🔧 configure it!

services:
    -
        class: Symplify\PHPStanRules\Rules\Complexity\ForbiddenSameNamedAssignRule
        tags: [phpstan.rules.rule]
        arguments:
            allowedVariableNames:
                - position

$value = 1000;
$value = 2000;


$value = 1000;
$anotherValue = 2000;

👍


ForbiddenSameNamedNewInstanceRule

New objects with "%s" name are overridden. This can lead to unwanted bugs, please pick a different name to avoid it.

$product = new Product();
$product = new Product();

$this->productRepository->save($product);


$firstProduct = new Product();
$secondProduct = new Product();

$this->productRepository->save($firstProduct);

👍


ForbiddenSpreadOperatorRule

Spread operator is not allowed.

$args = [$firstValue, $secondValue];
$message = sprintf('%s', ...$args);


$message = sprintf('%s', $firstValue, $secondValue);

👍


ForbiddenTestsNamespaceOutsideTestsDirectoryRule

"Tests" namespace can be only in "/tests" directory

// file path: "src/SomeClass.php

namespace App\Tests;

class SomeClass
{
}


// file path: "tests/SomeClass.php

namespace App\Tests;

class SomeClass
{
}

👍


ForbiddenThisArgumentRule

$this as argument is not allowed. Refactor method to service composition

$this->someService->process($this, ...);


$this->someService->process($value, ...);

👍


IfElseToMatchSpotterRule

If/else construction can be replace with more robust match()

class SomeClass
{
    public function spot($value)
    {
        if ($value === 100) {
            $items = ['yes'];
        } else {
            $items = ['no'];
        }

        return $items;
    }
}


class SomeClass
{
    public function spot($value)
    {
        return match($value) {
            100 => ['yes'],
            default => ['no'],
        };
    }
}

👍


IfImplementsInterfaceThenNewTypeRule

Class that implements specific interface, must use related class in new SomeClass

🔧 configure it!

services:
    -
        class: Symplify\PHPStanRules\Rules\IfImplementsInterfaceThenNewTypeRule
        tags: [phpstan.rules.rule]
        arguments:
            newTypesByInterface:
                ConfigurableRuleInterface: ConfiguredCodeSample

class SomeRule implements ConfigurableRuleInterface
{
    public function some()
    {
        $codeSample = new CodeSample();
    }
}


class SomeRule implements ConfigurableRuleInterface
{
    public function some()
    {
        $configuredCodeSample = new ConfiguredCodeSample();
    }
}

👍


IfNewTypeThenImplementInterfaceRule

Class must implement "%s" interface

🔧 configure it!

services:
    -
        class: Symplify\PHPStanRules\Rules\IfNewTypeThenImplementInterfaceRule
        tags: [phpstan.rules.rule]
        arguments:
            interfacesByNewTypes:
                ConfiguredCodeSample: ConfiguredRuleInterface

class SomeRule
{
    public function run()
    {
        return new ConfiguredCodeSample('...');
    }
}


class SomeRule implements ConfiguredRuleInterface
{
    public function run()
    {
        return new ConfiguredCodeSample('...');
    }
}

👍


NoAbstractMethodRule

Use explicit interface contract or a service over unclear abstract methods

abstract class SomeClass
{
    abstract public function run();
}


abstract class SomeClass implements RunnableInterface
{
}

interface RunnableInterface
{
    public function run();
}

👍


NoAbstractRule

Instead of abstract class, use specific service with composition

final class NormalHelper extends AbstractHelper
{
}

abstract class AbstractHelper
{
}


final class NormalHelper
{
    public function __construct(
        private SpecificHelper $specificHelper
    ) {
    }
}

final class SpecificHelper
{
}

👍


NoArrayAccessOnObjectRule

Use explicit methods over array access on object

class SomeClass
{
    public function run(MagicArrayObject $magicArrayObject)
    {
        return $magicArrayObject['more_magic'];
    }
}


class SomeClass
{
    public function run(MagicArrayObject $magicArrayObject)
    {
        return $magicArrayObject->getExplicitValue();
    }
}

👍


NoArrayStringObjectReturnRule

Use another value object over array with string-keys and objects, array<string, ValueObject>

final class SomeClass
{
    public getItems()
    {
        return $this->getValues();
    }

    /**
     * @return array<string, Value>
     */
    private function getValues()
    {
    }
}


final class SomeClass
{
    public getItems()
    {
        return $this->getValues();
    }

    /**
     * @return WrappingValue[]
     */
    private function getValues()
    {
        // ...
    }
}

👍


NoBinaryOpCallCompareRule

No magic closure function call is allowed, use explicit class with method instead

return array_filter($items, function ($item) {
}) !== [];


$values = array_filter($items, function ($item) {
});
return $values !== [];

👍


NoClassWithStaticMethodWithoutStaticNameRule

Class has a static method must so must contains "Static" in its name

class SomeClass
{
    public static function getSome()
    {
    }
}


class SomeStaticClass
{
    public static function getSome()
    {
    }
}

👍


NoConstantInterfaceRule

Reserve interface for contract only. Move constant holder to a class soon-to-be Enum

interface SomeContract
{
    public const YES = 'yes';

    public const NO = 'ne';
}


class SomeValues
{
    public const YES = 'yes';

    public const NO = 'ne';
}

👍


NoConstructorInTestRule

Do not use constructor in tests. Move to setUp() method

final class SomeTest
{
    public function __construct()
    {
        // ...
    }
}


final class SomeTest
{
    public function setUp()
    {
        // ...
    }
}

👍


NoContainerInjectionInConstructorRule

Instead of container injection, use specific service

class SomeClass
{
    public function __construct(ContainerInterface $container)
    {
        $this->someDependency = $container->get('...');
    }
}


class SomeClass
{
    public function __construct(SomeDependency $someDependency)
    {
        $this->someDependency = $someDependency;
    }
}

👍


NoDefaultExceptionRule

Use custom exceptions instead of native "%s"

throw new RuntimeException('...');


use App\Exception\FileNotFoundException;

throw new FileNotFoundException('...');

👍


NoDefaultParameterValueRule

Parameter "%s" cannot have default value

class SomeClass
{
    public function run($value = true): void
    {
    }
}


class SomeClass
{
    public function run($value): void
    {
    }
}

👍


NoDependencyJugglingRule

Use dependency injection instead of dependency juggling

public function __construct(
    private $service
) {
}

public function run($someObject)
{
    return $someObject->someMethod($this->service);
}


public function run($someObject)
{
    return $someObject->someMethod();
}

👍


NoDuplicatedArgumentRule

This call has duplicate argument

function run($one, $one);


function run($one, $two);

👍


NoDuplicatedShortClassNameRule

Class with base "%s" name is already used in "%s". Use unique name to make classes easy to recognize

🔧 configure it!

services:
    -
        class: Symplify\PHPStanRules\Rules\NoDuplicatedShortClassNameRule
        tags: [phpstan.rules.rule]
        arguments:
            toleratedNestingLevel: 1

namespace App;

class SomeClass
{
}

namespace App\Nested;

class SomeClass
{
}


namespace App;

class SomeClass
{
}

namespace App\Nested;

class AnotherClass
{
}

👍


NoDynamicNameRule

Use explicit names over dynamic ones

class SomeClass
{
    public function old(): bool
    {
        return $this->${variable};
    }
}


class SomeClass
{
    public function old(): bool
    {
        return $this->specificMethodName();
    }
}

👍


NoDynamicPropertyOnStaticCallRule

Use non-dynamic property on static calls or class const fetches

class SomeClass
{
    public function run()
    {
        return $this->connection::literal();
    }
}


class SomeClass
{
    public function run()
    {
        return Connection::literal();
    }
}

👍


NoEmptyClassRule

There should be no empty class

class SomeClass
{
}


class SomeClass
{
    public function getSome()
    {
    }
}

👍


NoFactoryInConstructorRule

Do not use factory/method call in constructor. Put factory in config and get service with dependency injection

class SomeClass
{
    private $someDependency;

    public function __construct(SomeFactory $factory)
    {
        $this->someDependency = $factory->build();
    }
}


class SomeClass
{
    private $someDependency;

    public function __construct(SomeDependency $someDependency)
    {
        $this->someDependency = $someDependency;
    }
}

👍


NoFuncCallInMethodCallRule

Separate function "%s()" in method call to standalone row to improve readability

final class SomeClass
{
    public function run($value): void
    {
        $this->someMethod(strlen('fooo'));
    }

    // ...
}


final class SomeClass
{
    public function run($value): void
    {
        $fooLength = strlen('fooo');
        $this->someMethod($fooLength);
    }

    // ...
}

👍


NoGetRepositoryOutsideConstructorRule

Do not use "$entityManager->getRepository()" outside of the constructor of repository service or setUp() method in test case

final class SomeController
{
    public function someAction(EntityManager $entityManager): void
    {
        $someEntityRepository = $entityManager->getRepository(SomeEntity::class);
    }
}


final class SomeRepository
{
    public function __construct(EntityManager $entityManager): void
    {
        $someEntityRepository = $entityManager->getRepository(SomeEntity::class);
    }
}

👍


NoGetterAndPropertyRule

There are 2 way to get "%s" value: public property and getter now - pick one to avoid variant behavior.

final class SomeProduct
{
    public $name;

    public function getName(): string
    {
        return $this->name;
    }
}


final class SomeProduct
{
    private $name;

    public function getName(): string
    {
        return $this->name;
    }
}

👍


NoInlineStringRegexRule

Use local named constant instead of inline string for regex to explain meaning by constant name

class SomeClass
{
    public function run($value)
    {
        return preg_match('#some_stu|ff#', $value);
    }
}


class SomeClass
{
    /**
     * @var string
     */
    public const SOME_STUFF_REGEX = '#some_stu|ff#';

    public function run($value)
    {
        return preg_match(self::SOME_STUFF_REGEX, $value);
    }
}

👍


NoIssetOnObjectRule

Use default null value and nullable compare instead of isset on object

class SomeClass
{
    public function run()
    {
        if (random_int(0, 1)) {
            $object = new SomeClass();
        }

        if (isset($object)) {
            return $object;
        }
    }
}


class SomeClass
{
    public function run()
    {
        $object = null;
        if (random_int(0, 1)) {
            $object = new SomeClass();
        }

        if ($object !== null) {
            return $object;
        }
    }
}

👍


NoMagicClosureRule

No magic closure function call is allowed, use explicit class with method instead

(static function () {
    // ...
})


final class HelpfulName
{
    public function clearName()
    {
        // ...
    }
}

👍


NoMaskWithoutSprintfRule

Missing sprintf() function for a mask

return 'Hey %s';


return sprintf('Hey %s', 'Matthias');

👍


NoMethodTagInClassDocblockRule

Do not use @method tag in class docblock

/**
 * @method getMagic() string
 */
class SomeClass
{
    public function __call()
    {
        // more magic
    }
}


class SomeClass
{
    public function getExplicitValue()
    {
        return 'explicit';
    }
}

👍


NoMirrorAssertRule

The assert is tautology that compares to itself. Fix it to different values

use PHPUnit\Framework\TestCase;

final class AssertMirror extends TestCase
{
    public function test()
    {
        $this->assertSame(1, 1);
    }
}


use PHPUnit\Framework\TestCase;

final class AssertMirror extends TestCase
{
    public function test()
    {
        $value = 200;
        $this->assertSame(1, $value);
    }
}

👍


NoMissingDirPathRule

The path "%s" was not found

$filePath = __DIR__ . '/missing_location.txt';


$filePath = __DIR__ . '/existing_location.txt';

👍


NoModifyAndReturnSelfObjectRule

Use void instead of modify and return self object

final class SomeClass
{
    public function modify(ComposerJson $composerJson): ComposerJson
    {
        $composerJson->addPackage('some-package');
        return $composerJson;
    }
}


final class SomeClass
{
    public function modify(ComposerJson $composerJson): void
    {
        $composerJson->addPackage('some-package');
    }
}

👍


NoMultiArrayAssignRule

Use value object over multi array assign

$values = [];
$values['person']['name'] = 'Tom';
$values['person']['surname'] = 'Dev';


$values = [];
$values[] = new Person('Tom', 'Dev');

👍


NoNestedFuncCallRule

Use separate function calls with readable variable names

$filteredValues = array_filter(array_map($callback, $items));


$mappedItems = array_map($callback, $items);
$filteredValues = array_filter($mappedItems);

👍


NoNullableArrayPropertyRule

Use required typed property over of nullable array property

final class SomeClass
{
    private ?array $property = null;
}


final class SomeClass
{
    private array $property = [];
}

👍


NoNullablePropertyRule

Use required typed property over of nullable property

final class SomeClass
{
    private ?DateTime $property = null;
}


final class SomeClass
{
    private DateTime $property;
}

👍


NoParentDuplicatedTraitUseRule

The "%s" trait is already used in parent class. Remove it here

class ParentClass
{
    use SomeTrait;
}

class SomeClass extends ParentClass
{
    use SomeTrait;
}


class ParentClass
{
    use SomeTrait;
}

class SomeClass extends ParentClass
{
}

👍


NoParentMethodCallOnEmptyStatementInParentMethodRule

Do not call parent method if parent method is empty

class ParentClass
{
    public function someMethod()
    {
    }
}

class SomeClass extends ParentClass
{
    public function someMethod()
    {
        parent::someMethod();
    }
}


class ParentClass
{
    public function someMethod()
    {
    }
}

class SomeClass extends ParentClass
{
    public function someMethod()
    {
    }
}

👍


NoParentMethodCallOnNoOverrideProcessRule

Do not call parent method if no override process

class SomeClass extends Printer
{
    public function print($nodes)
    {
        return parent::print($nodes);
    }
}


class SomeClass extends Printer
{
}

👍


NoPostIncPostDecRule

Post operation are forbidden, as they make 2 values at the same line. Use pre instead

class SomeClass
{
    public function run($value = 1)
    {
        // 1 ... 0
        if ($value--) {
        }
    }
}


class SomeClass
{
    public function run($value = 1)
    {
        // 0
        if (--$value) {
        }
    }
}

👍


NoPropertySetOverrideRule

Property set "%s" is overridden.

$someObject = new SomeClass();
$someObject->name = 'First value';

// ...
$someObject->name = 'Second value';


$someObject = new SomeClass();
$someObject->name = 'First value';

👍


NoProtectedElementInFinalClassRule

Instead of protected element in final class use private element or contract method

final class SomeClass
{
    protected function run()
    {
    }
}


final class SomeClass
{
    private function run()
    {
    }
}

👍


NoReferenceRule

Use explicit return value over magic &reference

class SomeClass
{
    public function run(&$value)
    {
    }
}


class SomeClass
{
    public function run($value)
    {
        return $value;
    }
}

👍


NoReturnArrayVariableListRule

Use value object over return of values

class ReturnVariables
{
    public function run($value, $value2): array
    {
        return [$value, $value2];
    }
}


final class ReturnVariables
{
    public function run($value, $value2): ValueObject
    {
        return new ValueObject($value, $value2);
    }
}

👍


NoReturnSetterMethodRule

Setter method cannot return anything, only set value

final class SomeClass
{
    private $name;

    public function setName(string $name): int
    {
        return 1000;
    }
}


final class SomeClass
{
    private $name;

    public function setName(string $name): void
    {
        $this->name = $name;
    }
}

👍


NoSetterOnServiceRule

Do not use setter on a service

class SomeService
{
    public function setSomeValue($value)
    {
    }
}


class SomeEntity
{
    public function setSomeValue($value)
    {
    }
}

👍


NoStaticPropertyRule

Do not use static property

final class SomeClass
{
    private static $customFileNames = [];
}


final class SomeClass
{
    private $customFileNames = [];
}

👍


NoSuffixValueObjectClassRule

Value Object class name "%s" must be without "ValueObject" suffix.

class SomeValueObject
{
    public function __construct(string $name)
    {
        $this->name = $name;
    }
}


class Some
{
    public function __construct(string $name)
    {
        $this->name = $name;
    }
}

👍


NoTraitRule

Do not use trait, extract to a service and dependency injection instead

trait SomeTrait
{
    public function run()
    {
    }
}


class SomeService
{
    public function run(...)
    {
    }
}

👍


NoVoidAssignRule

Assign of void value is not allowed, as it can lead to unexpected results

final class SomeClass
{
    public function run()
    {
        $value = $this->getNothing();
    }

    public function getNothing(): void
    {
    }
}


final class SomeClass
{
    public function run()
    {
        $this->getNothing();
    }

    public function getNothing(): void
    {
    }
}

👍


NoVoidGetterMethodRule

Getter method must return something, not void

final class SomeClass
{
    public function getData(): void
    {
        // ...
    }
}


final class SomeClass
{
    public function getData(): array
    {
        // ...
    }
}

👍


PreferredAttributeOverAnnotationRule

Use attribute instead of "%s" annotation

🔧 configure it!

services:
    -
        class: Symplify\PHPStanRules\Rules\PreferredAttributeOverAnnotationRule
        tags: [phpstan.rules.rule]
        arguments:
            annotations:
                - Symfony\Component\Routing\Annotation\Route

use Symfony\Component\Routing\Annotation\Route;

class SomeController
{
    /**
     * @Route()
     */
    public function action()
    {
    }
}


use Symfony\Component\Routing\Annotation\Route;

class SomeController
{
    #[Route]
    public function action()
    {
    }
}

👍


PreferredClassRule

Instead of "%s" class/interface use "%s"

🔧 configure it!

services:
    -
        class: Symplify\PHPStanRules\Rules\PreferredClassRule
        tags: [phpstan.rules.rule]
        arguments:
            oldToPreferredClasses:
                SplFileInfo: Symplify\SmartFileSystem\SmartFileInfo

class SomeClass
{
    public function run()
    {
        return new SplFileInfo('...');
    }
}


use Symplify\SmartFileSystem\SmartFileInfo;

class SomeClass
{
    public function run()
    {
        return new SmartFileInfo('...');
    }
}

👍


PreferredRawDataInTestDataProviderRule

Code configured at setUp() cannot be used in data provider. Move it to test() method

final class UseDataFromSetupInTestDataProviderTest extends TestCase
{
    private $data;

    protected function setUp()
    {
        $this->data = true;
    }

    public function provideFoo()
    {
        yield [$this->data];
    }

    /**
     * @dataProvider provideFoo
     */
    public function testFoo($value)
    {
        $this->assertTrue($value);
    }
}


use stdClass;

final class UseRawDataForTestDataProviderTest
{
    private $obj;

    protected function setUp()
    {
        $this->obj = new stdClass;
    }

    public function provideFoo()
    {
        yield [true];
    }

    /**
     * @dataProvider provideFoo
     */
    public function testFoo($value)
    {
        $this->obj->x = $value;
        $this->assertTrue($this->obj->x);
    }
}

👍


PrefixAbstractClassRule

Abstract class name "%s" must be prefixed with "Abstract"

abstract class SomeClass
{
}


abstract class AbstractSomeClass
{
}

👍


PreventDuplicateClassMethodRule

Content of method "%s()" is duplicated with method "%s()" in "%s" class. Use unique content or service instead

🔧 configure it!

services:
    -
        class: Symplify\PHPStanRules\Rules\PreventDuplicateClassMethodRule
        tags: [phpstan.rules.rule]
        arguments:
            minimumLineCount: 3

class SomeClass
{
    public function someMethod()
    {
        echo 'statement';
        $value = new SmartFinder();
    }
}

class AnotherClass
{
    public function someMethod()
    {
        echo 'statement';
        $differentValue = new SmartFinder();
    }
}


class SomeClass
{
    public function someMethod()
    {
        echo 'statement';
        $value = new SmartFinder();
    }
}
}

👍


PreventParentMethodVisibilityOverrideRule

Change "%s()" method visibility to "%s" to respect parent method visibility.

class SomeParentClass
{
    public function run()
    {
    }
}

class SomeClass
{
    protected function run()
    {
    }
}


class SomeParentClass
{
    public function run()
    {
    }
}

class SomeClass
{
    public function run()
    {
    }
}

👍


RegexSuffixInRegexConstantRule

Name your constant with "_REGEX" suffix, instead of "%s"

class SomeClass
{
    public const SOME_NAME = '#some\s+name#';

    public function run($value)
    {
        $somePath = preg_match(self::SOME_NAME, $value);
    }
}


class SomeClass
{
    public const SOME_NAME_REGEX = '#some\s+name#';

    public function run($value)
    {
        $somePath = preg_match(self::SOME_NAME_REGEX, $value);
    }
}

👍


RequireAttributeNameRule

Attribute must have all names explicitly defined

use Symfony\Component\Routing\Annotation\Route;

class SomeController
{
    #[Route("/path")]
    public function someAction()
    {
    }
}


use Symfony\Component\Routing\Annotation\Route;

class SomeController
{
    #[Route(path: "/path")]
    public function someAction()
    {
    }
}

👍


RequireAttributeNamespaceRule

Attribute must be located in "Attribute" namespace

// app/Entity/SomeAttribute.php
namespace App\Controller;

#[\Attribute]
final class SomeAttribute
{
}


// app/Attribute/SomeAttribute.php
namespace App\Attribute;

#[\Attribute]
final class SomeAttribute
{
}

👍


RequireConstantInAttributeArgumentRule

Argument "%s" must be a constant

🔧 configure it!

services:
    -
        class: Symplify\PHPStanRules\Rules\RequireConstantInAttributeArgumentRule
        tags: [phpstan.rules.rule]
        arguments:
            attributeWithNames:
                Symfony\Component\Routing\Annotation\Route:
                    - name

use Symfony\Component\Routing\Annotation\Route;

final class SomeClass
{
    #[Route(path: '/archive', name: 'blog_archive')]
    public function __invoke()
    {
    }
}


use Symfony\Component\Routing\Annotation\Route;

final class SomeClass
{
    #[Route(path: '/archive', name: RouteName::BLOG_ARCHIVE)]
    public function __invoke()
    {
    }
}

👍


RequireConstantInMethodCallPositionRule

Parameter argument on position %d must use constant

🔧 configure it!

services:
    -
        class: Symplify\PHPStanRules\Rules\Enum\RequireConstantInMethodCallPositionRule
        tags: [phpstan.rules.rule]
        arguments:
            requiredLocalConstantInMethodCall:
                SomeType:
                    someMethod:
                        - 0

class SomeClass
{
    public function someMethod(SomeType $someType)
    {
        $someType->someMethod('hey');
    }
}


class SomeClass
{
    private const HEY = 'hey'

    public function someMethod(SomeType $someType)
    {
        $someType->someMethod(self::HEY);
    }
}

👍


RequireDataProviderTestMethodRule

The "%s()" method must use data provider

🔧 configure it!

services:
    -
        class: Symplify\PHPStanRules\Rules\RequireDataProviderTestMethodRule
        tags: [phpstan.rules.rule]
        arguments:
            classesRequiringDataProvider:
                - *RectorTestCase

class SomeRectorTestCase extends RectorTestCase
{
    public function test()
    {
    }
}


class SomeRectorTestCase extends RectorTestCase
{
    /**
     * @dataProvider provideData()
     */
    public function test($value)
    {
    }

    public function provideData()
    {
        // ...
    }
}

👍


RequireExceptionNamespaceRule

Exception must be located in "Exception" namespace

// app/Controller/SomeException.php
namespace App\Controller;

final class SomeException extends Exception
{

}


// app/Exception/SomeException.php
namespace App\Exception;

final class SomeException extends Exception
{
}

👍


RequireNewArgumentConstantRule

New expression argument on position %d must use constant over value

🔧 configure it!

services:
    -
        class: Symplify\PHPStanRules\Rules\Enum\RequireNewArgumentConstantRule
        tags: [phpstan.rules.rule]
        arguments:
            constantArgByNewByType:
                Symfony\Component\Console\Input\InputOption:
                    - 2

use Symfony\Component\Console\Input\InputOption;

$inputOption = new InputOption('name', null, 2);


use Symfony\Component\Console\Input\InputOption;

$inputOption = new InputOption('name', null, InputOption::VALUE_REQUIRED);

👍


RequireSkipPrefixForRuleSkippedFixtureRule

Skipped tested file must start with "Skip" prefix

use PHPStan\Testing\RuleTestCase;

final class SomeRuleTest extends RuleTestCase
{
    /**
     * @dataProvider provideData()
     * @param array<string|int> $expectedErrorMessagesWithLines
     */
    public function testRule(string $filePath, array $expectedErrorMessagesWithLines): void
    {
        $this->analyse([$filePath], $expectedErrorMessagesWithLines);
    }

    public function provideData(): Iterator
    {
        yield [__DIR__ . '/Fixture/NewWithInterface.php', []];
    }

    protected function getRule(): Rule
    {
        return new SomeRule());
    }
}


use PHPStan\Testing\RuleTestCase;

final class SomeRuleTest extends RuleTestCase
{
    /**
     * @dataProvider provideData()
     * @param array<string|int> $expectedErrorMessagesWithLines
     */
    public function testRule(string $filePath, array $expectedErrorMessagesWithLines): void
    {
        $this->analyse([$filePath], $expectedErrorMessagesWithLines);
    }

    public function provideData(): Iterator
    {
        yield [__DIR__ . '/Fixture/SkipNewWithInterface.php', []];
    }

    protected function getRule(): Rule
    {
        return new SomeRule());
    }
}

👍


RequireSpecificReturnTypeOverAbstractRule

Provide more specific return type "%s" over abstract one

final class IssueControlFactory
{
    public function create(): Control
    {
        return new IssueControl();
    }
}

final class IssueControl extends Control
{
}


final class IssueControlFactory
{
    public function create(): IssueControl
    {
        return new IssueControl();
    }
}

final class IssueControl extends Control
{
}

👍


RequireStringArgumentInConstructorRule

Use quoted string in constructor "new %s()" argument on position %d instead of "::class. It prevent scoping of the class in building prefixed package.

🔧 configure it!

services:
    -
        class: Symplify\PHPStanRules\Rules\RequireStringArgumentInConstructorRule
        tags: [phpstan.rules.rule]
        arguments:
            stringArgPositionsByType:
                SomeClass:
                    - 0

class AnotherClass
{
    public function run()
    {
        new SomeClass(YetAnotherClass:class);
    }
}


class AnotherClass
{
    public function run()
    {
        new SomeClass('YetAnotherClass');
    }
}

👍


RequireStringRegexMatchKeyRule

Regex must use string named capture groups instead of numeric

use Nette\Utils\Strings;

class SomeClass
{
    private const REGEX = '#(a content)#';

    public function run()
    {
        $matches = Strings::match('a content', self::REGEX);
        if ($matches) {
            echo $matches[1];
        }
    }
}


use Nette\Utils\Strings;

class SomeClass
{
    private const REGEX = '#(?<content>a content)#';

    public function run()
    {
        $matches = Strings::match('a content', self::REGEX);
        if ($matches) {
            echo $matches['content'];
        }
    }
}

👍


RequireThisCallOnLocalMethodRule

Use "$this->()" instead of "self::()" to call local method

class SomeClass
{
    public function run()
    {
        self::execute();
    }

    private function execute()
    {
    }
}


class SomeClass
{
    public function run()
    {
        $this->execute();
    }

    private function execute()
    {
    }
}

👍


RequireThisOnParentMethodCallRule

Use "$this->()" instead of "parent::()" unless in the same named method

class SomeParentClass
{
    public function run()
    {
    }
}

class SomeClass extends SomeParentClass
{
    public function go()
    {
        parent::run();
    }
}


class SomeParentClass
{
    public function run()
    {
    }
}

class SomeClass extends SomeParentClass
{
    public function go()
    {
        $tihs->run();
    }
}

👍


RequireUniqueEnumConstantRule

Enum constants "%s" are duplicated. Make them unique instead

use MyCLabs\Enum\Enum;

class SomeClass extends Enum
{
    private const YES = 'yes';

    private const NO = 'yes';
}


use MyCLabs\Enum\Enum;

class SomeClass extends Enum
{
    private const YES = 'yes';

    private const NO = 'no';
}

👍


RequiredAbstractClassKeywordRule

Class name starting with "Abstract" must have an abstract keyword

class AbstractClass
{
}


abstract class AbstractClass
{
}

👍


RespectPropertyTypeInGetterReturnTypeRule

This getter method does not respect property type

final class SomeClass
{
    private $value = [];

    public function setValues(array $values)
    {
        $this->values = $values;
    }

    public function getValues(): array|null
    {
        return $this->values;
    }
}


final class SomeClass
{
    private $value = [];

    public function setValues(array $values)
    {
        $this->values = $values;
    }

    public function getValues(): array
    {
        return $this->values;
    }
}

👍


SeeAnnotationToTestRule

Class "%s" is missing @see annotation with test case class reference

🔧 configure it!

services:
    -
        class: Symplify\PHPStanRules\Rules\SeeAnnotationToTestRule
        tags: [phpstan.rules.rule]
        arguments:
            requiredSeeTypes:
                - Rule

class SomeClass extends Rule
{
}


/**
 * @see SomeClassTest
 */
class SomeClass extends Rule
{
}

👍


SuffixInterfaceRule

Interface must be suffixed with "Interface" exclusively

interface SomeClass
{
}


interface SomeInterface
{
}

👍


SuffixTraitRule

Trait must be suffixed by "Trait" exclusively

trait SomeClass
{
}


trait SomeTrait
{
}

👍


TooDeepNewClassNestingRule

new is limited to %d "new (new ))" nesting to each other. You have %d nesting.

🔧 configure it!

services:
    -
        class: Symplify\PHPStanRules\Rules\TooDeepNewClassNestingRule
        tags: [phpstan.rules.rule]
        arguments:
            maxNewClassNesting: 2

$someObject = new A(
    new B(
        new C()
    )
);


$firstObject = new B(new C());
$someObject = new A($firstObject);

👍


TooLongVariableRule

Variable "$%s" is too long with %d chars. Narrow it under %d chars

🔧 configure it!

services:
    -
        class: Symplify\PHPStanRules\Rules\TooLongVariableRule
        tags: [phpstan.rules.rule]
        arguments:
            maxVariableLength: 10

class SomeClass
{
    public function run()
    {
        return $superLongVariableName;
    }
}


class SomeClass
{
    public function run()
    {
        return $shortName;
    }
}

👍


UppercaseConstantRule

Constant "%s" must be uppercase

final class SomeClass
{
    public const some = 'value';
}


final class SomeClass
{
    public const SOME = 'value';
}

👍


ValueObjectOverArrayShapeRule

Instead of array shape, use value object with specific types in constructor and getters

/**
 * @return array{line: int}
 */
function createConfiguration()
{
    return ['line' => 100];
}


/**
 * @return array{line: int}
 */
function createConfiguration()
{
    return new Configuration(100);
}

final class Configuration
{
    public function __construct(
        private int $line
    ) {
    }

    public function getLine(): int
    {
        return $this->line;
    }
}

👍