説明なし

TransientCache.php 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php declare(strict_types = 1);
  2. namespace MailPoet\Cache;
  3. if (!defined('ABSPATH')) exit;
  4. use MailPoet\WP\Functions as WPFunctions;
  5. use MailPoetVendor\Carbon\Carbon;
  6. class TransientCache {
  7. public const SUBSCRIBERS_STATISTICS_COUNT_KEY = 'mailpoet_subscribers_statistics_count_cache';
  8. public const SUBSCRIBERS_GLOBAL_STATUS_STATISTICS_COUNT_KEY = 'mailpoet_subscribers_statistics_count_global_status_cache';
  9. /** @var WPFunctions */
  10. private $wp;
  11. public function __construct(
  12. WPFunctions $wp
  13. ) {
  14. $this->wp = $wp;
  15. }
  16. public function getItem(string $key, int $id): ?array {
  17. $items = $this->getItems($key);
  18. return $items[$id] ?? null;
  19. }
  20. public function getOldestCreatedAt(string $key): ?\DateTime {
  21. $oldest = $this->getOldestItem($key);
  22. return $oldest['created_at'] ?? null;
  23. }
  24. public function getOldestItem(string $key): ?array {
  25. $items = $this->getItems($key);
  26. $oldest = null;
  27. foreach ($items as $item) {
  28. if ($oldest === null || $item['created_at'] < $oldest['created_at']) {
  29. $oldest = $item;
  30. }
  31. }
  32. return $oldest;
  33. }
  34. public function setItem(string $key, array $item, int $id): void {
  35. $items = $this->getItems($key) ?? [];
  36. $items[$id] = [
  37. 'item' => $item,
  38. 'created_at' => Carbon::now(),
  39. ];
  40. $this->setItems($key, $items);
  41. }
  42. public function invalidateItem(string $key, int $id): void {
  43. $items = $this->getItems($key);
  44. unset($items[$id]);
  45. if (count($items)) {
  46. $this->setItems($key, $items);
  47. } else {
  48. $this->deleteItems($key);
  49. }
  50. }
  51. public function invalidateItems(string $key): void {
  52. $this->deleteItems($key);
  53. }
  54. private function deleteItems(string $key): void {
  55. $this->wp->deleteTransient($key);
  56. }
  57. private function setItems(string $key, array $items): void {
  58. $this->wp->setTransient($key, $items);
  59. }
  60. public function getItems(string $key): array {
  61. return $this->wp->getTransient($key) ?: [];
  62. }
  63. }