Passed
Branch b0.23.0 (6bd3f8)
by Sebastian
04:08
created

Model::set()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
/**
4
 * Linna Framework.
5
 *
6
 * @author Sebastian Rapetti <[email protected]>
7
 * @copyright (c) 2017, Sebastian Rapetti
8
 * @license http://opensource.org/licenses/MIT MIT License
9
 */
10
declare(strict_types=1);
11
12
namespace Linna\Mvc;
13
14
/**
15
 * Parent class for model classes.
16
 *
17
 * This class was implemented like part of Observer pattern
18
 * https://en.wikipedia.org/wiki/Observer_pattern
19
 * http://php.net/manual/en/class.splsubject.php
20
 */
21
class Model implements \SplSubject
22
{
23
    /**
24
     * @var object List of attached observerer
25
     */
26
    private $observers;
27
28
    /**
29
     * @var array Data for notify to observerer
30
     */
31
    private $updates = [];
32
33
    /**
34
     * Constructor.
35
     */
36 28
    public function __construct()
37
    {
38 28
        $this->observers = new \SplObjectStorage();
39 28
    }
40
41
    /**
42
     * Attach an Observer class to this Subject for updates
43
     * when occour a subject state change.
44
     *
45
     * @param \SplObserver $observer
46
     */
47 15
    public function attach(\SplObserver $observer)
48
    {
49 15
        if ($observer instanceof View) {
50 15
            $this->observers->attach($observer);
51
        }
52 15
    }
53
54
    /**
55
     * Detach an Observer class from this Subject.
56
     *
57
     * @param \SplObserver $observer
58
     */
59 1
    public function detach(\SplObserver $observer)
60
    {
61 1
        if ($observer instanceof View) {
62 1
            $this->observers->detach($observer);
63
        }
64 1
    }
65
66
    /**
67
     * Notify a state change of Subject to all registered Observeres.
68
     */
69 15
    public function notify()
70
    {
71 15
        foreach ($this->observers as $value) {
72 15
            $value->update($this);
73
        }
74 15
    }
75
    
76
    /**
77
     * Set the data to notify to all registered Observeres.
78
     *
79
     * @param array $data
80
     */
81 16
    public function set(array $data)
82
    {
83 16
        $this->updates = array_merge_recursive($this->updates, $data);
84 16
    }
85
    
86
    /**
87
     * Get the data to notify to all registered Observeres.
88
     *
89
     * @return array
90
     */
91 16
    public function get() : array
92
    {
93 16
        return $this->updates;
94
    }
95
}
96