Completed
Push — master ( d7e260...fc7aea )
by Artem
10:19
created

Dispatcher   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 79
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 16
dl 0
loc 79
ccs 0
cts 19
cp 0
rs 10
c 0
b 0
f 0
wmc 8

5 Methods

Rating   Name   Duplication   Size   Complexity  
A has() 0 3 1
A instantiate() 0 5 1
A get() 0 3 1
A handle() 0 17 4
A webhooks() 0 4 1
1
<?php
2
3
namespace Slides\Connector\Auth\Webhooks;
4
5
use Slides\Connector\Auth\Exceptions\WebhookException;
6
use Slides\Connector\Auth\Exceptions\WebhookValidationException;
7
8
/**
9
 * Class Dispatcher
10
 *
11
 * @package Slides\Connector\Auth\Webhooks
12
 */
13
class Dispatcher
14
{
15
    /**
16
     * Handle a webhook.
17
     *
18
     * @param string $key
19
     * @param array $payload
20
     *
21
     * @return void
22
     */
23
    public function handle(string $key, array $payload)
24
    {
25
        if(!$this->has($key)) {
26
            throw new WebhookException("Webhook with key \"{$key}\" cannot be found.");
27
        }
28
29
        $webhook = $this->instantiate($key, $payload);
30
31
        if(!$webhook->validate()) {
32
            throw new WebhookValidationException($webhook->getValidator());
33
        }
34
35
        try {
36
            $webhook->handle();
37
        }
38
        catch(\Exception $e) {
39
            throw new WebhookException(get_class($webhook) . ': ' . $e->getMessage());
40
        }
41
    }
42
43
    /**
44
     * Instantiate a webhook handler.
45
     *
46
     * @param string $key
47
     * @param array $payload
48
     *
49
     * @return Webhook
50
     */
51
    private function instantiate(string $key, array $payload)
52
    {
53
        $webhook = $this->get($key);
54
55
        return new $webhook($payload);
56
    }
57
58
    /**
59
     * Check whether a given webhook exists.
60
     *
61
     * @param string $key
62
     *
63
     * @return bool
64
     */
65
    private function has(string $key): bool
66
    {
67
        return array_key_exists($key, static::webhooks());
68
    }
69
70
    /**
71
     * Retrieve a class handler of by the webhook key.
72
     *
73
     * @param string $key
74
     * @param string|null $default
75
     *
76
     * @return string|null
77
     */
78
    private function get(string $key, $default = null)
79
    {
80
        return array_get(static::webhooks(), $key, $default);
81
    }
82
83
    /**
84
     * The supported webhook identifiers.
85
     *
86
     * @return array
87
     */
88
    public static function webhooks()
89
    {
90
        return [
91
            'user.sync' => UserSyncWebhook::class
92
        ];
93
    }
94
}