| 1 |
<?php |
| 2 |
|
| 3 |
namespace Illuminate\Support; |
| 4 |
|
| 5 |
use WeakMap; |
| 6 |
|
| 7 |
class Once |
| 8 |
{ |
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
protected static ?self $instance = null; |
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
protected static bool $enabled = true; |
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
protected function __construct(protected WeakMap $values) |
| 29 |
{ |
| 30 |
|
| 31 |
} |
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
public static function instance() |
| 39 |
{ |
| 40 |
return static::$instance ??= new static(new WeakMap); |
| 41 |
} |
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
public function value(Onceable $onceable) |
| 50 |
{ |
| 51 |
if (! static::$enabled) { |
| 52 |
return call_user_func($onceable->callable); |
| 53 |
} |
| 54 |
|
| 55 |
$object = $onceable->object ?: $this; |
| 56 |
|
| 57 |
$hash = $onceable->hash; |
| 58 |
|
| 59 |
if (! isset($this->values[$object])) { |
| 60 |
$this->values[$object] = []; |
| 61 |
} |
| 62 |
|
| 63 |
if (array_key_exists($hash, $this->values[$object])) { |
| 64 |
return $this->values[$object][$hash]; |
| 65 |
} |
| 66 |
|
| 67 |
return $this->values[$object][$hash] = call_user_func($onceable->callable); |
| 68 |
} |
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
public static function enable() |
| 76 |
{ |
| 77 |
static::$enabled = true; |
| 78 |
} |
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
public static function disable() |
| 86 |
{ |
| 87 |
static::$enabled = false; |
| 88 |
} |
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
public static function flush() |
| 96 |
{ |
| 97 |
static::$instance = null; |
| 98 |
} |
| 99 |
} |