rectorphp / rector-symfony

Rector upgrade rules for Symfony
http://getrector.com
MIT License
179 stars 86 forks source link

Replace ParameterBagInterface with #[Autowire()] attribute #648

Closed pedrocasado closed 1 month ago

pedrocasado commented 1 month ago

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.

RobertMe commented 1 month ago

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

TomasVotruba commented 1 month ago

Resolved in https://github.com/rectorphp/rector-symfony/pull/654