Completed
Push — master ( f8c4bd...25c22e )
by Nate
09:23 queued 07:32
created

Objects::createResourceCriteria()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

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