Manager::response()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 2
dl 0
loc 5
ccs 0
cts 5
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Distilleries\Contentful\Webhook;
4
5
use Exception;
6
7
class Manager
8
{
9
    /**
10
     * Handle Contentful webhook for given headers and payload.
11
     *
12
     * @param  array  $headers
13
     * @param  array  $payload
14
     * @param  boolean  $isPreview
15
     * @return array
16
     */
17
    public function handle(array $headers, array $payload, bool $isPreview = false): array
18
    {
19
        if (! isset($headers['x-contentful-topic'])) {
20
            return $this->response('Page not found', 404);
21
        }
22
23
        $topics = explode('.', $headers['x-contentful-topic'][0]);
24
        if ($topics[0] !== 'ContentManagement') {
25
            return $this->response('Page not found', 404);
26
        }
27
28
        switch ($topics[1]) {
29
            case 'Asset':
30
                $handler = new AssetHandler;
31
                break;
32
            case 'Entry':
33
                $handler = new EntryHandler;
34
                break;
35
            case 'ContentType':
36
            default:
37
                $handler = null;
38
        }
39
40
        if (! empty($handler)) {
41
            try {
42
                $handler->handle($topics[2], $payload, $isPreview);
43
            } catch (Exception $e) {
44
                return $this->response($e->getMessage(), 500);
45
            }
46
        }
47
48
        return $this->response();
49
    }
50
51
    /**
52
     * Return normalized service response signature.
53
     *
54
     * @param  string  $message
55
     * @param  integer  $status
56
     * @return array
57
     */
58
    private function response(string $message = '', int $status = 200): array
59
    {
60
        return [
61
            'status' => $status,
62
            'message' => ! empty($message) ? $message : null,
63
        ];
64
    }
65
}
66