Skip to content

Multiple closures on the same line all resolve to the first one #164

@JoshSalway

Description

@JoshSalway

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:

  1. 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.

  2. 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions