|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | +/** |
| 5 | + * This file is part of friendsofhyperf/components. |
| 6 | + * |
| 7 | + * @link https://github.com/friendsofhyperf/components |
| 8 | + * @document https://github.com/friendsofhyperf/components/blob/main/README.md |
| 9 | + * @contact huangdijia@gmail.com |
| 10 | + */ |
| 11 | + |
| 12 | +namespace FriendsOfHyperf\Support; |
| 13 | + |
| 14 | +use WeakMap; |
| 15 | + |
| 16 | +class Once |
| 17 | +{ |
| 18 | + /** |
| 19 | + * The current globally used instance. |
| 20 | + * |
| 21 | + * @var static|null |
| 22 | + */ |
| 23 | + protected static ?self $instance = null; |
| 24 | + |
| 25 | + /** |
| 26 | + * Indicates if the once instance is enabled. |
| 27 | + */ |
| 28 | + protected static bool $enabled = true; |
| 29 | + |
| 30 | + /** |
| 31 | + * Create a new once instance. |
| 32 | + * |
| 33 | + * @param WeakMap<object, array<string, mixed>> $values |
| 34 | + */ |
| 35 | + protected function __construct(protected WeakMap $values) |
| 36 | + { |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * Create a new once instance. |
| 41 | + * |
| 42 | + * @return static |
| 43 | + */ |
| 44 | + public static function instance() |
| 45 | + { |
| 46 | + return static::$instance ??= new static(new WeakMap()); |
| 47 | + } |
| 48 | + |
| 49 | + /** |
| 50 | + * Get the value of the given onceable. |
| 51 | + * |
| 52 | + * @return mixed |
| 53 | + */ |
| 54 | + public function value(Onceable $onceable) |
| 55 | + { |
| 56 | + if (! static::$enabled) { |
| 57 | + return call_user_func($onceable->callable); |
| 58 | + } |
| 59 | + |
| 60 | + $object = $onceable->object ?: $this; |
| 61 | + |
| 62 | + $hash = $onceable->hash; |
| 63 | + |
| 64 | + if (! isset($this->values[$object])) { |
| 65 | + $this->values[$object] = []; |
| 66 | + } |
| 67 | + |
| 68 | + if (array_key_exists($hash, $this->values[$object])) { |
| 69 | + return $this->values[$object][$hash]; |
| 70 | + } |
| 71 | + |
| 72 | + return $this->values[$object][$hash] = call_user_func($onceable->callable); |
| 73 | + } |
| 74 | + |
| 75 | + /** |
| 76 | + * Re-enable the once instance if it was disabled. |
| 77 | + */ |
| 78 | + public static function enable() |
| 79 | + { |
| 80 | + static::$enabled = true; |
| 81 | + } |
| 82 | + |
| 83 | + /** |
| 84 | + * Disable the once instance. |
| 85 | + */ |
| 86 | + public static function disable() |
| 87 | + { |
| 88 | + static::$enabled = false; |
| 89 | + } |
| 90 | + |
| 91 | + /** |
| 92 | + * Flush the once instance. |
| 93 | + */ |
| 94 | + public static function flush() |
| 95 | + { |
| 96 | + static::$instance = null; |
| 97 | + } |
| 98 | +} |
0 commit comments