← All changes
|
app/Features/AdminNotices/AdminNoticesRepository.php
+73
-0
2.0.0
→
2.1.1
View file →
| @@ -1,0 +1,73 @@ | ||
| 1 | +<?php | |
| 2 | + | |
| 3 | +declare(strict_types=1); | |
| 4 | + | |
| 5 | +namespace Metricool\Features\AdminNotices; | |
| 6 | + | |
| 7 | +use Metricool\Bootstrap\App; | |
| 8 | +use Metricool\Features\AdminNotices\Notices\ReviewNotice; | |
| 9 | +use Metricool\Features\AdminNotices\Notices\UpgradeNotice; | |
| 10 | + | |
| 11 | +class AdminNoticesRepository | |
| 12 | +{ | |
| 13 | + /** | |
| 14 | + * Array of AdminNotice class-strings that should be displayed. | |
| 15 | + * @internal New wp-admin notices should be added here | |
| 16 | + * @var array<int,class-string<AbstractAdminNotice>> | |
| 17 | + */ | |
| 18 | + public array $adminNoticeClassStrings = [ | |
| 19 | + ReviewNotice::class, | |
| 20 | + UpgradeNotice::class, | |
| 21 | + ]; | |
| 22 | + | |
| 23 | + /** @var AbstractAdminNotice[] */ | |
| 24 | + private array $notices = []; | |
| 25 | + | |
| 26 | + public function __construct() | |
| 27 | + { | |
| 28 | + $this->initiateNotices(); | |
| 29 | + } | |
| 30 | + | |
| 31 | + protected function initiateNotices(): void | |
| 32 | + { | |
| 33 | + $app = App::getInstance(); | |
| 34 | + foreach ($this->adminNoticeClassStrings as $classString) { | |
| 35 | + $this->add($app->make($classString)); | |
| 36 | + } | |
| 37 | + } | |
| 38 | + | |
| 39 | + /** | |
| 40 | + * Add a notice instance to the repository. | |
| 41 | + */ | |
| 42 | + public function add(AbstractAdminNotice $notice): AdminNoticesRepository | |
| 43 | + { | |
| 44 | + $this->notices[$notice->getId()] = $notice; | |
| 45 | + | |
| 46 | + return $this; | |
| 47 | + } | |
| 48 | + | |
| 49 | + /** | |
| 50 | + * Get instances of all admin notices. Notice instances are cached after the first retrieval. | |
| 51 | + */ | |
| 52 | + public function all(): array | |
| 53 | + { | |
| 54 | + return $this->notices; | |
| 55 | + } | |
| 56 | + | |
| 57 | + /** | |
| 58 | + * Find a notice instance by its identifier | |
| 59 | + */ | |
| 60 | + public function find(string $id): ?AbstractAdminNotice | |
| 61 | + { | |
| 62 | + return $this->notices[$id] ?? null; | |
| 63 | + } | |
| 64 | + | |
| 65 | + /** | |
| 66 | + * Get all admin notices that should be displayed. | |
| 67 | + * @return AbstractAdminNotice[] | |
| 68 | + */ | |
| 69 | + public function getShouldBeDisplayed(): array | |
| 70 | + { | |
| 71 | + return array_filter($this->notices, fn ($notice) => $notice->shouldDisplay()); | |
| 72 | + } | |
| 73 | +} | |