Once.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. * @return void
  23. */
  24. protected function __construct(protected WeakMap $values)
  25. {
  26. //
  27. }
  28. /**
  29. * Create a new once instance.
  30. *
  31. * @return static
  32. */
  33. public static function instance()
  34. {
  35. return static::$instance ??= new static(new WeakMap);
  36. }
  37. /**
  38. * Get the value of the given onceable.
  39. *
  40. * @param Onceable $onceable
  41. * @return mixed
  42. */
  43. public function value(Onceable $onceable)
  44. {
  45. if (! static::$enabled) {
  46. return call_user_func($onceable->callable);
  47. }
  48. $object = $onceable->object ?: $this;
  49. $hash = $onceable->hash;
  50. if (isset($this->values[$object][$hash])) {
  51. return $this->values[$object][$hash];
  52. }
  53. if (! isset($this->values[$object])) {
  54. $this->values[$object] = [];
  55. }
  56. return $this->values[$object][$hash] = call_user_func($onceable->callable);
  57. }
  58. /**
  59. * Re-enable the once instance if it was disabled.
  60. *
  61. * @return void
  62. */
  63. public static function enable()
  64. {
  65. static::$enabled = true;
  66. }
  67. /**
  68. * Disable the once instance.
  69. *
  70. * @return void
  71. */
  72. public static function disable()
  73. {
  74. static::$enabled = false;
  75. }
  76. /**
  77. * Flush the once instance.
  78. *
  79. * @return void
  80. */
  81. public static function flush()
  82. {
  83. static::$instance = null;
  84. }
  85. }