Last active
January 8, 2022 20:40
-
-
Save DarkGhostHunter/ba4b90af18169690853427aebed034fd to your computer and use it in GitHub Desktop.
RegeneratesCache class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
use Illuminate\Support\Carbon; | |
use Illuminate\Support\Facades\Cache; | |
use DateTimeInterface; | |
class RegeneratesCache | |
{ | |
/** | |
* When the data has been invalidated. | |
* | |
* @var \Illuminate\Support\Carbon|null | |
*/ | |
protected null|Carbon $invalidAt = null; | |
/** | |
* RegeneratesCache constructor. | |
* | |
* @param string $key | |
* @param int|\DateTimeInterface $ttl | |
* @param null|string $store | |
* @return void | |
*/ | |
public function __construct( | |
protected string $key, | |
protected int|DateTimeInterface $ttl = 60, | |
protected ?string $store = null | |
) | |
{ | |
// | |
} | |
/** | |
* Retrieves the data from the cache. | |
* | |
* @return mixed "null" if the data doesn't exists. | |
*/ | |
public function retrieve(): mixed | |
{ | |
return Cache::store($this->store)->get($this->key); | |
} | |
/** | |
* Checks if it should regenerate. | |
* | |
* @return bool | |
*/ | |
protected function shouldRegenerate(): bool | |
{ | |
if (!$time = Cache::store($this->store)->get($this->key.':time')) { | |
return true; | |
} | |
return (bool) $this->invalidAt?->isAfter($time); | |
} | |
/** | |
* Regenerates a cache. | |
* | |
* @param mixed $data | |
* @param bool $force | |
* @return bool "true" if it was regenerated. | |
*/ | |
public function regenerate(mixed $data, bool $force = false): bool | |
{ | |
if ($force || $this->shouldRegenerate()) { | |
$this->invalidAt = now(); | |
return Cache::store($this->store)->setMultiple([ | |
$this->key => $data, | |
$this->key.':time' => $this->invalidAt | |
], $this->ttl); | |
} | |
return false; | |
} | |
/** | |
* Sets the data as no longer equal to the cache. | |
* | |
* @param bool $forget "true" to forget the data from the cache. | |
* @return $this | |
*/ | |
public function invalidate(bool $forget = false): static | |
{ | |
$this->invalidAt = now(); | |
if ($forget) { | |
tap(Cache::store($this->store)) | |
->forget($this->key) | |
->forget($this->key.':time'); | |
} | |
return $this; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment