Skip to content

rule idea: disallow some types from being used as parameter type and/or return types #337

@stof

Description

@stof

I have 2 use cases for that in my (Symfony) projects:

  • I have a few services for which I definitely want usages to rely on the interface, because the interface autowiring would inject a decorated instance (performing some caching). In an open-source bundle, I would register the concrete implementation using a non-FQCN id so that it is not exposed to the Symfony autowiring. But in private projects, relying on the PSR-4 discovery feature makes DX much better so I'd rather avoid having to do special cases (and ensuring that PSR-4 discovery used for other classes does not re-register those classes). Detecting parameters typed with the concrete implementation for those special cases during the phpstan analysis would still prevent bad usages without the drawbacks on DX.
  • \Symfony\Component\Translation\TranslatableMessage implements both \Symfony\Contracts\Translation\TranslatableInterface and Stringable. The correct usage to get the translated value is $translatableMessage->trans($this->translator) (i.e. using the TranslatableInterface API). However, due to being Stringable, phpstan won't fail on $this->translator->trans($translatableMessage) (and that translation will work if the TranslatableMessage contains a key with no parameters, making it potentially harder to notice that this is broken when the TranslatableMessage object expects to use some parameters or a non-default domain). by forbidding to use a return type of TranslatableMessage (forcing methods to use the interface as their return type instead), we make sure phpstan will report errors in case of invalid usages ($this->translator->trans($translatableInterface) will report an error saying a string is expected but TranslatableInterface is provided)

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions