Debian Codegraph @

lib/3rdParty/composer/illuminate/support/Once.php

raw symbols SCIP
1 <?php
2
3 namespace Illuminate\Support;
4
5 use WeakMap;
6
7 class Once
8 {
9 /**
10 * The current globally used instance.
11 *
12 * @var static|null
13 */
14 protected static ?self $instance = null;
15
16 /**
17 * Indicates if the once instance is enabled.
18 *
19 * @var bool
20 */
21 protected static bool $enabled = true;
22
23 /**
24 * Create a new once instance.
25 *
26 * @param \WeakMap<object, array<string, mixed>> $values
27 */
28 protected function __construct(protected WeakMap $values)
29 {
30 //
31 }
32
33 /**
34 * Create a new once instance.
35 *
36 * @return static
37 */
38 public static function instance()
39 {
40 return static::$instance ??= new static(new WeakMap);
41 }
42
43 /**
44 * Get the value of the given onceable.
45 *
46 * @param Onceable $onceable
47 * @return mixed
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 * Re-enable the once instance if it was disabled.
72 *
73 * @return void
74 */
75 public static function enable()
76 {
77 static::$enabled = true;
78 }
79
80 /**
81 * Disable the once instance.
82 *
83 * @return void
84 */
85 public static function disable()
86 {
87 static::$enabled = false;
88 }
89
90 /**
91 * Flush the once instance.
92 *
93 * @return void
94 */
95 public static function flush()
96 {
97 static::$instance = null;
98 }
99 }