spaze / phpstan-disallowed-calls

PHPStan rules to detect disallowed method & function calls, constant, namespace, attribute & superglobal usages
MIT License
255 stars 17 forks source link

FeatureRequest: `disallowDirectory` #194

Closed BackEndTea closed 1 year ago

BackEndTea commented 1 year ago

In one of our projects we'd like to disallow any usage of functions or classes that are declared in a specific directory.

This directory contains a lot of our legacy code, but unfortunately it isn't PSR-4, and doens't have namespaces. Which means there is no easy way to forbid usage of that directory with this plugin.

spaze commented 1 year ago

Are you adding some new code to that directory, or would a one-off script to generate the config be enough? I already have a somewhat similar script to generate config from disable_functions/disable_classes config.

But I think that maybe an extra config would also work, like for example:

parameters:
    disallowedMethodCalls:
        -
            method: log()
            definedIn: foo/bar.php

definedIn would be matched using fnmatch(), while method already is, so you could have a config like this:

parameters:
    disallowedMethodCalls:
        -
            method: *
            definedIn: foo/*

and method, in this case any method, would be disallowed when defined in foo/. It may be implemented for attributes too, not just methods/functions.

BackEndTea commented 1 year ago

Are you adding some new code to that directory, or would a one-off script to generate the config be enough

It probably would be, but i'd rather be sure that even if new code is addd there, its not being added to our project.

For reference, the directory is in our vendor folder, its a legacy composer package, that is being used in multiple projects. So i can't guarantee that no new files will be added there.

spaze commented 1 year ago

Hey @BackEndTea sorry this got delayed, got sick before I was able to finish it. I went with the definedIn config option for functions and methods, there's even an example in the README (and matching MethodCallsDefinedInTest) that should match what you're trying to do:

parameters:
    disallowedFunctionCalls:
        -
            function: '*'
            definedIn:
                - 'vendor/foo/bar'
    disallowedMethodCalls:
        -
            method: '*'
            definedIn:
                - 'vendor/foo/bar'
    filesRootDir: %rootDir%/../../..

Let me know if it works for you and feel free to buy me a 🍺 or a ☕ if it does 😊 I'll tag and release it very soon.

spaze commented 1 year ago

Released in 2.15.0 now.