SseEventCache.php
92 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WPStaging\Framework\Logger; |
| 4 | |
| 5 | use WPStaging\Framework\Adapter\Directory; |
| 6 | use WPStaging\Framework\Utils\Cache\Cache; |
| 7 | |
| 8 | /** |
| 9 | * This class is used to cache the events for the SSE (Server-Sent Events) stream. |
| 10 | * It stores the events in a cache file and allows to push new events, load existing events, |
| 11 | * It is used by BackgroundLogger to push the events to the SSE stream. |
| 12 | */ |
| 13 | class SseEventCache |
| 14 | { |
| 15 | /** |
| 16 | * @var string |
| 17 | */ |
| 18 | const EVENT_TYPE_TASK = 'task'; |
| 19 | |
| 20 | /** |
| 21 | * @var string |
| 22 | */ |
| 23 | const EVENT_TYPE_COMPLETE = 'complete'; |
| 24 | |
| 25 | /** |
| 26 | * @var int |
| 27 | */ |
| 28 | protected $count = 0; |
| 29 | |
| 30 | /** |
| 31 | * @var array |
| 32 | */ |
| 33 | protected $events = []; |
| 34 | |
| 35 | /** |
| 36 | * @var Cache |
| 37 | */ |
| 38 | protected $cache; |
| 39 | |
| 40 | public function __construct(Cache $cache, Directory $directory) |
| 41 | { |
| 42 | $this->cache = $cache; |
| 43 | $this->cache->setPath($directory->getSseCacheDirectory()); |
| 44 | } |
| 45 | |
| 46 | public function setJobId(string $jobId, bool $checkIfExist = false) |
| 47 | { |
| 48 | $this->cache->setFilename($jobId . '.sse'); |
| 49 | if ($checkIfExist && !$this->cache->isValid(false)) { |
| 50 | return false; |
| 51 | } |
| 52 | |
| 53 | return true; |
| 54 | } |
| 55 | |
| 56 | public function push(array $log) |
| 57 | { |
| 58 | $this->events[] = $log; |
| 59 | |
| 60 | $this->count++; |
| 61 | $this->cache->save($this->events); |
| 62 | } |
| 63 | |
| 64 | public function load() |
| 65 | { |
| 66 | if (!$this->cache->isValid()) { |
| 67 | return; |
| 68 | } |
| 69 | |
| 70 | $this->events = $this->cache->get([]); |
| 71 | if (!is_array($this->events)) { |
| 72 | $this->events = []; |
| 73 | } |
| 74 | |
| 75 | $this->count = count($this->events); |
| 76 | } |
| 77 | |
| 78 | public function getCount() |
| 79 | { |
| 80 | return $this->count; |
| 81 | } |
| 82 | |
| 83 | public function getEvents(int $offset = 0) |
| 84 | { |
| 85 | if ($offset >= $this->count) { |
| 86 | return []; |
| 87 | } |
| 88 | |
| 89 | return array_slice($this->events, $offset); |
| 90 | } |
| 91 | } |
| 92 |