Completed
Push — 1.4 ( eba84d...d3bf7f )
by Rafał
08:33
created

PreviewWebhookEventSubscriber   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 76
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 7
dl 0
loc 76
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
A getSubscribedEvents() 0 6 1
B processEvent() 0 45 5
A isUrlValid() 0 4 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 2018 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 2018 Sourcefabric z.ú
14
 * @license http://www.superdesk.org/license
15
 */
16
17
namespace SWP\Bundle\CoreBundle\EventSubscriber;
18
19
use GuzzleHttp\Client;
20
use SWP\Bundle\ContentBundle\ArticleEvents;
21
use SWP\Bundle\CoreBundle\Model\ArticlePreview;
22
use SWP\Bundle\CoreBundle\Repository\WebhookRepositoryInterface;
23
use SWP\Bundle\CoreBundle\Webhook\WebhookEvents;
24
use SWP\Bundle\WebhookBundle\Model\WebhookInterface;
25
use SWP\Component\Common\Serializer\SerializerInterface;
26
use SWP\Component\MultiTenancy\Context\TenantContextInterface;
27
use SWP\Component\MultiTenancy\Repository\TenantRepositoryInterface;
28
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
29
use Symfony\Component\EventDispatcher\GenericEvent;
30
use Webmozart\Assert\Assert;
31
32
final class PreviewWebhookEventSubscriber extends AbstractWebhookEventSubscriber
33
{
34
    /**
35
     * @var SerializerInterface
36
     */
37
    private $serializer;
38
39
    public function __construct(
40
        SerializerInterface $serializer,
41
        WebhookRepositoryInterface $webhooksRepository,
42
        TenantContextInterface $tenantContext,
43
        TenantRepositoryInterface $tenantRepository
44
    ) {
45
        $this->serializer = $serializer;
46
47
        parent::__construct($webhooksRepository, $tenantContext, $tenantRepository);
48
    }
49
50
    public static function getSubscribedEvents()
51
    {
52
        return [
53
            ArticleEvents::PREVIEW => 'processEvent',
54
        ];
55
    }
56
57
    public function processEvent(GenericEvent $event, string $dispatcherEventName, EventDispatcherInterface $dispatcher): void
0 ignored issues
show
Unused Code introduced by
The parameter $dispatcherEventName is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
58
    {
59
        $subject = $event->getSubject();
60
        Assert::isInstanceOf($subject, ArticlePreview::class);
61
        $article = $subject->getArticle();
62
63
        $webhooks = $this->getWebhooks($article, WebhookEvents::PREVIEW_EVENT, $dispatcher);
64
        $headers = [];
65
66
        if (!isset($webhooks[0])) {
67
            return;
68
        }
69
70
        /** @var WebhookInterface $webhook */
71
        $webhook = $webhooks[0];
72
73
        $metadata = [
74
                'event' => WebhookEvents::PREVIEW_EVENT,
75
                'tenant' => $webhook->getTenantCode(),
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface SWP\Bundle\WebhookBundle\Model\WebhookInterface as the method getTenantCode() does only exist in the following implementations of said interface: SWP\Bundle\CoreBundle\Model\Webhook.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
76
            ];
77
78
        foreach ($metadata as $header => $value) {
79
            $headers['X-WEBHOOK-'.\strtoupper($header)] = $value;
80
        }
81
82
        $client = new Client();
83
        $requestOptions = [
84
                'headers' => $headers,
85
                'body' => $this->serializer->serialize($article, 'json'),
86
            ];
87
88
        /** @var \GuzzleHttp\Psr7\Response $response */
89
        $response = $client->post($webhook->getUrl(), $requestOptions);
90
        $content = $response->getBody()->getContents();
91
92
        $content = json_decode($content, true);
93
94
        if (!isset($content['url'])) {
95
            return;
96
        }
97
98
        if ($this->isUrlValid($content['url'])) {
99
            $subject->setPreviewUrl($content['url']);
100
        }
101
    }
102
103
    private function isUrlValid(string $url): bool
104
    {
105
        return false !== filter_var($url, FILTER_VALIDATE_URL);
106
    }
107
}
108