App::listen()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 10
c 0
b 0
f 0
rs 10
cc 3
nc 2
nop 0
1
<?php
2
3
/**
4
 * WebhookManager
5
 *
6
 * @author: Luca Agnello <[email protected]>
7
 */
8
9
namespace Gnello\WebhookManager;
10
11
use Gnello\WebhookManager\Services\BitbucketService;
12
use Gnello\WebhookManager\Services\ServiceInterface;
13
14
/**
15
 * Class App
16
 *
17
 * @package Gnello\WebhookManager
18
 */
19
class App
20
{
21
    /**
22
     * @var array
23
     */
24
    private $defaultOptions = [
25
        'service' => BitbucketService::class,
26
        'json_decode_assoc' => true
27
    ];
28
29
    /**
30
     * @var array
31
     */
32
    private $options = [];
33
34
    /**
35
     * @var array
36
     */
37
    private $callables = [];
38
39
    /**
40
     * @var ServiceInterface
41
     */
42
    private $service;
43
44
    /**
45
     * App constructor.
46
     *
47
     * @param array $options
48
     */
49
    public function __construct(array $options = [])
50
    {
51
        $this->options = array_merge($this->defaultOptions, $options);
52
    }
53
54
    /**
55
     * Returns the current service
56
     *
57
     * @return ServiceInterface
58
     * @throws WebhookManagerException
59
     */
60
    private function getService()
61
    {
62
        $className = $this->options['service'];
63
        if (class_exists($className)) {
64
            $this->service = new $className($this->options);
65
        } else {
66
            throw new WebhookManagerException("Given class " . $className . " not exists.");
67
        }
68
69
        if (!$this->service instanceof ServiceInterface) {
70
            throw new WebhookManagerException("Service must be an instance of ServiceInterface.");
71
        }
72
73
        return $this->service;
74
    }
75
76
    /**
77
     * Adds a callback bound with one or more events
78
     *
79
     * @param string|array   $event
80
     * @param callable       $callable
81
     * @return App
82
     */
83
    public function add($event, callable $callable): App
84
    {
85
        if (!is_array($event)) {
86
            $event = [$event];
87
        }
88
89
        foreach ($event as $e) {
90
            $this->callables[$e] = $callable;
91
        }
92
93
        return $this;
94
    }
95
96
    /**
97
     * Performs the callback bound with the event received
98
     *
99
     * @return mixed
100
     * @throws WebhookManagerException
101
     */
102
    public function listen()
103
    {
104
        $service = $this->getService();
105
        $event = $service->getEvent();
106
107
        if (isset($this->callables[$event]) && is_callable($this->callables[$event])) {
108
            return $this->callables[$event]($service);
109
        }
110
111
        throw new WebhookManagerException("Callable not found for the " . $event . " event.");
112
    }
113
}
114
115