Passed
Pull Request — master (#9)
by Daniel
02:12
created

WebhookCreatorLocal::createWebhooks()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 28
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 4
eloc 16
c 1
b 1
f 0
nc 4
nop 2
dl 0
loc 28
rs 9.7333
1
<?php
2
3
namespace CodeCloud\Bundle\ShopifyBundle\Service;
4
5
use CodeCloud\Bundle\ShopifyBundle\Api\GenericResource;
6
use CodeCloud\Bundle\ShopifyBundle\Api\ShopifyApiFactory;
7
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
8
9
/**
10
 * Creates Webhooks to be received by this application.
11
 */
12
class WebhookCreatorLocal extends AbstractWebhookCreator
13
{
14
    /**
15
     * @var UrlGeneratorInterface
16
     */
17
    private $router;
18
19
    /**
20
     * @param ShopifyApiFactory $apis
21
     * @param UrlGeneratorInterface $router
22
     */
23
    public function __construct(ShopifyApiFactory $apis, UrlGeneratorInterface $router)
24
    {
25
        $this->router = $router;
26
27
        parent::__construct($apis);
28
    }
29
30
    /**
31
     * {@inheritdoc}
32
     */
33
    public function createWebhooks(string $storeName, array $topics)
34
    {
35
        $api = $this->apis->getForStore($storeName);
36
37
        $existing = $api->Webhook->findAll();
38
39
        foreach ($topics as $topic) {
40
            foreach ($existing as $ex) {
41
                if ($ex['topic'] == $topic) {
42
                    continue 2;
43
                }
44
            }
45
46
            $endpoint = $this->router->generate('codecloud_shopify_webhooks', [
47
                'store' => $storeName,
48
                'topic' => $topic,
49
            ], UrlGeneratorInterface::ABSOLUTE_URL);
50
51
            // endpoint HAS to be https
52
            $endpoint = str_replace("http://", "https://", $endpoint);
53
54
            $webhook = GenericResource::create([
55
                'topic' => $topic,
56
                'address' => $endpoint,
57
                'format' => 'json',
58
            ]);
59
60
            $api->Webhook->create($webhook);
61
        }
62
    }
63
}
64