| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentCommunity\Framework\Support; |
| 4 |
|
| 5 |
class Once |
| 6 |
{ |
| 7 |
protected $trace = null; |
| 8 |
|
| 9 |
protected $zeroStack = null; |
| 10 |
|
| 11 |
public function __construct(array $trace) |
| 12 |
{ |
| 13 |
$this->trace = $trace[1]; |
| 14 |
|
| 15 |
$this->zeroStack = $trace[0]; |
| 16 |
} |
| 17 |
|
| 18 |
public function getArguments() |
| 19 |
{ |
| 20 |
return $this->trace['args']; |
| 21 |
} |
| 22 |
|
| 23 |
public function getFunctionName() |
| 24 |
{ |
| 25 |
return $this->trace['function']; |
| 26 |
} |
| 27 |
|
| 28 |
public function getObjectName() |
| 29 |
{ |
| 30 |
return $this->trace['class'] ?? null; |
| 31 |
} |
| 32 |
|
| 33 |
public function getObject() |
| 34 |
{ |
| 35 |
if ($this->globalFunction()) { |
| 36 |
return $this->zeroStack['file']; |
| 37 |
} |
| 38 |
|
| 39 |
return $this->staticCall() ? $this->trace['class'] : $this->trace['object']; |
| 40 |
} |
| 41 |
|
| 42 |
public function getHash($strict) |
| 43 |
{ |
| 44 |
$normalizedArguments = array_map(function ($argument) { |
| 45 |
return is_object($argument) ? spl_object_hash($argument) : $argument; |
| 46 |
}, $this->getArguments()); |
| 47 |
|
| 48 |
$object = $this->getObject(); |
| 49 |
|
| 50 |
$prefix = $this->getObjectName() . $this->getFunctionName(); |
| 51 |
|
| 52 |
if ($strict) { |
| 53 |
$prefix .= is_object($object) ? spl_object_id($object) : $object; |
| 54 |
} |
| 55 |
|
| 56 |
if (str_contains($prefix, '{closure')) { |
| 57 |
$prefix = $this->zeroStack['line']; |
| 58 |
} |
| 59 |
|
| 60 |
return md5($prefix.serialize($normalizedArguments)); |
| 61 |
} |
| 62 |
|
| 63 |
protected function staticCall() |
| 64 |
{ |
| 65 |
return $this->trace['type'] === '::'; |
| 66 |
} |
| 67 |
|
| 68 |
protected function globalFunction() |
| 69 |
{ |
| 70 |
return !isset($this->trace['type']); |
| 71 |
} |
| 72 |
|
| 73 |
public static function call(callable $callback, $strict = false) |
| 74 |
{ |
| 75 |
$backtrace = new static(debug_backtrace( |
| 76 |
DEBUG_BACKTRACE_PROVIDE_OBJECT, 2 |
| 77 |
)); |
| 78 |
|
| 79 |
$hash = $backtrace->getHash($strict); |
| 80 |
|
| 81 |
if (!$result = wp_cache_get($hash)) { |
| 82 |
wp_cache_set( |
| 83 |
$hash, call_user_func_array( |
| 84 |
$callback, $backtrace->getArguments() |
| 85 |
) |
| 86 |
); |
| 87 |
} |
| 88 |
|
| 89 |
return wp_cache_get($hash); |
| 90 |
} |
| 91 |
} |
| 92 |
|