Observable::detachAll()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
/**
3
 * Observable.
4
 *
5
 * @copyright Copyright (c) 2016 Starweb AB
6
 * @license   BSD 3-Clause
7
 */
8
9
namespace Starlit\Observable;
10
11
use \SplSubject;
12
use \SplObserver;
13
14
/**
15
 * @author Andreas Nilsson <http://github.com/jandreasn>
16
 */
17
abstract class Observable implements SplSubject
18
{
19
    /**
20
     * @var SplObserver[]
21
     */
22
    private $observers = [];
23
24
    /**
25
     * Attach an observer to the set of observers for this object.
26
     *
27
     * @param SplObserver $observer
28
     */
29 3
    public function attach(SplObserver $observer): void
30
    {
31 3
        $objectId = spl_object_hash($observer);
32 3
        $this->observers[$objectId] = $observer;
33 3
    }
34
35
    /**
36
     * Detach an observer from the set of observers for this object.
37
     *
38
     * @param SplObserver $observer
39
     */
40 1
    public function detach(SplObserver $observer): void
41
    {
42 1
        $objectId = spl_object_hash($observer);
43 1
        unset($this->observers[$objectId]);
44 1
    }
45
46
    /**
47
     * Notify all of this object's observers.
48
     */
49 3
    public function notify(): void
50
    {
51 3
        foreach ($this->observers as $observer) {
52 1
            $observer->update($this);
53
        }
54 3
    }
55
56
    /**
57
     * Detaches all observers.
58
     */
59 1
    public function detachAll(): void
60
    {
61 1
        $this->observers = [];
62 1
    }
63
64
    /**
65
     * Magic method called before object unserialization to return the names of all properties to be serialized.
66
     *
67
     * @return array
68
     */
69 1
    public function __sleep(): array
70
    {
71
        // We don't want observers to be serialized, since the reference to current objects are broken
72 1
        $allObjectProperties = array_keys(get_object_vars($this));
73 1
        $exclude = ['observers'];
74 1
        $objectPropertiesToSerialize = array_diff($allObjectProperties, $exclude);
75
76 1
        return $objectPropertiesToSerialize;
77
    }
78
}
79