Once.php 1.9 KB

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