Completed
Push — master ( 7d28f4...e7e513 )
by Nate
06:34
created

SOQL::getVariables()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
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/force/license
6
 * @link       https://www.flipboxfactory.com/software/force/
7
 */
8
9
namespace flipbox\craft\salesforce\records;
10
11
use Craft;
12
use craft\helpers\Json;
13
use flipbox\craft\ember\helpers\ModelHelper;
14
use flipbox\craft\ember\models\HandleRulesTrait;
15
use flipbox\craft\ember\records\ActiveRecordWithId;
16
use flipbox\craft\salesforce\queries\SOQLQuery;
17
use flipbox\craft\salesforce\validators\QueryBuilderValidator;
18
use flipbox\craft\salesforce\criteria\QueryCriteria;
19
use Flipbox\Salesforce\Query\DynamicQueryBuilderInterface;
20
use Psr\Http\Message\ResponseInterface;
21
use yii\validators\UniqueValidator;
22
23
/**
24
 * @author Flipbox Factory <[email protected]>
25
 * @since 1.0.0
26
 *
27
 * @property string $name
28
 * @property string $settings
29
 * @property string $class
30
 * @property string $soql
31
 */
32
class SOQL extends ActiveRecordWithId implements DynamicQueryBuilderInterface
33
{
34
    use HandleRulesTrait;
35
36
    /**
37
     * The table name
38
     */
39
    const TABLE_ALIAS = 'salesforce_queries';
40
41
    /**
42
     * The Active Query class
43
     */
44
    const ACTIVE_QUERY_CLASS = SOQLQuery::class;
45
46
    /**
47
     * @inheritdoc
48
     */
49
    public function init()
50
    {
51
        parent::init();
52
53
        // Always this class
54
        $this->class = static::class;
55
    }
56
57
58
    /*******************************************
59
     * SETTINGS
60
     *******************************************/
61
62
    /**
63
     * @inheritdoc
64
     * @throws \Twig_Error_Loader
65
     * @throws \yii\base\Exception
66
     */
67
    public function settingsHtml(): string
68
    {
69
        return Craft::$app->getView()->renderTemplate(
70
            'salesforce/_components/queries/dynamic',
71
            [
72
                'record' => $this
73
            ]
74
        );
75
    }
76
77
    /*******************************************
78
     * QUERY
79
     *******************************************/
80
81
    /**
82
     * @inheritdoc
83
     */
84
    public static function find()
85
    {
86
        /** @noinspection PhpUnhandledExceptionInspection */
87
        /** @noinspection PhpIncompatibleReturnTypeInspection */
88
        return Craft::createObject(
89
            static::ACTIVE_QUERY_CLASS,
90
            [
91
                get_called_class(),
92
                [
93
                    'class' => static::class
94
                ]
95
            ]
96
        );
97
    }
98
99
    /**
100
     * @inheritdoc
101
     */
102
    protected static function findByCondition($condition)
103
    {
104
        if (!is_numeric($condition) && is_string($condition)) {
105
            $condition = ['handle' => $condition];
106
        }
107
108
        /** @noinspection PhpInternalEntityUsedInspection */
109
        return parent::findByCondition($condition);
110
    }
111
112
    /**
113
     * @inheritdoc
114
     */
115
    public function rules()
116
    {
117
        return array_merge(
118
            parent::rules(),
119
            $this->handleRules(),
120
            [
121
                [
122
                    [
123
                        'class'
124
                    ],
125
                    QueryBuilderValidator::class
126
                ],
127
                [
128
                    [
129
                        'name'
130
                    ],
131
                    'required'
132
                ],
133
                [
134
                    [
135
                        'class'
136
                    ],
137
                    'required'
138
                ],
139
                [
140
                    [
141
                        'name',
142
                    ],
143
                    'string',
144
                    'max' => 255
145
                ],
146
                [
147
                    [
148
                        'handle'
149
                    ],
150
                    UniqueValidator::class
151
                ],
152
                [
153
                    [
154
                        'name',
155
                        'settings',
156
                        'soql'
157
                    ],
158
                    'safe',
159
                    'on' => [
160
                        ModelHelper::SCENARIO_DEFAULT
161
                    ]
162
                ]
163
            ]
164
        );
165
    }
166
167
    /**
168
     * @return QueryCriteria
169
     *
170
     * @deprecated
171
     */
172
    public function getCriteria(): QueryCriteria
173
    {
174
        return new QueryCriteria([
175
            'query' => $this
176
        ]);
177
    }
178
179
    /*******************************************
180
     * EVENTS
181
     *******************************************/
182
183
    /**
184
     * @param bool $insert
185
     * @param array $changedAttributes
186
     */
187
    public function afterSave($insert, $changedAttributes)
188
    {
189
        parent::afterSave($insert, $changedAttributes);
190
        $this->ensureSettings();
191
    }
192
193
194
    /*******************************************
195
     * NEW RECORD
196
     *******************************************/
197
198
    /**
199
     * @inheritdoc
200
     */
201
    public static function instantiate($row)
202
    {
203
        $class = $row['class'] ?? static::class;
204
        return new $class;
205
    }
206
207
    /**
208
     * @param static $record
209
     * @param $row
210
     */
211
    public static function populateRecord($record, $row)
212
    {
213
        parent::populateRecord($record, $row);
214
215
        // Ensure settings is an array
216
        $record->setOldAttribute('settings', $record->ensureSettings());
217
    }
218
219
220
    /*******************************************
221
     * SETTINGS
222
     *******************************************/
223
224
    /**
225
     * @param string $attribute
226
     * @return mixed
227
     */
228
    public function getSettingsValue(string $attribute)
229
    {
230
        $settings = $this->ensureSettings();
231
        return $settings[$attribute] ?? null;
232
    }
233
234
    /**
235
     * @param string $attribute
236
     * @param $value
237
     * @return $this
238
     */
239
    public function setSettingsValue(string $attribute, $value)
240
    {
241
        $settings = $this->ensureSettings();
242
        $settings[$attribute] = $value;
243
244
        $this->setAttribute('settings', $settings);
245
        return $this;
246
    }
247
248
    /**
249
     * @return array|null
250
     */
251
    protected function ensureSettings()
252
    {
253
        $settings = $this->getAttribute('settings');
254
255
        if (is_string($settings)) {
256
            $settings = Json::decodeIfJson($settings);
257
        }
258
259
        $this->setAttribute('settings', $settings);
260
261
        return $settings;
262
    }
263
264
265
    /*******************************************
266
     * RETRIEVE QUERY
267
     *******************************************/
268
269
    /**
270
     * @param array $criteria
271
     * @param array $config
272
     * @return ResponseInterface
273
     * @throws \flipbox\craft\ember\exceptions\RecordNotFoundException
274
     * @throws \yii\base\InvalidConfigException
275
     */
276
    public function fetch(array $criteria = [], array $config = []): ResponseInterface
277
    {
278
        return (new QueryCriteria([
279
            'query' => $this->build()
280
        ]))->fetch($criteria, $config);
281
    }
282
283
    /*******************************************
284
     * BUILDER INTERFACE
285
     *******************************************/
286
287
    /**
288
     * @return array
289
     */
290
    public function getVariables(): array
291
    {
292
        return (array)($this->getSettingsValue('variables') ?: []);
293
    }
294
295
    /**
296
     * @inheritdoc
297
     */
298
    public function setVariables(array $variables = [])
299
    {
300
        return $this->setSettingsValue('variables', $variables);
301
    }
302
303
    /**
304
     * @return string
305
     */
306
    public function build(): string
307
    {
308
        if (null === ($soql = $this->soql)) {
309
            return '';
310
        }
311
312
        return Craft::$app->getView()->renderString(
313
            $soql,
314
            $this->getVariables()
315
        );
316
    }
317
318
    /**
319
     * @return string
320
     */
321
    public function __toString()
322
    {
323
        return $this->build();
324
    }
325
}
326