Skip to content

[DependencyInjection] Deprecate TraitGetByTypeToInjectRector - #1002

Merged
TomasVotruba merged 1 commit into
mainfrom
deprecate-trait-get-by-type
Aug 3, 2026
Merged

[DependencyInjection] Deprecate TraitGetByTypeToInjectRector#1002
TomasVotruba merged 1 commit into
mainfrom
deprecate-trait-get-by-type

Conversation

@TomasVotruba

Copy link
Copy Markdown
Member

TraitGetByTypeToInjectRector turned $this->get(SomeType::class) inside a trait into a @required autowired method:

 trait SomeInjects
 {
+    private SomeType $someType;
+
+    /**
+     * @required
+     */
+    public function autowireSomeInjects(SomeType $someType): void
+    {
+        $this->someType = $someType;
+    }
+
     public function someMethod()
     {
-        return $this->get(SomeType::class);
+        return $this->someType;
     }
 }

Why deprecate

A trait has no context about the class it ends up in. $this->get() is only valid when the trait is used inside an old container-aware Controller/Command, and the rule cannot verify that — it rewrites any trait with a get() call. The generated @required method also only works in a Symfony DI-managed service, which again is unknowable from the trait alone.

The rule was written for one custom project and does not generalize. The class-based siblings (ControllerGetByTypeToConstructorInjectionRector, CommandGetByTypeToConstructorInjectionRector, GetBySymfonyStringToConstructorInjectionRector) do have that context and stay.

Changes

  • rule implements DeprecatedInterface, refactor() throws
  • removed from the symfony-constructor-injection set
  • tests removed
  • AutowireClassMethodFactory removed — it had no other consumer

A trait has no context about the class it is used in, so the $this->get()
call cannot be safely resolved to a constructor/autowired injection. The rule
was built for a single custom project and does not generalize.

Also removes the now-unused AutowireClassMethodFactory and drops the rule from
the symfony-constructor-injection set.
@TomasVotruba
TomasVotruba enabled auto-merge (squash) August 3, 2026 21:34
@TomasVotruba
TomasVotruba merged commit bcd9d2a into main Aug 3, 2026
7 checks passed
@TomasVotruba
TomasVotruba deleted the deprecate-trait-get-by-type branch August 3, 2026 21:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant