rectorphp/rector-symfony

Replace ParameterBagInterface with #[Autowire()] attribute

pedrocasado opened this issue · 2 comments

Replace ParameterBagInterface with #[Autowire()] attribute

Example below:

<?php

-use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
+use Symfony\Component\DependencyInjection\Attribute\Autowire;
 
 class CertificateFactory
 {
     protected ?string $certName;
     protected ?string $certPath;
 
-    public function __construct(ParameterBagInterface $parameterBag)
-    {
-        $this->certName = $parameterBag->get('certificate_name');
-        $this->certPath = $parameterBag->get('certificate_folder');
+    public function __construct(
+        #[Autowire('%env(CERT_NAME)%')] ?string $certName,
+        #[Autowire('%env(CERT_PATH)%')] ?string $certPath,
+    ) {
+        $this->certName = $certName;
+        $this->certPath = $certPath;

Does it makes sense?

This can also be replaced with constructor property promotion further.

In case of actual parameters it might be preferable to use #[Autowire(param: 'certificate_name')], and in case of %env(...)% it might be preferable to use #[Autowire(env: 'CERT_NAME')], as they're more explicit.

And/or a separate rule might exist for this. This as the #[Autowire('%param%')] works since 6.1 (the version where #[Autowire] was added). Only in 6.3 (named) arguments were added for param: 'param name', env: 'environment variable name', etc

Resolved in #654