Completed
Push — master ( 53e590...136153 )
by Nate
16:58 queued 14:19
created

Objects::getResource()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 0
cts 12
cp 0
rs 9.7998
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 6
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\fields;
10
11
use Craft;
12
use craft\base\ElementInterface;
13
use craft\base\Field;
14
use craft\elements\db\ElementQueryInterface;
15
use flipbox\ember\helpers\ModelHelper;
16
use flipbox\ember\validators\MinMaxValidator;
17
use flipbox\hubspot\criteria\CompanyCriteria;
18
use flipbox\hubspot\criteria\ContactCriteria;
19
use flipbox\hubspot\criteria\ContactListCriteria;
20
use flipbox\hubspot\criteria\ObjectCriteria;
21
use flipbox\hubspot\criteria\ObjectCriteriaInterface;
22
use flipbox\hubspot\db\ObjectAssociationQuery;
23
use flipbox\hubspot\HubSpot;
24
use flipbox\hubspot\records\ObjectAssociation;
25
use flipbox\hubspot\services\resources\Companies;
26
use flipbox\hubspot\services\resources\ContactLists;
27
use flipbox\hubspot\services\resources\Contacts;
28
use flipbox\hubspot\services\resources\CRUDInterface;
29
use yii\base\InvalidConfigException;
30
31
/**
32
 * @author Flipbox Factory <[email protected]>
33
 * @since 1.0.0
34
 */
35
class Objects extends Field
36
{
37
    /**
38
     * The action event name
39
     */
40
    const EVENT_REGISTER_ACTIONS = 'registerActions';
41
42
    /**
43
     * The action event name
44
     */
45
    const EVENT_REGISTER_AVAILABLE_ACTIONS = 'registerAvailableActions';
46
47
    /**
48
     * The item action event name
49
     */
50
    const EVENT_REGISTER_ITEM_ACTIONS = 'registerItemActions';
51
52
    /**
53
     * The item action event name
54
     */
55
    const EVENT_REGISTER_AVAILABLE_ITEM_ACTIONS = 'registerAvailableItemActions';
56
57
    /**
58
     * The input template path
59
     */
60
    const INPUT_TEMPLATE_PATH = 'hubspot/_components/fieldtypes/Objects/input';
61
62
    /**
63
     * The default HubSpot Resource Id (if none exists)
64
     */
65
    const DEFAULT_HUBSPOT_ID = 'UNKNOWN_ID';
66
67
    /**
68
     * @var string
69
     */
70
    public $object;
71
72
    /**
73
     * @var int|null
74
     */
75
    public $min;
76
77
    /**
78
     * @var int|null
79
     */
80
    public $max;
81
82
    /**
83
     * @var string
84
     */
85
    public $viewUrl = '';
86
87
    /**
88
     * @var string
89
     */
90
    public $listUrl = '';
91
92
    /**
93
     * @var array
94
     */
95
    public $selectedActions = [];
96
97
    /**
98
     * @var array
99
     */
100
    public $selectedItemActions = [];
101
102
    /**
103
     * @var string|null
104
     */
105
    public $selectionLabel;
106
107
    /**
108
     * @inheritdoc
109
     */
110
    public static function displayName(): string
111
    {
112
        return Craft::t('hubspot', 'HubSpot Objects');
113
    }
114
115
    /**
116
     * @inheritdoc
117
     */
118
    public static function defaultSelectionLabel(): string
119
    {
120
        return Craft::t('hubspot', 'Add a HubSpot Objects');
121
    }
122
123
    /**
124
     * @inheritdoc
125
     */
126
    public static function hasContentColumn(): bool
127
    {
128
        return false;
129
    }
130
131
    /*******************************************
132
     * VALIDATION
133
     *******************************************/
134
135
    /**
136
     * @inheritdoc
137
     */
138
    public function getElementValidationRules(): array
139
    {
140
        return [
141
            [
142
                MinMaxValidator::class,
143
                'min' => $this->min,
144
                'max' => $this->max,
145
                'tooFew' => Craft::t(
146
                    'hubspot',
147
                    '{attribute} should contain at least {min, number} {min, plural, one{domain} other{domains}}.'
148
                ),
149
                'tooMany' => Craft::t(
150
                    'hubspot',
151
                    '{attribute} should contain at most {max, number} {max, plural, one{domain} other{domains}}.'
152
                ),
153
                'skipOnEmpty' => false
154
            ]
155
        ];
156
    }
157
158
    /*******************************************
159
     * CRUD
160
     *******************************************/
161
162
    /**
163
     * @return CRUDInterface
164
     * @throws InvalidConfigException
165
     */
166
    public function getResource(): CRUDInterface
167
    {
168
        $service = HubSpot::getInstance()->getResources()->get($this->object);
169
170
        if (!$service instanceof CRUDInterface) {
171
            throw new InvalidConfigException(sprintf(
172
                "Resource must be an instance of '%s', '%s' given",
173
                CRUDInterface::class,
174
                get_class($service)
175
            ));
176
        }
177
178
        return $service;
179
    }
180
181
    /*******************************************
182
     * CRITERIA
183
     *******************************************/
184
185
    /**
186
     * @return array
187
     */
188
    protected function getResourceCriteriaMap(): array
189
    {
190
        return [
191
            Companies::HUBSPOT_RESOURCE => function (ObjectAssociation $record = null) {
192
                return [
193
                    'class' => CompanyCriteria::class,
194
                    'id' => $record ? $record->objectId : self::DEFAULT_HUBSPOT_ID
195
                ];
196
            },
197
            Contacts::HUBSPOT_RESOURCE => function (ObjectAssociation $record = null) {
198
                return [
199
                    'class' => ContactCriteria::class,
200
                    'id' => $record ? $record->objectId : self::DEFAULT_HUBSPOT_ID
201
                ];
202
            },
203
            ContactLists::HUBSPOT_RESOURCE => function (ObjectAssociation $record = null) {
204
                return [
205
                    'class' => ContactListCriteria::class,
206
                    'id' => $record ? $record->objectId : self::DEFAULT_HUBSPOT_ID
207
                ];
208
            }
209
        ];
210
    }
211
212
    /**
213
     * @param ObjectAssociation|null $record
214
     * @param array $config
215
     * @return ObjectCriteriaInterface
216
     * @throws \yii\base\InvalidConfigException
217
     */
218
    public function createResourceCriteria(
219
        ObjectAssociation $record = null,
220
        array $config = []
221
    ): ObjectCriteriaInterface {
222
        $resourceMap = $this->getResourceCriteriaMap();
223
224
        $criteria = $resourceMap[$this->object] ?? ObjectCriteria::class;
225
226
        // Closure check
227
        if (is_callable($criteria)) {
228
            $criteria = call_user_func_array($criteria, ['record' => $record]);
229
        }
230
231
        // Ensure Criteria
232
        if (!$criteria instanceof ObjectCriteriaInterface) {
233
            $criteria = \flipbox\ember\helpers\ObjectHelper::create(
234
                $criteria,
235
                ObjectCriteriaInterface::class
236
            );
237
        }
238
239
        if (!$criteria instanceof ObjectCriteriaInterface) {
240
            $criteria = new ObjectCriteria();
241
        }
242
243
        // TODO - apply the $config to the criteria
244
245
        return $criteria;
246
    }
247
248
    /*******************************************
249
     * VALUE
250
     *******************************************/
251
252
    /**
253
     * @inheritdoc
254
     */
255
    public function normalizeValue($value, ElementInterface $element = null)
256
    {
257
        return HubSpot::getInstance()->getObjectsField()->normalizeValue(
258
            $this,
259
            $value,
260
            $element
261
        );
262
    }
263
264
265
    /*******************************************
266
     * ELEMENT
267
     *******************************************/
268
269
    /**
270
     * @inheritdoc
271
     */
272
    public function modifyElementsQuery(ElementQueryInterface $query, $value)
273
    {
274
        return HubSpot::getInstance()->getObjectsField()->modifyElementsQuery(
275
            $this,
276
            $query,
277
            $value
278
        );
279
    }
280
281
282
    /*******************************************
283
     * RULES
284
     *******************************************/
285
286
    /**
287
     * @inheritdoc
288
     */
289
    public function rules()
290
    {
291
        return array_merge(
292
            parent::rules(),
293
            [
294
                [
295
                    'object',
296
                    'required',
297
                    'message' => Craft::t('hubspot', 'Hubspot Object cannot be empty.')
298
                ],
299
                [
300
                    [
301
                        'object',
302
                        'min',
303
                        'max',
304
                        'viewUrl',
305
                        'listUrl',
306
                        'selectionLabel'
307
                    ],
308
                    'safe',
309
                    'on' => [
310
                        ModelHelper::SCENARIO_DEFAULT
311
                    ]
312
                ]
313
            ]
314
        );
315
    }
316
317
    /*******************************************
318
     * SEARCH
319
     *******************************************/
320
321
    /**
322
     * @param ObjectAssociationQuery $value
323
     * @inheritdoc
324
     */
325
    public function getSearchKeywords($value, ElementInterface $element): string
326
    {
327
        $objects = [];
328
329
        foreach ($value->all() as $model) {
330
            array_push($objects, $model->objectId);
331
        }
332
333
        return parent::getSearchKeywords($objects, $element);
334
    }
335
336
    /*******************************************
337
     * VIEWS
338
     *******************************************/
339
340
    /**
341
     * @param ObjectAssociationQuery $value
342
     * @inheritdoc
343
     * @throws \Twig_Error_Loader
344
     * @throws \yii\base\Exception
345
     */
346
    public function getInputHtml($value, ElementInterface $element = null): string
347
    {
348
        $value->limit(null);
349
        return HubSpot::getInstance()->getObjectsField()->getInputHtml($this, $value, $element, false);
350
    }
351
352
    /**
353
     * @inheritdoc
354
     * @throws \Twig_Error_Loader
355
     * @throws \yii\base\Exception
356
     */
357
    public function getSettingsHtml()
358
    {
359
        return HubSpot::getInstance()->getObjectsField()->getSettingsHtml($this);
360
    }
361
362
    /*******************************************
363
     * EVENTS
364
     *******************************************/
365
366
    /**
367
     * @inheritdoc
368
     * @throws \Exception
369
     */
370
    public function afterElementSave(ElementInterface $element, bool $isNew)
371
    {
372
        /** @var ObjectAssociationQuery $value */
373
        $value = $element->getFieldValue($this->handle);
374
375
        HubSpot::getInstance()->getObjectAssociations()->save($value);
376
377
        parent::afterElementSave($element, $isNew);
378
    }
379
}
380