How to Upgrade Twig from Underscored to Namespaces

Symfony recently announced a new version of Twig with namespaces as we know it. Before PHP 5.2 there was Underscored_Namespace - I remember because that was the first version I used.

Today I'll show you how to upgrade from _ to \\ in few minutes seconds.

This set would not be possible and as good as it is without you, open-source PHP community. I'd like to thank 👏:

Find and Replace?

So all we need to do is replace Twig_ with Twig\?


This would fail since Twig\Function class doesn't exist. Twig\TwigFunction does. There 150 more cases where find and replace fails.

2 Places

We need to replace both docblocks:

- * @throws \Twig_Error_Loader
+ * @throws \Twig\Error\LoaderError
 public function render(): void
-    /** @var \Twig_Environment $env */
+    /** @var \Twig\Environment $env */
     $env = $this->getTwigEnv();

     // ...

And the code:

-$safeTwigEnvironment = new \Twig_Environment(
+$safeTwigEnvironment = new \Twig\Environment(
-   new \Twig_Loader_Array([])
+   new \Twig\Loader\ArrayLoader([])

In a reaction to the Symfony blog post, I see many developers do upgrades manually. In case of 50 changes, it's ok, but private code bases will go 1000+ use cases.

Code Pattern Refactoring

For Rector it just 1 pattern to refactor. Just tell him to process your files src:

composer require rector/rector --dev # make sure you have version 0.4.10+ at least
vendor/bin/rector process src --level twig-underscore-to-namespace

Happy coding!

Found a typo? Fix it to join team of 64 people that improve content here

❤️️ Do you like what I write about? Or do you hate it but enjoy discussion? 😠
You can support my writing by throwing a couple bucks at my Patreon