Completed
Push — 1.4 ( 460714...084e89 )
by Paweł
24:24 queued 03:14
created

SendWebhookConsumer::execute()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 8.8657
c 0
b 0
f 0
cc 6
nc 5
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Superdesk Web Publisher Core Bundle.
7
 *
8
 * Copyright 2017 Sourcefabric z.ú. and contributors.
9
 *
10
 * For the full copyright and license information, please see the
11
 * AUTHORS and LICENSE files distributed with this source code.
12
 *
13
 * @copyright 2017 Sourcefabric z.ú
14
 * @license http://www.superdesk.org/license
15
 */
16
17
namespace SWP\Bundle\CoreBundle\Consumer;
18
19
use GuzzleHttp\Client;
20
use JMS\Serializer\SerializerInterface;
21
use OldSound\RabbitMqBundle\RabbitMq\ConsumerInterface;
22
use PhpAmqpLib\Message\AMQPMessage;
23
use GuzzleHttp;
24
25
class SendWebhookConsumer implements ConsumerInterface
26
{
27
    /**
28
     * @var SerializerInterface
29
     */
30
    protected $serializer;
31
32
    public function __construct(SerializerInterface $serializer)
33
    {
34
        $this->serializer = $serializer;
35
    }
36
37
    public function execute(AMQPMessage $message): void
38
    {
39
        $decodedMessage = $this->serializer->deserialize($message->body, 'array', 'json');
40
        if (!\array_key_exists('url', $decodedMessage) || !array_key_exists('subject', $decodedMessage)) {
41
            return;
42
        }
43
44
        $headers = [];
45
        if (\array_key_exists('metadata', $decodedMessage)) {
46
            foreach ($decodedMessage['metadata'] as $header => $value) {
47
                $headers['X-WEBHOOK-'.\strtoupper($header)] = $value;
48
            }
49
        }
50
51
        $webhookRequest = new GuzzleHttp\Psr7\Request(
52
            'POST',
53
            $decodedMessage['url'],
54
            $headers,
55
            $this->serializer->serialize($decodedMessage['subject'], 'json')
56
        );
57
58
        try {
59
            $this->getClient()->send($webhookRequest);
60
        } catch (GuzzleHttp\Exception\ClientException | GuzzleHttp\Exception\ServerException $e) {
61
            return;
62
        }
63
    }
64
65
    protected function getClient(): Client
66
    {
67
        return new Client();
68
    }
69
}
70