Completed
Push — master ( b4fe79...e03f7c )
by Iman
03:39
created

EloquentEventsManager   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 55
ccs 20
cts 20
cp 1
rs 10
c 0
b 0
f 0
wmc 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 6 1
A commitChain() 0 5 2
A start() 0 6 4
A forgetAbout() 0 7 3
1
<?php
2
3
namespace Imanghafoori\HeyMan\WatchingStrategies;
4
5
use Imanghafoori\HeyMan\HeyManSwitcher;
6
7
class EloquentEventsManager
8
{
9
    private $event;
10
11
    private $modelClass;
12
13
    private $data = [];
14
15
    /**
16
     * EloquentEventsManager constructor.
17
     *
18
     * @param $event
19
     * @param $modelClass
20
     *
21
     * @return EloquentEventsManager
22
     */
23 15
    public function init(string $event, array $modelClass) : self
24
    {
25 15
        $this->event = $event;
26 15
        $this->modelClass = $modelClass;
27
28 15
        return $this;
29
    }
30
31
    /**
32
     * @param $callback
33
     */
34 15
    public function commitChain(callable $callback)
35
    {
36 15
        $callback = app(HeyManSwitcher::class)->wrapForIgnorance($callback, 'eloquent');
37 15
        foreach ($this->modelClass as $model) {
38 15
            $this->data[$model][$this->event][] = $callback;
39
        }
40
41
42 15
    }
43
44 105
    public function start()
45
    {
46 105
        foreach ($this->data as $model => $data) {
47 13
            foreach ($data as $event => $cb) {
48 11
                foreach ($cb as $c) {
49 13
                    $model::{$event}($c);
50
                }
51
            }
52
        }
53 105
    }
54
55 4
    public function forgetAbout($models, $event = null)
56
    {
57 4
        foreach ($models as $model) {
58 4
            if (is_null($event)) {
59 1
                unset($this->data[$model]);
60
            } else {
61 4
                unset($this->data[$model][$event]);
62
            }
63
        }
64 4
    }
65
}
66