Passed
Push — master ( de3d61...be839c )
by Alec
13:42 queued 13s
created

ASubject::notify()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AlecRabbit\Spinner\Core\A;
6
7
use AlecRabbit\Spinner\Contract\IObserver;
8
use AlecRabbit\Spinner\Contract\ISubject;
9
use AlecRabbit\Spinner\Exception\InvalidArgumentException;
10
11
abstract class ASubject implements ISubject
12
{
13
    public function __construct(
14
        protected ?IObserver $observer = null,
15
    ) {
16
    }
17
18
    public function notify(): void
19
    {
20
        $this->observer?->update($this);
21
    }
22
23
    public function attach(IObserver $observer): void
24
    {
25
        if ($this->observer !== null) {
26
            throw new InvalidArgumentException('Observer is already attached.');
27
        }
28
29
        $this->assertNotSelf($observer);
30
31
        $this->observer = $observer;
32
    }
33
34
    protected function assertNotSelf(object $obj): void
35
    {
36
        if ($obj === $this) {
37
            throw new InvalidArgumentException('Object can not be self.');
38
        }
39
    }
40
41
    public function detach(IObserver $observer): void
42
    {
43
        if ($this->observer === $observer) {
44
            $this->observer = null;
45
        }
46
    }
47
}
48