Completed
Push — master ( 99c3bc...8ae47d )
by Nate
11:33 queued 09:36
created

Objects::getConnection()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 0
cts 5
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
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\connections\ConnectionInterface;
18
use flipbox\hubspot\db\ObjectAssociationQuery;
19
use flipbox\hubspot\HubSpot;
20
use flipbox\hubspot\services\resources\CRUDInterface;
21
use Psr\SimpleCache\CacheInterface;
22
use yii\base\InvalidConfigException;
23
24
/**
25
 * @author Flipbox Factory <[email protected]>
26
 * @since 1.0.0
27
 */
28
class Objects extends Field
29
{
30
    /**
31
     * The action event name
32
     */
33
    const EVENT_REGISTER_ACTIONS = 'registerActions';
34
35
    /**
36
     * The action event name
37
     */
38
    const EVENT_REGISTER_AVAILABLE_ACTIONS = 'registerAvailableActions';
39
40
    /**
41
     * The item action event name
42
     */
43
    const EVENT_REGISTER_ITEM_ACTIONS = 'registerItemActions';
44
45
    /**
46
     * The item action event name
47
     */
48
    const EVENT_REGISTER_AVAILABLE_ITEM_ACTIONS = 'registerAvailableItemActions';
49
50
    /**
51
     * The input template path
52
     */
53
    const INPUT_TEMPLATE_PATH = 'hubspot/_components/fieldtypes/Objects/input';
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 array
82
     */
83
    public $selectedActions = [];
84
85
    /**
86
     * @var array
87
     */
88
    public $selectedItemActions = [];
89
90
    /**
91
     * @var string|null
92
     */
93
    public $selectionLabel;
94
95
    /**
96
     * Indicates whether the full sync operation should be preformed if a matching HubSpot Object was found but not
97
     * currently associated to the element.  For example, when attempting to Sync a Craft User to a HubSpot Contact, if
98
     * the HubSpot Contact already exists; true would override data in HubSpot while false would just perform
99
     * an association (note, a subsequent sync operation could be preformed)
100
     * @var bool
101
     */
102
    public $syncToHubSpotOnMatch = false;
103
104
    /**
105
     * @inheritdoc
106
     */
107
    public static function displayName(): string
108
    {
109
        return Craft::t('hubspot', 'HubSpot Objects');
110
    }
111
112
    /**
113
     * @inheritdoc
114
     */
115
    public static function defaultSelectionLabel(): string
116
    {
117
        return Craft::t('hubspot', 'Add a HubSpot Objects');
118
    }
119
120
    /**
121
     * @inheritdoc
122
     */
123
    public static function hasContentColumn(): bool
124
    {
125
        return false;
126
    }
127
128
    /*******************************************
129
     * VALIDATION
130
     *******************************************/
131
132
    /**
133
     * @inheritdoc
134
     */
135
    public function getElementValidationRules(): array
136
    {
137
        return [
138
            [
139
                MinMaxValidator::class,
140
                'min' => $this->min ? (int)$this->min : null,
141
                'max' => $this->max ? (int)$this->max : null,
142
                'tooFew' => Craft::t(
143
                    'hubspot',
144
                    '{attribute} should contain at least {min, number} {min, plural, one{domain} other{domains}}.'
145
                ),
146
                'tooMany' => Craft::t(
147
                    'hubspot',
148
                    '{attribute} should contain at most {max, number} {max, plural, one{domain} other{domains}}.'
149
                ),
150
                'skipOnEmpty' => false
151
            ]
152
        ];
153
    }
154
155
    /*******************************************
156
     * CONNECTION
157
     *******************************************/
158
159
    /**
160
     * @return ConnectionInterface
161
     * @throws \yii\base\InvalidConfigException
162
     */
163
    public function getConnection(): ConnectionInterface
164
    {
165
        $service = HubSpot::getInstance()->getConnections();
166
        return $service->get($service::DEFAULT_CONNECTION);
167
    }
168
169
    /*******************************************
170
     * CACHE
171
     *******************************************/
172
173
    /**
174
     * @return CacheInterface
175
     * @throws \yii\base\InvalidConfigException
176
     */
177
    public function getCache(): CacheInterface
178
    {
179
        $service = HubSpot::getInstance()->getCache();
180
        return $service->get($service::DEFAULT_CACHE);
181
    }
182
183
    /*******************************************
184
     * CRUD
185
     *******************************************/
186
187
    /**
188
     * @return CRUDInterface
189
     * @throws InvalidConfigException
190
     */
191
    public function getResource(): CRUDInterface
192
    {
193
        $service = HubSpot::getInstance()->getResources()->get($this->object);
194
195
        if (!$service instanceof CRUDInterface) {
196
            throw new InvalidConfigException(sprintf(
197
                "Resource must be an instance of '%s', '%s' given",
198
                CRUDInterface::class,
199
                get_class($service)
200
            ));
201
        }
202
203
        return $service;
204
    }
205
206
    /*******************************************
207
     * VALUE
208
     *******************************************/
209
210
    /**
211
     * @inheritdoc
212
     */
213
    public function normalizeValue($value, ElementInterface $element = null)
214
    {
215
        return HubSpot::getInstance()->getObjectsField()->normalizeValue(
216
            $this,
217
            $value,
218
            $element
219
        );
220
    }
221
222
223
    /*******************************************
224
     * ELEMENT
225
     *******************************************/
226
227
    /**
228
     * @inheritdoc
229
     */
230
    public function modifyElementsQuery(ElementQueryInterface $query, $value)
231
    {
232
        return HubSpot::getInstance()->getObjectsField()->modifyElementsQuery(
233
            $this,
234
            $query,
235
            $value
236
        );
237
    }
238
239
240
    /*******************************************
241
     * RULES
242
     *******************************************/
243
244
    /**
245
     * @inheritdoc
246
     */
247
    public function rules()
248
    {
249
        return array_merge(
250
            parent::rules(),
251
            [
252
                [
253
                    'object',
254
                    'required',
255
                    'message' => Craft::t('hubspot', 'Hubspot Object cannot be empty.')
256
                ],
257
                [
258
                    [
259
                        'object',
260
                        'min',
261
                        'max',
262
                        'viewUrl',
263
                        'listUrl',
264
                        'selectionLabel'
265
                    ],
266
                    'safe',
267
                    'on' => [
268
                        ModelHelper::SCENARIO_DEFAULT
269
                    ]
270
                ]
271
            ]
272
        );
273
    }
274
275
    /*******************************************
276
     * SEARCH
277
     *******************************************/
278
279
    /**
280
     * @param ObjectAssociationQuery $value
281
     * @inheritdoc
282
     */
283
    public function getSearchKeywords($value, ElementInterface $element): string
284
    {
285
        $objects = [];
286
287
        foreach ($value->all() as $model) {
288
            array_push($objects, $model->objectId);
289
        }
290
291
        return parent::getSearchKeywords($objects, $element);
292
    }
293
294
    /*******************************************
295
     * VIEWS
296
     *******************************************/
297
298
    /**
299
     * @param ObjectAssociationQuery $value
300
     * @inheritdoc
301
     * @throws \Twig_Error_Loader
302
     * @throws \yii\base\Exception
303
     */
304
    public function getInputHtml($value, ElementInterface $element = null): string
305
    {
306
        $value->limit(null);
307
        return HubSpot::getInstance()->getObjectsField()->getInputHtml($this, $value, $element, false);
308
    }
309
310
    /**
311
     * @inheritdoc
312
     * @throws \Twig_Error_Loader
313
     * @throws \yii\base\Exception
314
     */
315
    public function getSettingsHtml()
316
    {
317
        return HubSpot::getInstance()->getObjectsField()->getSettingsHtml($this);
318
    }
319
320
    /*******************************************
321
     * EVENTS
322
     *******************************************/
323
324
    /**
325
     * @inheritdoc
326
     * @throws \Exception
327
     */
328
    public function afterElementSave(ElementInterface $element, bool $isNew)
329
    {
330
        /** @var ObjectAssociationQuery $value */
331
        $value = $element->getFieldValue($this->handle);
332
333
        HubSpot::getInstance()->getObjectAssociations()->save($value);
334
335
        parent::afterElementSave($element, $isNew);
336
    }
337
}
338