Passed
Push — master ( 10edce...c9c069 )
by Aimeos
04:23
created

Traits::notify()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 4
nc 2
nop 2
dl 0
loc 10
rs 10
c 1
b 0
f 0
1
<?php
2
3
/**
4
 * @license LGPLv3, http://opensource.org/licenses/LGPL-3.0
5
 * @copyright Aimeos (aimeos.org), 2019
6
 * @package MW
7
 * @subpackage Observer
8
 */
9
10
11
namespace Aimeos\MW\Observer\Publisher;
12
13
14
/**
15
 * Default implementation of a publisher in the observer pattern
16
 *
17
 * @package MW
18
 * @subpackage Observer
19
 */
20
trait Traits
21
{
22
	protected $listeners = [];
23
24
25
	/**
26
	 * Adds a listener object to the publisher.
27
	 *
28
	 * @param \Aimeos\MW\Observer\Listener\Iface $l Object implementing listener interface
29
	 * @param string $action Name of the action to listen for
30
	 * @return \Aimeos\MW\Observer\Publisher\Iface Publisher object for method chaining
31
	 */
32
	public function attach( \Aimeos\MW\Observer\Listener\Iface $l, $action )
33
	{
34
		$this->listeners[$action][] = $l;
35
		return $this;
36
	}
37
38
39
	/**
40
	 * Removes a listener from the publisher object.
41
	 *
42
	 * @param \Aimeos\MW\Observer\Listener\Iface $l Object implementing listener interface
43
	 * @param string $action Name of the action to remove the listener from
44
	 * @return \Aimeos\MW\Observer\Publisher\Iface Publisher object for method chaining
45
	 */
46
	public function detach( \Aimeos\MW\Observer\Listener\Iface $l, $action )
47
	{
48
		if( isset( $this->listeners[$action] ) )
49
		{
50
			foreach( $this->listeners[$action] as $key => $listener )
51
			{
52
				if( $listener === $l ) {
53
					unset( $this->listeners[$action][$key] );
54
				}
55
			}
56
		}
57
58
		return $this;
59
	}
60
61
62
	/**
63
	 * Removes all attached listeners from the publisher
64
	 *
65
	 * @return \Aimeos\MW\Observer\Publisher\Iface Publisher object for method chaining
66
	 */
67
	public function off()
68
	{
69
		$this->listeners = [];
70
		return $this;
71
	}
72
73
74
	/**
75
	 * Sends updates to all listeners of the given action.
76
	 *
77
	 * @param string $action Name of the action
78
	 * @param mixed $value Value or object given to the listeners
79
	 * @return mixed Modified value parameter
80
	 */
81
	protected function notify( $action, $value = null )
82
	{
83
		if( isset( $this->listeners[$action] ) )
84
		{
85
			foreach( $this->listeners[$action] as $key => $listener ) {
86
				$value = $listener->update( $this, $action, $value );
87
			}
88
		}
89
90
		return $value;
91
	}
92
}
93