ListenerCapableTrait   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 0
dl 0
loc 44
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A setProvider() 0 5 1
eventsListening() 0 1 ?
A attachListeners() 0 11 3
1
<?php
2
3
/**
4
 * Phoole (PHP7.2+)
5
 *
6
 * @category  Library
7
 * @package   Phoole\Event
8
 * @copyright Copyright (c) 2019 Hong Zhang
9
 */
10
declare(strict_types=1);
11
12
namespace Phoole\Event;
13
14
/**
15
 * ListenerCapableTrait
16
 *
17
 * Classes use this trait will be able to listen to events
18
 *
19
 * @package Phoole\Event
20
 */
21
trait ListenerCapableTrait
22
{
23
    /**
24
     * @var Provider
25
     */
26
    protected $provider;
27
28
    /**
29
     * @param  Provider $provider
30
     */
31
    public function setProvider(Provider $provider): void
32
    {
33
        $this->provider = $provider;
34
        $this->attachListeners();
35
    }
36
37
    /**
38
     * Returns array of ['classMethodName', int priority]
39
     *
40
     * e.g.
41
     * return [
42
     *     'methodOne',
43
     *     ['methodTwo', 50],
44
     * ];
45
     *
46
     * @return array
47
     */
48
    abstract protected function eventsListening(): array;
49
50
    /**
51
     * attach $this related listener callable to the provider
52
     */
53
    protected function attachListeners()
54
    {
55
        foreach ($this->eventsListening() as $method) {
56
            if (is_array($method)) {
57
                list($method, $priority) = $method;
58
                $this->provider->attach([$this, $method], $priority);
59
            } else {
60
                $this->provider->attach([$this, $method]);
61
            }
62
        }
63
    }
64
}