| 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 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
public function __construct( |
| 19 |
public string $hash, |
| 20 |
public ?object $object, |
| 21 |
public $callable, |
| 22 |
) { |
| 23 |
|
| 24 |
} |
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 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 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
protected static function objectFromTrace(array $trace) |
| 48 |
{ |
| 49 |
return $trace[1]['object'] ?? null; |
| 50 |
} |
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 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 |
} |