From 55f7969d1cf4cf61f5d3695bfe966ce4004ef286 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Tvrd=C3=ADk?= Date: Tue, 27 Jan 2026 12:57:20 +0100 Subject: [PATCH 1/2] fix: prevent memory leak in shutdown handler using WeakReference The register_shutdown_function was holding a strong reference to $this, preventing garbage collection until script termination. This change wraps the reference in a WeakReference, allowing normal garbage collection while still cleaning up temporary files at shutdown if the object still exists. --- src/Knp/Snappy/AbstractGenerator.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Knp/Snappy/AbstractGenerator.php b/src/Knp/Snappy/AbstractGenerator.php index 529bc7c..b2ed4c4 100644 --- a/src/Knp/Snappy/AbstractGenerator.php +++ b/src/Knp/Snappy/AbstractGenerator.php @@ -74,7 +74,10 @@ public function __construct($binary, array $options = [], array|null $env = null $this->env = empty($env) ? null : $env; if (\is_callable([$this, 'removeTemporaryFiles'])) { - \register_shutdown_function([$this, 'removeTemporaryFiles']); + $ref = \WeakReference::create($this); + \register_shutdown_function(static function () use ($ref): void { + $ref->get()?->removeTemporaryFiles(); + }); } } From 5a9b7f2ebd702125592a7b9907f9ca70f2690c76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Tvrd=C3=ADk?= Date: Tue, 27 Jan 2026 12:59:32 +0100 Subject: [PATCH 2/2] style: add use statement for WeakReference --- src/Knp/Snappy/AbstractGenerator.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Knp/Snappy/AbstractGenerator.php b/src/Knp/Snappy/AbstractGenerator.php index b2ed4c4..0e9a6c7 100644 --- a/src/Knp/Snappy/AbstractGenerator.php +++ b/src/Knp/Snappy/AbstractGenerator.php @@ -7,9 +7,10 @@ use Psr\Log\LoggerAwareTrait; use Symfony\Component\Process\Process; use Exception; +use InvalidArgumentException; use LogicException; use RuntimeException; -use InvalidArgumentException; +use WeakReference; /** * Base generator class for medias. @@ -74,7 +75,7 @@ public function __construct($binary, array $options = [], array|null $env = null $this->env = empty($env) ? null : $env; if (\is_callable([$this, 'removeTemporaryFiles'])) { - $ref = \WeakReference::create($this); + $ref = WeakReference::create($this); \register_shutdown_function(static function () use ($ref): void { $ref->get()?->removeTemporaryFiles(); });