Passed
Pull Request — master (#21)
by Matthew
01:49
created

Mapper::objectUpToDate()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
c 0
b 0
f 0
dl 0
loc 11
rs 10
cc 4
nc 2
nop 4
1
<?php
2
3
namespace Dynamic\Salsify\Model;
4
5
use Dynamic\Salsify\Task\ImportTask;
6
use Exception;
7
use JsonMachine\JsonMachine;
8
use SilverStripe\ORM\DataObject;
9
10
/**
11
 * Class Mapper
12
 * @package Dynamic\Salsify\Model
13
 */
14
class Mapper extends Service
15
{
16
17
    /**
18
     * @var
19
     */
20
    private $file = null;
21
22
    /**
23
     * @var JsonMachine
24
     */
25
    private $productStream;
26
27
    /**
28
     * @var JsonMachine
29
     */
30
    private $assetStream;
31
32
    /**
33
     * @var array
34
     */
35
    private $currentUniqueFields;
36
37
    /**
38
     * @var int
39
     */
40
    private $importCount = 0;
41
42
    /**
43
     * Mapper constructor.
44
     * @param string $importerKey
45
     * @param $file
46
     * @throws \Exception
47
     */
48
    public function __construct($importerKey, $file = null)
49
    {
50
        parent::__construct($importerKey);
51
        if (!$this->config()->get('mapping')) {
52
            throw  new Exception('A Mapper needs a mapping');
53
        }
54
55
        if ($file !== null) {
56
            $this->file = $file;
57
            $this->productStream = JsonMachine::fromFile($file, '/4/products');
58
            $this->resetAssetStream();
59
        }
60
    }
61
62
    /**
63
     *
64
     */
65
    public function resetAssetStream()
66
    {
67
        $this->assetStream = JsonMachine::fromFile($this->file, '/3/digital_assets');
68
    }
69
70
    /**
71
     * Maps the data
72
     * @throws \Exception
73
     */
74
    public function map()
75
    {
76
        foreach ($this->productStream as $name => $data) {
77
            foreach ($this->config()->get('mapping') as $class => $mappings) {
78
                $this->mapToObject($class, $mappings, $data);
79
                $this->currentUniqueFields = [];
80
            }
81
        }
82
        ImportTask::output("Imported and updated $this->importCount products.");
83
    }
84
85
    /**
86
     * @param string|DataObject $class
87
     * @param array $mappings The mapping for a specific class
88
     * @param array $data
89
     *
90
     * @return DataObject
91
     * @throws \Exception
92
     */
93
    public function mapToObject($class, $mappings, $data)
94
    {
95
        $object = $this->findObjectByUnique($class, $mappings, $data);
96
        if (!$object) {
0 ignored issues
show
introduced by
$object is of type SilverStripe\ORM\DataObject, thus it always evaluated to true.
Loading history...
97
            $object = $class::create();
98
        }
99
100
        $firstUniqueKey = array_keys($this->uniqueFields($mappings))[0];
101
        $firstUniqueValue = $data[$mappings[$firstUniqueKey]['salsifyField']];
102
        ImportTask::output("Updating $firstUniqueKey $firstUniqueValue");
103
104
        if ($this->objectUpToDate($object, $data, $firstUniqueKey, $firstUniqueValue)) {
105
            return $object;
106
        }
107
108
        foreach ($mappings as $dbField => $salsifyField) {
109
            $field = $this->getField($salsifyField, $data);
110
            if ($field === false) {
111
                continue;
112
            }
113
            
114
            $value = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $value is dead and can be removed.
Loading history...
115
            $type = $this->getFieldType($salsifyField);
116
            $objectData = $data;
117
118
            if (is_array($salsifyField)) {
119
                if ($this->handleShouldSkip($dbField, $salsifyField, $data)) {
120
                    ImportTask::output("Skipping $firstUniqueKey $firstUniqueValue");
121
                    return null;
122
                };
123
124
                $objectData = $this->handleModification($dbField, $salsifyField, $data);
125
            }
126
127
            $value = $this->handleType($type, $objectData, $field, $salsifyField, $dbField, $class);
0 ignored issues
show
Bug introduced by
$type of type string is incompatible with the type integer expected by parameter $type of Dynamic\Salsify\Model\Mapper::handleType(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

127
            $value = $this->handleType(/** @scrutinizer ignore-type */ $type, $objectData, $field, $salsifyField, $dbField, $class);
Loading history...
128
            $this->writeValue($object, $dbField, $value);
129
        }
130
131
        if ($object->isChanged()) {
132
            $object->write();
133
            $this->importCount++;
134
        } else {
135
            ImportTask::output("$firstUniqueKey $firstUniqueValue was not changed.");
136
        }
137
        return $object;
138
    }
139
140
    /**
141
     * @param DataObject $object
142
     * @param array $data
143
     * @param string $firstUniqueKey
144
     * @param string $firstUniqueValue
145
     * @return bool
146
     */
147
    private function objectUpToDate($object, $data, $firstUniqueKey, $firstUniqueValue)
148
    {
149
        if (
150
            $this->config()->get('skipUpToDate') == true &&
151
            $object->hasField('SalsifyUpdatedAt') &&
152
            $data['salsify:updated_at'] == $object->getField('SalsifyUpdatedAt')
153
        ) {
154
            ImportTask::output("Skipping $firstUniqueKey $firstUniqueValue. It is up to Date.");
155
            return true;
156
        }
157
        return false;
158
    }
159
160
    /**
161
     * @param array $salsifyField
162
     * @param array $data
163
     *
164
     * @return string|false
165
     */
166
    private function getField($salsifyField, $data)
167
    {
168
        if (!is_array($salsifyField)) {
0 ignored issues
show
introduced by
The condition is_array($salsifyField) is always true.
Loading history...
169
            return array_key_exists($salsifyField, $data) ? $salsifyField : false;
170
        }
171
172
        $hasSalsifyField = array_key_exists('salsifyField', $salsifyField);
0 ignored issues
show
Unused Code introduced by
The assignment to $hasSalsifyField is dead and can be removed.
Loading history...
173
        $isLiteralField = (
174
            $this->getFieldType($salsifyField) === 'Literal' &&
175
            array_key_exists('value', $salsifyField)
176
        );
177
178
        if ($isLiteralField) {
179
            return $salsifyField['value'];
180
        }
181
182
        if (array_key_exists($salsifyField['salsifyField'], $data)) {
183
            return $salsifyField['salsifyField'];
184
        } else if (array_key_exists('fallback', $salsifyField)) {
185
            // make fallback an array
186
            if (!is_array($salsifyField['fallback'])) {
187
                $salsifyField['fallback'] = [$salsifyField['fallback']];
188
            }
189
190
            foreach ($salsifyField['fallback'] as $fallback) {
191
                if (array_key_exists($fallback, $data)) {
192
                    return $fallback;
193
                }
194
            }
195
        }
196
197
        return false;
198
    }
199
200
    /**
201
     * @param string $class
202
     * @param array $mappings
203
     * @param array $data
204
     *
205
     * @return \SilverStripe\ORM\DataObject
206
     */
207
    private function findObjectByUnique($class, $mappings, $data)
208
    {
209
        $uniqueFields = $this->uniqueFields($mappings);
210
        // creates a filter
211
        $filter = [];
212
        foreach ($uniqueFields as $dbField => $salsifyField) {
213
            $modifiedData = $data;
214
            $fieldMapping = $mappings[$dbField];
215
216
            $modifiedData = $this->handleModification($dbField, $fieldMapping, $modifiedData);
217
218
            // adds unique fields to filter
219
            $filter[$dbField] = $modifiedData[$salsifyField];
220
        }
221
222
        return DataObject::get($class)->filter($filter)->first();
223
    }
224
225
    /**
226
     * Gets a list of all the unique field keys
227
     *
228
     * @param array $mappings
229
     * @return array
230
     */
231
    private function uniqueFields($mappings)
232
    {
233
        // cached after first map
234
        if (!empty($this->currentUniqueFields)) {
235
            return $this->currentUniqueFields;
236
        }
237
238
        $uniqueFields = [];
239
        foreach ($mappings as $dbField => $salsifyField) {
240
            if (!is_array($salsifyField)) {
241
                continue;
242
            }
243
244
            if (
245
                !array_key_exists('unique', $salsifyField) ||
246
                !array_key_exists('salsifyField', $salsifyField)
247
            ) {
248
                continue;
249
            }
250
251
            if ($salsifyField['unique'] !== true) {
252
                continue;
253
            }
254
255
            $uniqueFields[$dbField] = $salsifyField['salsifyField'];
256
        }
257
258
        $this->currentUniqueFields = $uniqueFields;
259
        return $uniqueFields;
260
    }
261
262
    /**
263
     * @param string $dbField
264
     * @param array $config
265
     * @param array $data
266
     * @return array
267
     */
268
    private function handleModification($dbField, $config, $data)
269
    {
270
        if (array_key_exists('modification', $config)) {
271
            $mod = $config['modification'];
272
            if ($this->hasMethod($mod)) {
273
                return $this->{$mod}($dbField, $config, $data);
274
            }
275
            ImportTask::output("{$mod} is not a valid field modifier. skipping modification for field {$dbField}.");
276
        }
277
        return $data;
278
    }
279
280
    /**
281
     * @param string $dbField
282
     * @param array $config
283
     * @param array $data
284
     * @return boolean
285
     */
286
    private function handleShouldSkip($dbField, $config, $data)
287
    {
288
        if (array_key_exists('shouldSkip', $config)) {
289
            $skipMethod = $config['shouldSkip'];
290
            if ($this->hasMethod($skipMethod)) {
291
                return $this->{$skipMethod}($dbField, $config, $data);
292
            }
293
            ImportTask::output("{$skipMethod} is not a valid skip test method. Skipping skip test for field {$dbField}.");
294
        }
295
        return false;
296
    }
297
298
    /**
299
     * @param string|array $field
300
     * @return string
301
     */
302
    public function getFieldType($field)
303
    {
304
        $fieldTypes = $this->config()->get('field_types');
305
        if (is_array($field) && array_key_exists('type', $field)) {
306
            if (in_array($field['type'], $fieldTypes)) {
307
                return $field['type'];
308
            }
309
        }
310
        // default to raw
311
        return 'Raw';
312
    }
313
314
    /**
315
     * @param int $type
316
     * @param array $salsifyData
317
     * @param string $salsifyField
318
     * @param array $dbFieldConfig
319
     * @param string $dbField
320
     * @param string $class
321
     *
322
     * @return mixed
323
     */
324
    private function handleType($type, $salsifyData, $salsifyField, $dbFieldConfig, $dbField, $class)
325
    {
326
        if ($this->hasMethod("handle{$type}Type")) {
327
            return $this->{"handle{$type}Type"}($salsifyData, $salsifyField, $dbFieldConfig, $dbField, $class);
328
        }
329
        ImportTask::output("{$type} is not a valid type. skipping field {$dbField}.");
330
        return '';
331
    }
332
333
    /**
334
     * @param DataObject $object
335
     * @param string $dbField
336
     * @param mixed $value
337
     *
338
     * @throws \Exception
339
     */
340
    private function writeValue($object, $dbField, $value)
341
    {
342
        $isManyRelation = array_key_exists($dbField, $object->config()->get('has_many')) ||
343
            array_key_exists($dbField, $object->config()->get('many_many')) ||
344
            array_key_exists($dbField, $object->config()->get('belongs_many_many'));
345
346
        if (!$isManyRelation) {
347
            $object->$dbField = $value;
348
            return;
349
        }
350
351
        if (!$object->exists()) {
352
            $object->write();
353
        }
354
355
        if (is_array($value)) {
356
            $object->{$dbField}()->addMany($value);
357
            return;
358
        }
359
360
        $object->{$dbField}()->add($value);
361
    }
362
363
    /**
364
     * @return \JsonMachine\JsonMachine
365
     */
366
    public function getAssetStream()
367
    {
368
        return $this->assetStream;
369
    }
370
371
    /**
372
     * @return bool
373
     */
374
    public function hasFile()
375
    {
376
        return $this->file !== null;
377
    }
378
}
379