SubjectTrait   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 14
c 2
b 0
f 0
dl 0
loc 62
ccs 16
cts 16
cp 1
rs 10
wmc 8

4 Methods

Rating   Name   Duplication   Size   Complexity  
A attach() 0 9 2
A notify() 0 4 2
A isAttached() 0 3 1
A detach() 0 11 3
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
$this of type miBadger\Observer\SubjectTrait is incompatible with the type miBadger\Observer\SubjectInterface expected by parameter $subject of miBadger\Observer\ObserverInterface::update(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

79
			$observer->update(/** @scrutinizer ignore-type */ $this, $arguments);
Loading history...
80
		}
81 1
	}
82
}
83