Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace Lazy;
- class Lazy
- {
- /**
- * @var callable
- */
- private $callable;
- /**
- * @var Context
- */
- private $context;
- /**
- * @var bool
- */
- private $cacheable = true;
- /**
- * @var mixed
- */
- private $cache;
- /**
- * @param callable $callable
- * @param Context|null $context
- */
- public function __construct(callable $callable, Context $context = null)
- {
- $this->callable = $callable;
- if ($context === null) {
- $context = new Context();
- }
- $this->context = $context;
- }
- /**
- * @return mixed
- */
- private function invoke()
- {
- $this->context->lazy($this);
- if (!$this->cache || !$this->cacheable) {
- $callable = $this->callable;
- $this->cache = $callable($this->context);
- }
- return $this->cache;
- }
- /**
- * @return string
- */
- public function __toString()
- {
- return (string)$this->invoke();
- }
- /**
- * @param $property
- * @return mixed
- */
- public function __get($property)
- {
- return $this->invoke()->{$property};
- }
- /**
- * @param $property
- * @param $value
- * @return mixed
- */
- public function __set($property, $value)
- {
- return $this->invoke()->{$property} = $value;
- }
- /**
- * @param $method
- * @param $arguments
- * @return mixed
- */
- public function __call($method, $arguments)
- {
- return call_user_func_array([$this->invoke(), $method], $arguments);
- }
- /**
- * @return mixed
- */
- public function __invoke()
- {
- return $this->invoke();
- }
- public function disableCache()
- {
- $this->cacheable = false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement