Description
When multiple closures are defined on the same source line with identical signatures, they all resolve to the first closure after a serialize/unserialize roundtrip. No error is thrown; the wrong closure silently executes.
Reproduction
<?php
require 'vendor/autoload.php';
use Opis\Closure\SerializableClosure;
$closures = [fn() => 'a', fn() => 'b', fn() => 'c'];
$serialized = array_map(function($c) {
return serialize(new SerializableClosure($c));
}, $closures);
$results = array_map(function($s) {
return unserialize($s)();
}, $serialized);
var_dump($results);
// Expected: ['a', 'b', 'c']
// Actual: ['a', 'a', 'a']
Root cause
Two places contribute:
-
AbstractParser::resolve() uses a cache key of {prefix}/{fileKey}/{startLine}/{endLine}. Multiple closures sharing the same line hit the same cache entry, so the second closure returns the first one's parsed info.
-
ClosureParser::findFunctionIndex() scans from getStartLine() and returns the first T_FN/T_FUNCTION token it finds. There is no mechanism to distinguish which closure on that line corresponds to which \Closure object.
Impact
This affects any code that serializes arrays of inline closures, e.g. job chains, pipeline stages, callback arrays. The same bug exists in laravel/serializable-closure (issue laravel/serializable-closure#131) and a fix is in progress there.
Multi-line closures (each on their own line) are not affected.
Environment
- opis/closure: 4.5.0
- PHP: 8.4.19
- OS: Windows 11
Description
When multiple closures are defined on the same source line with identical signatures, they all resolve to the first closure after a serialize/unserialize roundtrip. No error is thrown; the wrong closure silently executes.
Reproduction
Root cause
Two places contribute:
AbstractParser::resolve()uses a cache key of{prefix}/{fileKey}/{startLine}/{endLine}. Multiple closures sharing the same line hit the same cache entry, so the second closure returns the first one's parsed info.ClosureParser::findFunctionIndex()scans fromgetStartLine()and returns the firstT_FN/T_FUNCTIONtoken it finds. There is no mechanism to distinguish which closure on that line corresponds to which\Closureobject.Impact
This affects any code that serializes arrays of inline closures, e.g. job chains, pipeline stages, callback arrays. The same bug exists in
laravel/serializable-closure(issue laravel/serializable-closure#131) and a fix is in progress there.Multi-line closures (each on their own line) are not affected.
Environment