SplSubjectWithObserversTrait   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
dl 0
loc 36
ccs 13
cts 13
cp 1
rs 10
c 1
b 0
f 0
wmc 7

5 Methods

Rating   Name   Duplication   Size   Complexity  
A attach() 0 3 1
A constructSplSubjectWithObservers() 0 3 1
A getObservers() 0 3 1
A notify() 0 10 3
A detach() 0 3 1
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