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