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

ASubject   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 34
rs 10
wmc 8

5 Methods

Rating   Name   Duplication   Size   Complexity  
A detach() 0 4 2
A attach() 0 9 2
A notify() 0 3 1
A __construct() 0 3 1
A assertNotSelf() 0 4 2
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