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

Observer::notify()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 5.024

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 3
cts 5
cp 0.6
rs 9.9332
c 0
b 0
f 0
cc 4
nc 3
nop 2
crap 5.024
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