Error Identifier: attribute.nonRepeatable
Every error reported by PHPStan has an error identifier. Here’s a list of all error identifiers. In PHPStan Pro you can see the error identifier next to each error and filter errors by their identifiers.
Code example #
<?php declare(strict_types = 1);
#[\Attribute]
class MyAttribute
{
}
#[MyAttribute]
#[MyAttribute]
class Foo
{
}
Why is it reported? #
PHP attributes are not repeatable by default. When an attribute class is declared without the Attribute::IS_REPEATABLE flag, it can only be applied once to a given target (class, method, property, etc.). Applying the same non-repeatable attribute more than once to the same target is a runtime error.
In the example above, MyAttribute is applied twice to the class Foo, but the attribute class does not include the Attribute::IS_REPEATABLE flag in its #[\Attribute] declaration.
How to fix it #
Remove the duplicate attribute:
<?php declare(strict_types = 1);
#[\Attribute]
class MyAttribute
{
}
#[MyAttribute]
-#[MyAttribute]
class Foo
{
}
Or make the attribute repeatable by adding the IS_REPEATABLE flag:
<?php declare(strict_types = 1);
-#[\Attribute]
+#[\Attribute(\Attribute::IS_REPEATABLE | \Attribute::TARGET_CLASS)]
class MyAttribute
{
}
#[MyAttribute]
#[MyAttribute]
class Foo
{
}
How to ignore this error #
You can use the identifier attribute.nonRepeatable to ignore this error using a comment:
// @phpstan-ignore attribute.nonRepeatable
codeThatProducesTheError();
You can also use only the identifier key to ignore all errors of the same type in your configuration file in the ignoreErrors parameter:
parameters:
ignoreErrors:
-
identifier: attribute.nonRepeatable
Rules that report this error #
- PHPStan\Rules\Classes\ClassAttributesRule [1]
- PHPStan\Rules\Classes\ClassConstantAttributesRule [1]
- PHPStan\Rules\Constants\ConstantAttributesRule [1]
- PHPStan\Rules\EnumCases\EnumCaseAttributesRule [1]
- PHPStan\Rules\Functions\ArrowFunctionAttributesRule [1]
- PHPStan\Rules\Functions\ClosureAttributesRule [1]
- PHPStan\Rules\Functions\FunctionAttributesRule [1]
- PHPStan\Rules\Functions\ParamAttributesRule [1]
- PHPStan\Rules\Methods\MethodAttributesRule [1]
- PHPStan\Rules\Properties\PropertyAttributesRule [1]
- PHPStan\Rules\Properties\PropertyHookAttributesRule [1]
- PHPStan\Rules\Traits\TraitAttributesRule [1]