SplSubjectWithObserversTrait::notify()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 5
nc 3
nop 0
dl 0
loc 10
ccs 4
cts 4
cp 1
crap 3
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace EngineWorks\ProgressStatus;
6
7
use EngineWorks\ProgressStatus\Tests\Mocks\Observer;
8
use LogicException;
9
use SplObserver;
10
use SplSubject;
11
12
/**
13
 * Implementation of SplSubject interface using the ObserversSet object storage.
14
 */
15
trait SplSubjectWithObserversTrait
16
{
17
    /** @var ObserversSet */
18
    private $observers;
19 25
20
    private function constructSplSubjectWithObservers(): void
21 25
    {
22
        $this->observers = new ObserversSet();
23
    }
24 4
25
    public function attach(SplObserver $observer): void
26 4
    {
27
        $this->observers->attach($observer);
28
    }
29 1
30
    public function detach(SplObserver $observer): void
31 1
    {
32
        $this->observers->detach($observer);
33
    }
34 24
35
    public function notify(): void
36 24
    {
37
        if (! $this instanceof SplSubject) {
38 1
            throw new LogicException(sprintf('Object %s is not an instance of SplSubject', get_class($this)));
39
        }
40 23
        /** @phpstan-var ObserversSet $observers */
41 3
        $observers = $this->getObservers();
42
        /** @phpstan-var Observer $observer */
43
        foreach ($observers as $observer) {
44
            $observer->update($this);
45 24
        }
46
    }
47 24
48
    private function getObservers(): ObserversSet
49
    {
50
        return $this->observers;
51
    }
52
}
53