Completed
Push — master ( 296743...12eab9 )
by Kirill
36:17
created

Observer   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 30%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 0
dl 0
loc 39
ccs 3
cts 10
cp 0.3
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A subscribe() 0 10 2
A notify() 0 10 4
1
<?php
2
/**
3
 * This file is part of Railt package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
declare(strict_types=1);
9
10
namespace Railt\SDL\Runtime;
11
12
/**
13
 * Trait Observer
14
 * @mixin Observable
15
 */
16
trait Observer
17
{
18
    /**
19
     * @var array|\Closure[]
20
     */
21
    private $observers = [];
22
23
    /**
24
     * @param \Closure $observer
25
     * @param bool $prepend
26
     * @return Observable
27
     */
28
    public function subscribe(\Closure $observer, bool $prepend = false): Observable
29
    {
30
        if ($prepend) {
31
            \array_unshift($this->observers, $observer);
32
        } else {
33
            $this->observers[] = $observer;
34
        }
35
36
        return $this;
37
    }
38
39
    /**
40
     * @param mixed $payload
41
     * @param bool $overwrite
42
     * @return mixed
43
     */
44 6577
    protected function notify($payload, bool $overwrite = false)
45
    {
46 6577
        foreach ($this->observers as $observer) {
47
            if ($overwrite && ($data = $observer($payload)) !== null) {
48
                $payload = $data;
49
            }
50
        }
51
52 6577
        return $payload;
53
    }
54
}
55