Lines
100.00%
9 / 9
Functions and Methods
100.00%
3 / 3
Classes and Traits
100.00%
1 / 1
| Name | Lines | Functions and Methods | CRAP | Classes and Traits | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Observable | 100.00% | 9 / 9 | 100.00% | 3 / 3 | 5 | 100.00% | 1 / 1 | |||
| subscribe | 100.00% | 3 / 3 | 100.00% | 1 / 1 | 2 | |||||
| unsubscribe | 100.00% | 4 / 4 | 100.00% | 1 / 1 | 1 | |||||
| notify | 100.00% | 2 / 2 | 100.00% | 1 / 1 | 2 | |||||
| 1 | <?php | |
| 2 | ||
| 3 | declare(strict_types=1); | |
| 4 | ||
| 5 | namespace Lorekeeper\Client; | |
| 6 | ||
| 7 | use Psl\Observer\ObserverInterface; | |
| 8 | use Psl\Observer\SubjectInterface; | |
| 9 | ||
| 10 | /** @require-implements SubjectInterface */ | |
| 11 | trait Observable | |
| 12 | { | |
| 13 | /** @var list<ObserverInterface<SubjectInterface>> */ | |
| 14 | private array $observers = []; | |
| 15 | ||
| 16 | /** @param ObserverInterface<SubjectInterface> $observer */ | |
| 17 | public function subscribe(ObserverInterface $observer): void | |
| 18 | { | |
| 19 | if (in_array($observer, $this->observers, strict: true)) { | |
| 20 | return; | |
| 21 | } | |
| 22 | ||
| 23 | $this->observers[] = $observer; | |
| 24 | } | |
| 25 | ||
| 26 | /** @param ObserverInterface<SubjectInterface> $observer */ | |
| 27 | public function unsubscribe(ObserverInterface $observer): void | |
| 28 | { | |
| 29 | $this->observers = array_values(array_filter( | |
| 30 | $this->observers, | |
| 31 | static fn(ObserverInterface $subscribed): bool => $subscribed !== $observer, | |
| 32 | )); | |
| 33 | } | |
| 34 | ||
| 35 | public function notify(): void | |
| 36 | { | |
| 37 | foreach ($this->observers as $observer) { | |
| 38 | $observer->update($this); | |
| 39 | } | |
| 40 | } | |
| 41 | } |