Completed
Push — master ( 6c6364...557817 )
by Nate
09:56 queued 07:58
created

SyncByElementTrait::handleSyncUpResponse()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 0
cts 8
cp 0
rs 9.584
c 0
b 0
f 0
cc 3
nc 2
nop 3
crap 12
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://flipboxfactory.com/software/hubspot/license
6
 * @link       https://www.flipboxfactory.com/software/hubspot/
7
 */
8
9
namespace flipbox\hubspot\services\resources\traits;
10
11
use craft\base\Element;
12
use craft\base\ElementInterface;
13
use craft\helpers\Json;
14
use flipbox\hubspot\connections\ConnectionInterface;
15
use flipbox\hubspot\fields\Objects;
16
use flipbox\hubspot\helpers\ConnectionHelper;
17
use flipbox\hubspot\HubSpot;
18
use flipbox\hubspot\pipeline\stages\ElementAssociationStage;
19
use flipbox\hubspot\pipeline\stages\ElementSaveStage;
20
use flipbox\hubspot\traits\TransformElementIdTrait;
21
use flipbox\hubspot\traits\TransformElementPayloadTrait;
22
use flipbox\hubspot\transformers\error\Interpret;
23
use Flipbox\Pipeline\Pipelines\Pipeline;
24
use Flipbox\Transform\Factory;
25
use Psr\Http\Message\ResponseInterface;
26
use Psr\SimpleCache\CacheInterface;
27
28
/**
29
 * @author Flipbox Factory <[email protected]>
30
 * @since 1.0.0
31
 */
32
trait SyncByElementTrait
33
{
34
    use TransformElementIdTrait,
35
        TransformElementPayloadTrait;
36
37
    /**
38
     * @param string $id
39
     * @param ConnectionInterface|string|null $connection
40
     * @param CacheInterface|string|null $cache
41
     * @return callable
42
     */
43
    public abstract function rawHttpReadRelay(
44
        string $id,
45
        ConnectionInterface $connection = null,
46
        CacheInterface $cache = null
47
    ): callable;
48
49
    /**
50
     * @param array $payload
51
     * @param string|null $identifier
52
     * @param ConnectionInterface|string|null $connection
53
     * @param CacheInterface|string|null $cache
54
     * @return callable
55
     * @throws \yii\base\InvalidConfigException
56
     */
57
    public abstract function rawHttpUpsertRelay(
58
        array $payload,
59
        string $identifier = null,
60
        ConnectionInterface $connection = null,
61
        CacheInterface $cache = null
62
    ): callable;
63
64
    /**
65
     * @param ElementInterface $element
66
     * @param Objects $field
67
     * @param ConnectionInterface|null $connection
68
     * @param CacheInterface|null $cache
69
     * @return bool
70
     * @throws \yii\base\InvalidConfigException
71
     */
72
    public function syncDown(
73
        ElementInterface $element,
74
        Objects $field,
75
        ConnectionInterface $connection = null,
76
        CacheInterface $cache = null
77
    ): bool {
78
        /** @var Element $element */
79
80
        /** @var string $id */
81
        if (null === ($id = $this->transformElementId($element, $field))) {
82
            return false;
83
        }
84
85
        return $this->rawSyncDown(
86
            $element,
87
            $field,
88
            $id,
89
            $connection,
90
            $cache
91
        );
92
    }
93
94
    /**
95
     * @param ElementInterface $element
96
     * @param Objects $field
97
     * @param string $id
98
     * @param ConnectionInterface|null $connection
99
     * @param CacheInterface|null $cache
100
     * @return bool
101
     * @throws \yii\base\InvalidConfigException
102
     */
103
    public function rawSyncDown(
104
        ElementInterface $element,
105
        Objects $field,
106
        string $id,
107
        ConnectionInterface $connection = null,
108
        CacheInterface $cache = null
109
    ): bool {
110
        /** @var Element $element */
111
112
        /** @var ResponseInterface $response */
113
        $response = $this->rawHttpReadRelay(
114
            $id,
115
            ConnectionHelper::resolveConnection($connection),
116
            $cache
117
        )();
118
119
        return $this->handleSyncDownResponse(
120
            $response,
121
            $element,
122
            $field
123
        );
124
    }
125
126
    /**
127
     * @param ResponseInterface $response
128
     * @param ElementInterface $element
129
     * @param Objects $field
130
     * @return bool
131
     */
132
    protected function handleSyncDownResponse(
133
        ResponseInterface $response,
134
        ElementInterface $element,
135
        Objects $field
136
    ): bool {
137
        $logger = HubSpot::getInstance()->getPsrLogger();
138
139
        if ($response->getStatusCode() >= 200 && $response->getStatusCode() <= 299) {
140
            $pipeline = new Pipeline([
141
                'stages' => [
142
                    new ElementSaveStage($field, ['logger' => $logger]),
143
                    new ElementAssociationStage($field, ['logger' => $logger])
144
                ]
145
            ]);
146
147
            return $pipeline->process($response, $element) instanceof ResponseInterface;
148
        }
149
150
        $this->handleResponseErrors($response, $element);
151
152
        return false;
153
    }
154
155
    /**
156
     * @param ElementInterface $element
157
     * @param Objects $field
158
     * @param ConnectionInterface|null $connection
159
     * @param CacheInterface|null $cache
160
     * @return bool
161
     * @throws \yii\base\InvalidConfigException
162
     */
163
164
    public function syncUp(
165
        ElementInterface $element,
166
        Objects $field,
167
        ConnectionInterface $connection = null,
168
        CacheInterface $cache = null
169
    ): bool {
170
        return $this->rawSyncUp(
171
            $element,
172
            $field,
173
            $this->transformElementPayload($element, $field),
174
            $this->transformElementId($element, $field),
175
            $connection,
176
            $cache
177
        );
178
    }
179
180
    /**
181
     * @param ElementInterface $element
182
     * @param Objects $field
183
     * @param array $payload
184
     * @param string|null $id
185
     * @param ConnectionInterface|null $connection
186
     * @param CacheInterface|null $cache
187
     * @return bool
188
     * @throws \yii\base\InvalidConfigException
189
     */
190
    public function rawSyncUp(
191
        ElementInterface $element,
192
        Objects $field,
193
        array $payload,
194
        string $id = null,
195
        ConnectionInterface $connection = null,
196
        CacheInterface $cache = null
197
    ): bool {
198
        /** @var Element $element */
199
200
        /** @var ResponseInterface $response */
201
        $response = $this->rawHttpUpsertRelay(
202
            $payload,
203
            $id,
204
            $connection,
205
            $cache
206
        )();
207
208
        return $this->handleSyncUpResponse(
209
            $response,
210
            $element,
211
            $field
212
        );
213
    }
214
215
    /**
216
     * @param ResponseInterface $response
217
     * @param ElementInterface $element
218
     * @param Objects $field
219
     * @return bool
220
     */
221
    protected function handleSyncUpResponse(
222
        ResponseInterface $response,
223
        ElementInterface $element,
224
        Objects $field
225
    ): bool {
226
        $logger = HubSpot::getInstance()->getPsrLogger();
227
228
        if ($response->getStatusCode() >= 200 && $response->getStatusCode() <= 299) {
229
            $pipeline = new Pipeline([
230
                'stages' => [
231
                    new ElementAssociationStage($field, ['logger' => $logger])
232
                ]
233
            ]);
234
235
            return $pipeline->process($response, $element) instanceof ResponseInterface;
236
        }
237
238
        $this->handleResponseErrors($response, $element);
239
240
        return false;
241
    }
242
243
    /**
244
     * @param ResponseInterface $response
245
     * @param ElementInterface $element
246
     */
247
    protected function handleResponseErrors(ResponseInterface $response, ElementInterface $element)
248
    {
249
        /** @var Element $element */
250
251
        $data = Json::decodeIfJson(
252
            $response->getBody()->getContents()
253
        );
254
255
        $errors = (array)Factory::item(
256
            new Interpret(),
257
            $data
258
        );
259
260
        $errors = array_filter($errors);
261
262
        if (empty($errors)) {
263
            $element->addErrors($errors);
264
        }
265
    }
266
}
267