'Closure not setting variables as expected

For some reason, $uuid & $tags are not being set correctly.

public function handle(Request $request, Closure $next)
    {
        $uuid = null;
        $tags = [];
        Telescope::tag(function (IncomingEntry $entry) use (&$tags, &$uuid) {
            if ($entry->type === 'request') {
                if (isset($entry->content) && isset($entry->content['headers'])) {
                    $headers = $entry->content['headers'];
                    if (isset($headers['x-workflow-id'])) {
                        $tags[] = "workflow-id" . ":" . $headers['x-workflow-id'];
                    }
                    if (isset($headers['x-run-id'])) {
                        $tags[] = "run-id" . ":" . $headers['x-run-id'];
                    }
                    if (isset($headers['x-workflow-type'])) {
                        $tags[] = "workflow-type" . ":" . $headers['x-workflow-type'];
                    }
                    $uuid = $entry->uuid;
                    Log::info("UUID inside closure: " . $uuid);
                    Log::info("Count of tags inside closure: " . count($tags));
                }
            }
            return $tags;
        });
        $response = $next($request);
        Log::info("count of tags outside the closure: " . count($tags));
        Log::info("uuid outside the closure: " . $uuid);
        if (count($tags) > 0) {
            $response->header('X-Telescope-Uuid', $uuid);
        }
        return $response;
    }

By not working mean I have two issues:

  1. $uuid and $tags are not set correctly by the closure
  2. It seems the closure runs after the $response = $next($request); line, which I can't really explain. The logs seem to point that way.

An example run:

[2022-05-12 20:44:55] local.INFO: count of tags outside the closure: 0  
[2022-05-12 20:44:55] local.INFO: uuid outside the closure:   
[2022-05-12 20:44:55] local.INFO: UUID inside closure: 9648a9bd-57df-4263-9c8f-630bbc79e388  
[2022-05-12 20:44:55] local.INFO: Count of tags inside closure: 3

As you can see, the two logs from inside the closure are printed after. If anyone is wondering, this is a middleware I'm making for helping me debug stuff through telescope by

  1. Assigning the tags on telescope
  2. Returning the telescope uuid which will allow me to generate a direct link to the telescope request that was sent to laravel


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source