From 605b1278f74dbda7434b531ec1928aa2b837cecf Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Fri, 25 Sep 2026 23:34:59 +0200 Subject: [PATCH] Reject a Template instance created by another environment when resolving templates --- CHANGELOG | 1 + src/Environment.php | 4 ++++ tests/EnvironmentTest.php | 16 ++++++++++++++++ 3 files changed, 21 insertions(+) diff --git a/CHANGELOG b/CHANGELOG index 07baad014..f7798eaa4 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,6 @@ # 3.30.1 (2026-XX-XX) + * Reject a deprecated `Template` instance created by another environment in `Environment::resolveTemplate()` * Speed up reading object attributes backed by getters or class constants # 3.30.0 (2026-09-25) diff --git a/src/Environment.php b/src/Environment.php index ddd779629..354ea89a4 100644 --- a/src/Environment.php +++ b/src/Environment.php @@ -514,6 +514,10 @@ class Environment if ($name instanceof Template) { trigger_deprecation('twig/twig', '3.9', 'Passing a "%s" instance to "%s" is deprecated.', Template::class, __METHOD__); + if (!$name->isOwnedBy($this)) { + throw new RuntimeError(\sprintf('A "%s" can only be used with the "%s" that created it.', Template::class, self::class)); + } + return new TemplateWrapper($this, $name); } if ($name instanceof TemplateWrapper) { diff --git a/tests/EnvironmentTest.php b/tests/EnvironmentTest.php index cd9511e86..caa0eaab1 100644 --- a/tests/EnvironmentTest.php +++ b/tests/EnvironmentTest.php @@ -96,6 +96,22 @@ class EnvironmentTest extends TestCase $twig->load($foreign->load('index')); } + /** + * @group legacy + */ + #[Group('legacy')] + public function testResolveTemplateRejectsTemplateFromAnotherEnvironment(): void + { + $foreign = new Environment(new ArrayLoader(['index' => 'foreign'])); + $twig = new Environment(new ArrayLoader()); + + $this->expectDeprecation('Since twig/twig 3.9: Passing a "Twig\Template" instance to "Twig\Environment::resolveTemplate" is deprecated.'); + $this->expectException(RuntimeError::class); + $this->expectExceptionMessage('A "Twig\Template" can only be used with the "Twig\Environment" that created it.'); + + $twig->resolveTemplate([$foreign->load('index')->unwrap($foreign)]); + } + /** * @group legacy */