Debian Codegraph @

lib/3rdParty/composer/illuminate/support/Onceable.php

raw symbols SCIP
1 <?php
2
3 namespace Illuminate\Support;
4
5 use Closure;
6 use Illuminate\Contracts\Support\HasOnceHash;
7 use Laravel\SerializableClosure\Support\ReflectionClosure;
8
9 class Onceable
10 {
11 /**
12 * Create a new onceable instance.
13 *
14 * @param string $hash
15 * @param object|null $object
16 * @param callable $callable
17 */
18 public function __construct(
19 public string $hash,
20 public ?object $object,
21 public $callable,
22 ) {
23 //
24 }
25
26 /**
27 * Tries to create a new onceable instance from the given trace.
28 *
29 * @param array<int, array<string, mixed>> $trace
30 * @return static|null
31 */
32 public static function tryFromTrace(array $trace, callable $callable)
33 {
34 if (! is_null($hash = static::hashFromTrace($trace, $callable))) {
35 $object = static::objectFromTrace($trace);
36
37 return new static($hash, $object, $callable);
38 }
39 }
40
41 /**
42 * Computes the object of the onceable from the given trace, if any.
43 *
44 * @param array<int, array<string, mixed>> $trace
45 * @return object|null
46 */
47 protected static function objectFromTrace(array $trace)
48 {
49 return $trace[1]['object'] ?? null;
50 }
51
52 /**
53 * Computes the hash of the onceable from the given trace.
54 *
55 * @param array<int, array<string, mixed>> $trace
56 * @return string|null
57 */
58 protected static function hashFromTrace(array $trace, callable $callable)
59 {
60 if (str_contains($trace[0]['file'] ?? '', 'eval()\'d code')) {
61 return null;
62 }
63
64 $uses = array_map(
65 static function (mixed $argument) {
66 if ($argument instanceof HasOnceHash) {
67 return $argument->onceHash();
68 }
69
70 if (is_object($argument)) {
71 return spl_object_hash($argument);
72 }
73
74 return $argument;
75 },
76 $callable instanceof Closure ? (new ReflectionClosure($callable))->getClosureUsedVariables() : [],
77 );
78
79 $class = $callable instanceof Closure ? (new ReflectionClosure($callable))->getClosureCalledClass()?->getName() : null;
80
81 $class ??= isset($trace[1]['class']) ? $trace[1]['class'] : null;
82
83 return hash('xxh128', sprintf(
84 '%s@%s%s:%s (%s)',
85 $trace[0]['file'],
86 $class ? $class.'@' : '',
87 $trace[1]['function'],
88 $trace[0]['line'],
89 serialize($uses),
90 ));
91 }
92 }