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 GuzzleHttp\Exception\ClientException; |
8
|
|
|
use Symfony\Component\Routing\Generator\UrlGeneratorInterface; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Creates Webhooks. |
12
|
|
|
*/ |
13
|
|
|
class WebhookCreator implements WebhookCreatorInterface |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @var ShopifyApiFactory |
17
|
|
|
*/ |
18
|
|
|
private $apis; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @var UrlGeneratorInterface |
22
|
|
|
*/ |
23
|
|
|
private $router; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @param ShopifyApiFactory $apis |
27
|
|
|
* @param UrlGeneratorInterface $router |
28
|
|
|
*/ |
29
|
|
|
public function __construct(ShopifyApiFactory $apis, UrlGeneratorInterface $router) |
30
|
|
|
{ |
31
|
|
|
$this->apis = $apis; |
32
|
|
|
$this->router = $router; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* {@inheritdoc} |
37
|
|
|
*/ |
38
|
|
|
public function createWebhooks(string $storeName, array $topics) |
39
|
|
|
{ |
40
|
|
|
$api = $this->apis->getForStore($storeName); |
41
|
|
|
|
42
|
|
|
foreach ($topics as $topic) { |
43
|
|
|
$endpoint = $this->router->generate('codecloud_shopify_webhooks', [ |
44
|
|
|
'store' => $storeName, |
45
|
|
|
'topic' => $topic, |
46
|
|
|
], UrlGeneratorInterface::ABSOLUTE_URL); |
47
|
|
|
|
48
|
|
|
// endpoint HAS to be https |
49
|
|
|
$endpoint = str_replace("http://", "https://", $endpoint); |
50
|
|
|
|
51
|
|
|
$webhook = GenericResource::create([ |
52
|
|
|
'topic' => $topic, |
53
|
|
|
'address' => $endpoint, |
54
|
|
|
'format' => 'json', |
55
|
|
|
]); |
56
|
|
|
|
57
|
|
|
try { |
58
|
|
|
$api->Webhook->create($webhook); |
59
|
|
|
} catch (ClientException $e) { |
60
|
|
|
if ($e->getResponse()->getStatusCode() == 422) { |
61
|
|
|
continue; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
throw $e; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* {@inheritdoc} |
71
|
|
|
*/ |
72
|
|
|
public function listWebhooks(string $storeName) |
73
|
|
|
{ |
74
|
|
|
$api = $this->apis->getForStore($storeName); |
75
|
|
|
|
76
|
|
|
return $api->Webhook->findAll(); |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
/** |
80
|
|
|
* {@inheritdoc} |
81
|
|
|
*/ |
82
|
|
|
public function deleteAllWebhooks(string $storeName) |
83
|
|
|
{ |
84
|
|
|
$api = $this->apis->getForStore($storeName); |
85
|
|
|
|
86
|
|
|
foreach ($api->Webhook->findAll() as $webhook) { |
87
|
|
|
$api->Webhook->delete($webhook['id']); |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|