spaze/phpstan-disallowed-calls
PHPStan rules to detect disallowed functions, methods, constants, namespaces, attributes, variables, and properties without running code. Catch leftover debug calls like var_dump() and enforce custom logging or API usage in production.
disallowedClasses or disallowedNamespaces are reported: instanceof, first-class callables like Foo::bar(...), DNF types like (A&B)|null, types of class constants, and interfaces extended by interfaces or implemented by enums (#444)Class, Interface (with the new disallowed.interface identifier), Enum or Trait, also in static calls, extends and implements, which said Namespace before; only use imports keep Namespace because they can also import a namespace (#440, #443 - possible BC break)allowInClassWithMethodAttributes sees attributes on hooks; matching hooks by name like Foo::$bar::get() in allowInMethods is now documented (#441, #445)Suit::Hearts was reported twice, as a class and as an enum, now it's reported once as Enum (#440)ReflectionException when the config had allowInMethodsWithAttributes, allowExceptInMethodsWithAttributes or their aliases (#441)self::, static:: and parent:: calls aren't reported as Namespace self is forbidden. anymore when a wildcard pattern happens to match them (#443)str_contains() isn't used anymore, it doesn't exist on PHP 7.4 (#436)composer.json (#439)PHPStan1Compatibility renamed to PHPStanCompatibility, because it covers older PHPStan 2.x versions too (#441)Possible BC break note: messages and identifiers changed for static calls, extends and implements (Namespace/disallowed.namespace is now Class, Interface, Enum or Trait), for interfaces and traits anywhere else (Class/disallowed.class is now Interface/disallowed.interface or Trait/disallowed.trait), and for enums in type declarations (Class is now Enum). The duplicate Class error for enum cases and constants is gone. If you match these errors in ignoreErrors or a baseline, they may need updating, and the newly reported usages can add errors.
New bundled configuration file disallowed-non-timing-safe-calls.neon for code that works with keys, tokens, and other secrets: it disallows hex2bin(), bin2hex(), base64_decode(), and base64_encode(), because their runtime depends on the processed bytes and can leak information about them, and recommends the sodium_* functions instead, or ParagonIE\ConstantTime\* when ext-sodium is not available (#433, #434)
includes:
- vendor/spaze/phpstan-disallowed-calls/disallowed-non-timing-safe-calls.neon
Note: comparing secrets, digests, hashes is the other half - use hash_equals(), not ===, which is an operator, so no rule here can catch it.
Attributes placed on a method or a function - not just used inside one - now match the name-based allowInMethods/allowInFunctions patterns, the same way allowInMethodsWithAttributes already matched them (#427, #428 - possible BC break)
Allow directives now fall through to the next one in the same config entry when they don't match, so e.g. allowInInstanceOf combined with allowInClassWithAttributes works as alternatives; how the directives compose is now documented (#429, #430)
Documented that directive aliases (allowInFunctions/allowInMethods, disallowInMethods/allowExceptInMethods etc.) refer to one single directive and only one of them is used when an entry sets several (#430)
expectExceptionMessage() deprecation is handled while keeping older PHPUnit versions working (#425)goto is reachable again in the test fixture (#420)Possible BC break note: allowExceptInMethods and its aliases can now report an attribute placed on a matching method or function, which was previously always allowed - if attribute errors newly appear, check your patterns. Other than that, errors can only disappear with this release.
classPattern param directive matches a parameter's declared class name against a wildcard pattern using fnmatch() (#412, docs example #417)allowInInstanceOf/disallowInInstanceOf now support fnmatch() wildcard patterns (#399, docs example #417) and param conditions (#401)allowExceptIn/allowExceptInMethods and their disallowIn* aliases (#414)allowExceptParamsAnywhere and disallowParamsAnywhere aliases for allowExceptParams/disallowParams to match other *Anywhere directives (#410)typeString: descriptive exception on parse failure (#407)typeString now throws an exception, and '0' (a string consisting of 0) is now a valid typeString (#409)func(...)) with param conditions is now handled correctly (#418)allowExceptInFunctions/allowExceptInMethods with multiple entries only checked the first one, not anymore (#405)CLAUDE.md (#403, export-ignored in #413)export-ignore phpstan-dead-code-detector.php from release archives (#413)Applies only to disallowedNamespaces and disallowedClasses, the following configuration keys let you permit (or restrict) a class or namespace based on whether it appears as a parameter type hint or a return type hint in a function or method signature, and ban (or allow) using it elsewhere, for example in the method body.
allowInParamTypes: trueallowExceptInParamTypes: true (or the disallowInParamTypes alias)allowInReturnType: trueallowExceptInReturnType: true (or the disallowInReturnType alias)See the docs for examples.
Note: to enable usage in use imports use allowInUse: true.
X.Y.Z to eliminate test-runner warnings (#393, thanks @Copilot)allowInMethodsWithAttributes in signatures to use a node visitor (#395)Can disallow (some) keywords with disallowedKeywords, only global supported for now (#390)
parameters:
disallowedKeywords:
-
keyword: 'global'
allowIn:
- 'legacy/*'
This release includes a proper fix for the "defined in" checks originally fixed in 4.9.1. (#388)
As a necessary side effect, unknown functions (functions where their reflection is not available) won't be reported as disallowed anymore, if configured, by this extension as is the case with for example methods already.
Naming is hard, so that's why this Disallowed Calls extension now supports disallowing instance and static properties, and enum properties with disallowProperties (#378)
Generator (#372)include types in the switch (#373)disallowedSuperglobals docs more clear that it doesn't recommend $_REQUEST (#377)Oh, a Friday 13th release! 👻
You can now also pass an array to errorTip in the config:
errorTip:
- Tip 1
- Tip 2
PHPStan will print al the tips, but please note that tips will be prefixed with •, like this:
💡• a tip
• another one
errorTip (#367 #369, thanks @Copilot and myself 🤖)bin (#358)dd() and dump() for now (#353)phpstan-ignore-errors.php into the package (#328)hasConstant check (#343)A test to ensure the extension still works where it was working before. The test checks out a configured repository, installs the latest version of the extension, then runs PHPStan.
If you disallow multiple classes or namespaces using an fnmatch wildcard, for example like this:
disallowedClasses:
-
class: 'Foo\Bar\*Something'
... then there may be one or more classes that you'd like to exclude from all the *Something classes for some reason. Previously, starting with 2.15.0, you could exclude them by name using the exclude option:
exclude:
- 'Foo\Bar\NotThisSomething'
This release brings a new directive called excludeWithAttribute which you can also use to exclude items from the original set, but based on whether they have the specified attribute:
disallowedClasses:
-
class: 'Foo\Bar\*Something'
excludeWithAttribute:
- 'MyApp\ThisAttribute'
Then if you have two classes like this:
namespace Foo\Bar;
class ThisSomething
{
}
#[\MyApp\ThisAttribute]
class ThatSomething
{
}
then only ThisSomething class would be disallowed.
excludeWithAttribute is supported for classes and namespaces for now, and supports fnmatch patterns.
zend.assertions=1 (#321)This is a follow-up to the allowInMethodsWithAttributes feature added in 4.3.1.
When you disallow the Event class (with disallowedClasses) and would like to allow it again in a method that has the Attr attribute (see the example code below), the Event class should be allowed even in the method signature. Previously, it was flagged as a disallowed usage (#315)
class Handler
{
#[Attr]
public function foo(Event $event) // should be allowed too
{
$event = new Event(); // allowed
}
}
instanceofs (allowInInstanceOf, allowExceptInInstanceOf, allowInUse directives, docs) (#306)allow* support for all items (previously constants, superglobals and control structures didn't support for example allowInMethods etc.) (#310)If this extension helps you write better code you can sponsor a release or buy me a 🍻 or a 🍰, thanks!
This bugfix release includes a better detection of disallowed attributes reallowed in a method with attributes (#304)
The original 4.3.0 release notes:
This release has been sponsored by @ticketswap & @ruudk, thank you 🍰
So far, when you wanted to re-allow a disallowed function or a method, or specifically disallow them, you could use:
allowIn path to specify a path or a filename where the function or method could be called without generating an errorallowInMethods (or the allowInFunctions alias) to specify functions and methods in which the disallowed function would be alloweddisallowIn or disallowInMethods (or the allowExceptIn[...] aliases) if you wanted to list paths or methods in which the call is explicitly disallowedStarting with this release, you can use attributes to sort of mark functions and methods in which the disallowed call would be allowed (or explicitly disallowed):
allowInClassWithAttributes to allow for example a method in a class that has a specified class attributeallowInMethodsWithAttributes (or the disallowInFunctionsWithAttributes alias) to allow the call in methods (or function) with the given method attribute (or a function attribute)allowInClassWithMethodAttributes to allow a call in a class where any method has the attribute, where "any method" includes any other method as well, static or not, public, private, or protecteddisallowIn[...] counterparts (with allowExceptIn[...] aliases) to specify only classes and methods in which the call should be disallowedThis allows you to create rules that do not depend on paths or method names, and can be useful if you're working with frameworks or libs that already use attributes. You can specify multiple items in the directives above and only one of them needs to match (it's not an AND list, more like OR list) and they all support fnmatch patterns.
fnmatch less often only when needed (#297)disallowedAttributes docs (#299, thanks @ruudk)You too can sponsor a release or buy me a 🍻 or a 🍰, thanks!
This release has been sponsored by @ticketswap & @ruudk, thank you 🍰
So far, when you wanted to re-allow a disallowed function or a method, or specifically disallow them, you could use:
allowIn path to specify a path or a filename where the function or method could be called without generating an errorallowInMethods (or the allowInFunctions alias) to specify functions and methods in which the disallowed function would be alloweddisallowIn or disallowInMethods (or the allowExceptIn[...] aliases) if you wanted to list paths or methods in which the call is explicitly disallowedStarting with this release, you can use attributes to sort of mark functions and methods in which the disallowed call would be allowed (or explicitly disallowed):
allowInClassWithAttributes to allow for example a method in a class that has a specified class attributeallowInMethodsWithAttributes (or the disallowInFunctionsWithAttributes alias) to allow the call in methods (or function) with the given method attribute (or a function attribute)allowInClassWithMethodAttributes to allow a call in a class where any method has the attribute, where "any method" includes any other method as well, static or not, public, private, or protecteddisallowIn[...] counterparts (with allowExceptIn[...] aliases) to specify only classes and methods in which the call should be disallowedThis allows you to create rules that do not depend on paths or method names, and can be useful if you're working with frameworks or libs that already use attributes. You can specify multiple items in the directives above and only one of them needs to match (it's not an AND list, more like OR list) and they all support fnmatch patterns.
fnmatch less often only when needed (#297)disallowedAttributes docs (#299, thanks @ruudk)You too can sponsor a release or buy me a 🍻 or a 🍰, thanks!
isset() in disallowedFunctionCalls (#289, thanks @ksaveras!)unset, too (#291)array_merge arrays with error messages only when not empty, this should speed things up a bit, maybe (#287)This version replaces 4.1.0 in which callables were not detected in constructors. The notes below are taken from 4.1.0.
This release adds new detections listed below, meaning it's possible that you'll see new error messages.
First class callable syntax (#279), for example:
$func = print_r(...);
Dynamic calls (#276, #278), for example:
$func('foo');
$object->$method();
Test anonymous class usages (#277), for example:
$foo = new class implements ...
$foo = new class extends ...
Anonymous class usages (when the anonymous class extends DisallowedClass for example) were detected before, however the detection is now tested.
Detect callable parameters (#281, #283, #285), for example:
array_map('function', []);
array_map([$object, 'method'], []);
array_map([Class::class, 'staticMethod']);
This release has been replaced by 4.1.1 which also detects callables in constructors, unlike this version.
The 4.0 release removed support for PHPStan 1.x, and this release brings it back. Both PHPStan 1.12 and PHPStan 2.0 are supported (#273).
You can learn more about PHPStan 2.0 in the release notes or in the blog post and don't forget to get yourself an elephpant and a t-shirt!
This major release supports and requires PHPStan 2.0 (#267) (update: the 4.0.1 release adds back support for PHPStan 1.12)
As mentioned in the UPGRADING.md guide:
It's not feasible to try to support both PHPStan 1.x and PHPStan 2.x with the same extension code.
You can learn more about PHPStan 2.0 in the release notes or in the blog post and don't forget to get yourself an elephpant and a t-shirt!
That's it. That's the release.
create_function as a disallowed function call (#261, thanks @BackEndTea)ClassConstFetch where $class is Name only for enums to correctly support PHPStan 1.12.6 (#266)Internal changes:
PHPStan 1.11 added error identifiers and while they were supported by this extension for quite some time (since #97), they were not added by default, only when you've specified them.
This release adds error identifiers everywhere, and they'll be used if you don't specify custom identifiers in your custom config.
The full list of identifiers is in the ErrorIdentifiers class here https://github.com/spaze/phpstan-disallowed-calls/blob/main/src/RuleErrors/ErrorIdentifiers.php and they have a disallowed.something format.
else, elseif, goto (#257)Checking params inside ( ... ) doesn't work at the moment, so you can disallow all declare() constructs but can't re-allow e.g. declare(strict-types = 1).
If you try to disallow else if with the space, an exception will be thrown, because else if is parsed as else followed by if, so disallowing else if with the space wouldn't have the desired effect and the result would be unexpected. Disallow elseif, or don't write else if in your code 😇
phpinfo() to dangerous calls config (#255)See
for reasons why (phpinfo() echoes cookie values like the session id, which may then be stolen with XSS for example, bypassing HttpOnly cookie flag), and use https://github.com/spaze/phpinfo instead of just calling phpinfo().
array_values() (#253, this is a new bleeding edge rule added in PHPStan 1.10.59)ENT_QUOTES as int 3 in disallowed-loose-calls.neon config (#250)disallowedEnums, they use DisallowedConstant internally (#243, docs)disallowedConstants' constant field is always present (#245)The 3.1.0 release was the same minus #248.
New major version because some major new features in this release, and some potential backwards compatibility breaks, if you use the extension in one way or another, all described below.
typeString config option (#234)
You can now specify dis/allowed parameter values as PHPDoc string like typeString: 'foo'|'bar' or typeString: 'array{}' etc. instead of just value: scalarmessage key in the disallowed configuration, "because reasons" was added automatically. I thought it was funny back when this was an internal extension only, but maybe it's not anymore. So there's no "because reasons" anymore, and the error message will always end with a full stop ., unless it already ends with one, or unless it ends with ? or !.allowExceptParamsInAllowed description in docs was flipped around (#235)libs dir into src (#227)ClassWithAttributesAllow (#230)Did you know you can use @dependabot to update your actions, not just your code? I've updated my article which mentions Dependabot https://www.michalspacek.com/dont-let-security-bugs-catch-you-off-guard#github-dependabot
How can I help you explore Laravel packages today?