Completed
Push — develop ( 9820c9...39d465 )
by Nate
03:37
created

ObjectAssociations   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 271
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 11

Test Coverage

Coverage 6.67%

Importance

Changes 0
Metric Value
wmc 30
c 0
b 0
f 0
lcom 2
cbo 11
dl 0
loc 271
ccs 6
cts 90
cp 0.0667
rs 10

16 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 8 1
A findObjectIdByElement() 0 5 1
A findObjectId() 0 11 2
A findElementId() 0 11 2
A getQuery() 0 4 1
A associationQuery() 0 10 1
A existingAssociations() 0 13 4
A getElementByObjectId() 0 11 2
A findElementByObjectId() 0 12 2
A findObjectIdByElementId() 0 13 2
A query() 0 13 1
A associations() 0 9 1
B save() 0 22 6
A resolveFieldFromQuery() 0 9 2
A tableAlias() 0 4 1
A recordClass() 0 4 1
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;
10
11
use Craft;
12
use craft\base\Element;
13
use craft\base\ElementInterface;
14
use craft\errors\ElementNotFoundException;
15
use craft\helpers\Json;
16
use flipbox\craft\sortable\associations\db\SortableAssociationQueryInterface;
17
use flipbox\craft\sortable\associations\records\SortableAssociationInterface;
18
use flipbox\craft\sortable\associations\services\SortableAssociations;
19
use flipbox\ember\helpers\SiteHelper;
20
use flipbox\ember\services\traits\records\Accessor;
21
use flipbox\ember\validators\MinMaxValidator;
22
use flipbox\hubspot\db\ObjectAssociationQuery;
23
use flipbox\hubspot\fields\Objects;
24
use flipbox\hubspot\HubSpot;
25
use flipbox\hubspot\records\ObjectAssociation;
26
27
/**
28
 * @author Flipbox Factory <[email protected]>
29
 * @since 1.0.0
30
 *
31
 * @method ObjectAssociationQuery parentGetQuery($config = [])
32
 * @method ObjectAssociation create(array $attributes = [])
33
 * @method ObjectAssociation find($identifier)
34
 * @method ObjectAssociation get($identifier)
35
 * @method ObjectAssociation findByCondition($condition = [])
36
 * @method ObjectAssociation getByCondition($condition = [])
37
 * @method ObjectAssociation findByCriteria($criteria = [])
38
 * @method ObjectAssociation getByCriteria($criteria = [])
39
 * @method ObjectAssociation[] findAllByCondition($condition = [])
40
 * @method ObjectAssociation[] getAllByCondition($condition = [])
41
 * @method ObjectAssociation[] findAllByCriteria($criteria = [])
42
 * @method ObjectAssociation[] getAllByCriteria($criteria = [])
43
 */
44
class ObjectAssociations extends SortableAssociations
45
{
46
    use Accessor {
47
        getQuery as parentGetQuery;
48
    }
49
50
    /**
51
     * @inheritdoc
52
     */
53
    const SOURCE_ATTRIBUTE = ObjectAssociation::SOURCE_ATTRIBUTE;
54
55
    /**
56
     * @inheritdoc
57
     */
58
    const TARGET_ATTRIBUTE = ObjectAssociation::TARGET_ATTRIBUTE;
59
60
    /**
61
     * @inheritdoc
62
     */
63 3
    public function init()
64
    {
65 3
        $settings = HubSpot::getInstance()->getSettings();
66 3
        $this->cacheDuration = $settings->associationsCacheDuration;
67 3
        $this->cacheDependency = $settings->associationsCacheDependency;
68
69 3
        parent::init();
70 3
    }
71
72
    /**
73
     * @param ElementInterface $element
74
     * @param Objects $field
75
     * @return string|null
76
     */
77
    public function findObjectIdByElement(ElementInterface $element, Objects $field)
78
    {
79
        /** @var Element $element */
80
        return $this->findObjectId($field->id, $element->getId(), $element->siteId);
81
    }
82
83
    /**
84
     * @noinspection PhpDocMissingThrowsInspection
85
     *
86
     * @param string $fieldId
87
     * @param string $elementId
88
     * @param string|null $siteId
89
     * @return null|string
90
     */
91
    public function findObjectId(string $fieldId, string $elementId, string $siteId = null)
92
    {
93
        $objectId = HubSpot::getInstance()->getObjectAssociations()->getQuery([
94
            'select' => ['objectId'],
95
            'elementId' => $elementId,
96
            'siteId' => SiteHelper::ensureSiteId($siteId),
97
            'fieldId' => $fieldId
98
        ])->scalar();
99
100
        return is_string($objectId) ? $objectId : null;
101
    }
102
103
    /**
104
     * @noinspection PhpDocMissingThrowsInspection
105
     *
106
     * @param string $fieldId
107
     * @param string $elementId
108
     * @param string|null $siteId
109
     * @return null|string
110
     */
111
    public function findElementId(string $fieldId, string $elementId, string $siteId = null)
112
    {
113
        $elementId = HubSpot::getInstance()->getObjectAssociations()->getQuery([
114
            'select' => ['elementId'],
115
            'objectId' => $elementId,
116
            'siteId' => SiteHelper::ensureSiteId($siteId),
117
            'fieldId' => $fieldId
118
        ])->scalar();
119
120
        return is_string($elementId) ? $elementId : null;
121
    }
122
123
    /**
124
     * @inheritdoc
125
     * @return ObjectAssociationQuery
126
     */
127
    public function getQuery($config = []): SortableAssociationQueryInterface
128
    {
129
        return $this->parentGetQuery($config);
130
    }
131
132
    /**
133
     * @inheritdoc
134
     * @return ObjectAssociationQuery
135
     */
136
    protected function associationQuery(
137
        SortableAssociationInterface $record
138
    ): SortableAssociationQueryInterface {
139
        /** @var ObjectAssociation $record */
140
        return $this->query(
141
            $record->{static::SOURCE_ATTRIBUTE},
142
            $record->fieldId,
143
            $record->siteId
144
        );
145
    }
146
147
    /**
148
     * @inheritdoc
149
     * @param ObjectAssociationQuery $query
150
     */
151
    protected function existingAssociations(
152
        SortableAssociationQueryInterface $query
153
    ): array {
154
        $source = $this->resolveStringAttribute($query, 'element');
155
        $field = $this->resolveStringAttribute($query, 'field');
156
        $site = $this->resolveStringAttribute($query, 'siteId');
157
158
        if ($source === null || $field === null || $site === null) {
159
            return [];
160
        }
161
162
        return $this->associations($source, $field, $site);
163
    }
164
165
166
    /**
167
     * @param string $objectId
168
     * @return ElementInterface
169
     * @throws ElementNotFoundException
170
     */
171
    public function getElementByObjectId(string $objectId): ElementInterface
172
    {
173
        if (!$element = $this->findElementByObjectId($objectId)) {
174
            throw new ElementNotFoundException(sprintf(
175
                "Unable to get element from HubSpot Id: '%s'.",
176
                $objectId
177
            ));
178
        }
179
180
        return $element;
181
    }
182
183
    /**
184
     * @param string $objectId
185
     * @return ElementInterface|null
186
     */
187
    public function findElementByObjectId(string $objectId)
188
    {
189
        $record = $this->findByCondition([
190
            'objectId' => $objectId
191
        ]);
192
193
        if ($record === null) {
194
            return null;
195
        }
196
197
        return $record->getElement();
198
    }
199
200
    /**
201
     * Find the HubSpot Id by Element Id
202
     *
203
     * @param int $id
204
     * @return string|null
205
     */
206
    public function findObjectIdByElementId(int $id)
207
    {
208
        $objectId = $this->getQuery()
209
            ->select(['objectId'])
210
            ->element($id)
211
            ->scalar();
212
213
        if (!$objectId) {
214
            return null;
215
        }
216
217
        return $objectId;
218
    }
219
220
221
    /**
222
     * @param $source
223
     * @param int $fieldId
224
     * @param int $siteId
225
     * @return ObjectAssociationQuery
226
     */
227
    private function query(
228
        $source,
229
        int $fieldId,
230
        int $siteId
231
    ): ObjectAssociationQuery {
232
        return $this->getQuery()
233
            ->where([
234
                static::SOURCE_ATTRIBUTE => $source,
235
                'fieldId' => $fieldId,
236
                'siteId' => $siteId
237
            ])
238
            ->orderBy(['sortOrder' => SORT_ASC]);
239
    }
240
241
    /**
242
     * @param $source
243
     * @param int $fieldId
244
     * @param int $siteId
245
     * @return array
246
     */
247
    private function associations(
248
        $source,
249
        int $fieldId,
250
        int $siteId
251
    ): array {
252
        return $this->query($source, $fieldId, $siteId)
253
            ->indexBy(static::TARGET_ATTRIBUTE)
254
            ->all();
255
    }
256
257
    /**
258
     * @inheritdoc
259
     * @param bool $validate
260
     * @throws \Exception
261
     */
262
    public function save(
263
        SortableAssociationQueryInterface $query,
264
        bool $validate = true
265
    ): bool {
266
        if ($validate === true && null !== ($field = $this->resolveFieldFromQuery($query))) {
267
            $error = '';
268
            (new MinMaxValidator([
269
                'min' => $field->min ? (int)$field->min : null,
270
                'max' => $field->max ? (int)$field->max : null
271
            ]))->validate($query, $error);
272
273
            if (!empty($error)) {
274
                HubSpot::error(sprintf(
275
                    "Hubspot Resource failed to save due to the following validation errors: '%s'",
276
                    Json::encode($error)
277
                ));
278
                return false;
279
            }
280
        }
281
282
        return parent::save($query);
283
    }
284
285
    /**
286
     * @param SortableAssociationQueryInterface $query
287
     * @return Objects|null
288
     */
289
    protected function resolveFieldFromQuery(
290
        SortableAssociationQueryInterface $query
291
    ) {
292
        if (null === ($fieldId = $this->resolveStringAttribute($query, 'field'))) {
293
            return null;
294
        }
295
296
        return HubSpot::getInstance()->getObjectsField()->findById($fieldId);
297
    }
298
299
    /**
300
     * @inheritdoc
301
     */
302
    protected static function tableAlias(): string
303
    {
304
        return ObjectAssociation::tableAlias();
305
    }
306
307
    /**
308
     * @inheritdoc
309
     */
310
    public static function recordClass(): string
311
    {
312
        return ObjectAssociation::class;
313
    }
314
}
315