Advertisement
Guest User

Untitled

a guest
Sep 3rd, 2015
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. <?php
  2. namespace Lazy;
  3.  
  4. class Lazy
  5. {
  6.  
  7. /**
  8. * @var callable
  9. */
  10. private $callable;
  11.  
  12. /**
  13. * @var Context
  14. */
  15. private $context;
  16.  
  17. /**
  18. * @var bool
  19. */
  20. private $cacheable = true;
  21.  
  22. /**
  23. * @var mixed
  24. */
  25. private $cache;
  26.  
  27. /**
  28. * @param callable $callable
  29. * @param Context|null $context
  30. */
  31. public function __construct(callable $callable, Context $context = null)
  32. {
  33. $this->callable = $callable;
  34.  
  35. if ($context === null) {
  36. $context = new Context();
  37. }
  38.  
  39. $this->context = $context;
  40. }
  41.  
  42. /**
  43. * @return mixed
  44. */
  45. private function invoke()
  46. {
  47. $this->context->lazy($this);
  48.  
  49. if (!$this->cache || !$this->cacheable) {
  50. $callable = $this->callable;
  51. $this->cache = $callable($this->context);
  52. }
  53.  
  54. return $this->cache;
  55. }
  56.  
  57. /**
  58. * @return string
  59. */
  60. public function __toString()
  61. {
  62. return (string)$this->invoke();
  63. }
  64.  
  65. /**
  66. * @param $property
  67. * @return mixed
  68. */
  69. public function __get($property)
  70. {
  71. return $this->invoke()->{$property};
  72. }
  73.  
  74. /**
  75. * @param $property
  76. * @param $value
  77. * @return mixed
  78. */
  79. public function __set($property, $value)
  80. {
  81. return $this->invoke()->{$property} = $value;
  82. }
  83.  
  84. /**
  85. * @param $method
  86. * @param $arguments
  87. * @return mixed
  88. */
  89. public function __call($method, $arguments)
  90. {
  91. return call_user_func_array([$this->invoke(), $method], $arguments);
  92. }
  93.  
  94. /**
  95. * @return mixed
  96. */
  97. public function __invoke()
  98. {
  99. return $this->invoke();
  100. }
  101.  
  102. public function disableCache()
  103. {
  104. $this->cacheable = false;
  105. }
  106. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement