1 | <?php |
||
2 | |||
3 | /** |
||
4 | * This file is part of the miBadger package. |
||
5 | * |
||
6 | * @author Michael Webbers <[email protected]> |
||
7 | * @license http://opensource.org/licenses/Apache-2.0 Apache v2 License |
||
8 | */ |
||
9 | |||
10 | namespace miBadger\Observer; |
||
11 | |||
12 | /** |
||
13 | * The subject trait of the observer pattern. |
||
14 | * |
||
15 | * @see http://en.wikipedia.org/wiki/Observer_pattern |
||
16 | * @since 1.0.0 |
||
17 | */ |
||
18 | trait SubjectTrait |
||
19 | { |
||
20 | /** @var ObserverInterface[] The attached observers. */ |
||
21 | private $observers = []; |
||
22 | |||
23 | /** |
||
24 | * Returns true if the observer is attached to the subject. |
||
25 | * |
||
26 | * @param ObserverInterface $observer |
||
27 | * @return bool true if the observer is attached to the subject. |
||
28 | */ |
||
29 | 3 | public function isAttached(ObserverInterface $observer) |
|
30 | { |
||
31 | 3 | return in_array($observer, $this->observers); |
|
32 | } |
||
33 | |||
34 | /** |
||
35 | * Returns true if the observer is attached successfully. |
||
36 | * |
||
37 | * @param ObserverInterface $observer |
||
38 | * @return bool true if the observer is attached successfully. |
||
39 | */ |
||
40 | 3 | public function attach(ObserverInterface $observer) |
|
41 | { |
||
42 | 3 | if ($this->isAttached($observer)) { |
|
43 | 1 | return false; |
|
44 | } |
||
45 | |||
46 | 3 | $this->observers[] = $observer; |
|
47 | |||
48 | 3 | return true; |
|
49 | } |
||
50 | |||
51 | /** |
||
52 | * Returns true if the observer is detached successfully. |
||
53 | * |
||
54 | * @param ObserverInterface $observer |
||
55 | * @return bool true if the observer is detached successfully. |
||
56 | */ |
||
57 | 1 | public function detach(ObserverInterface $observer) |
|
58 | { |
||
59 | 1 | foreach ($this->observers as $key => $value) { |
|
60 | 1 | if ($value === $observer) { |
|
61 | 1 | unset($this->observers[$key]); |
|
62 | |||
63 | 1 | return true; |
|
64 | } |
||
65 | } |
||
66 | |||
67 | 1 | return false; |
|
68 | } |
||
69 | |||
70 | /** |
||
71 | * Notify all the attached observers. |
||
72 | * |
||
73 | * @param mixed $arguments |
||
74 | * @return null |
||
75 | */ |
||
76 | 1 | public function notify($arguments = null) |
|
77 | { |
||
78 | 1 | foreach ($this->observers as $observer) { |
|
79 | 1 | $observer->update($this, $arguments); |
|
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
80 | } |
||
81 | 1 | } |
|
82 | } |
||
83 |