Passed
Pull Request — master (#39)
by Matthew
09:38
created

Mapper::getMappings()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 2
nc 2
nop 0
1
<?php
2
3
namespace Dynamic\Salsify\Model;
4
5
use Dyanmic\Salsify\ORM\SalsifyIDExtension;
6
use Dynamic\Salsify\Task\ImportTask;
7
use Exception;
8
use JsonMachine\JsonMachine;
9
use SilverStripe\Core\Injector\Injector;
10
use SilverStripe\ORM\DataList;
11
use SilverStripe\ORM\DataObject;
12
use SilverStripe\Versioned\Versioned;
0 ignored issues
show
Bug introduced by
The type SilverStripe\Versioned\Versioned was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
13
14
/**
15
 * Class Mapper
16
 * @package Dynamic\Salsify\Model
17
 */
18
class Mapper extends Service
19
{
20
21
    public const STOP_GENERATOR = 'stop';
22
23
    /**
24
     * @var
25
     */
26
    private $file = null;
27
28
    /**
29
     * @var JsonMachine
30
     */
31
    private $productStream;
32
33
    /**
34
     * @var JsonMachine
35
     */
36
    private $assetStream;
37
38
    /**
39
     * @var array
40
     */
41
    private $currentUniqueFields = [];
42
43
    /**
44
     * @var int
45
     */
46
    private $importCount = 0;
47
48
    /**
49
     * @var bool
50
     */
51
    public $skipSiliently = false;
52
53
    /**
54
     * Mapper constructor.
55
     * @param string $importerKey
56
     * @param $file
57
     * @throws \Exception
58
     */
59
    public function __construct($importerKey, $file = null)
60
    {
61
        parent::__construct($importerKey);
62
        if (!$this->config()->get('mapping')) {
63
            throw  new Exception('A Mapper needs a mapping');
64
        }
65
66
        if ($file !== null) {
67
            $this->file = $file;
68
            $this->resetProductSteam();
69
            $this->resetAssetStream();
70
        }
71
    }
72
73
    /**
74
     *
75
     */
76
    protected function resetAssetStream()
77
    {
78
        $this->assetStream = JsonMachine::fromFile($this->file, '/3/digital_assets');
79
    }
80
81
    /**
82
     *
83
     */
84
    protected function resetProductSteam()
85
    {
86
        $this->productStream = JsonMachine::fromFile($this->file, '/4/products');
87
    }
88
89
    /**
90
     * @return \Generator|void
91
     * @throws Exception
92
     */
93
    public function getAssets()
94
    {
95
        foreach ($this->assetStream as $name => $data) {
96
            $injected = (yield $name => $data);
97
            if ($injected === static::STOP_GENERATOR) break;
98
        }
99
        $this->resetAssetStream();
100
    }
101
102
    /**
103
     * @return \Generator|void
104
     * @throws Exception
105
     */
106
    public function getProducts()
107
    {
108
        foreach ($this->productStream as $name => $data) {
109
            $injected = yield $name => $data;
110
            if ($injected === static::STOP_GENERATOR) break;
111
        }
112
        $this->resetProductSteam();
113
    }
114
115
    /**
116
     * @return \Generator
117
     */
118
    protected function getMappings()
119
    {
120
        foreach ($this->config()->get('mapping') as $class => $mappings) {
121
            yield $class => $mappings;
122
        }
123
    }
124
125
    /**
126
     * Maps the data
127
     * @throws \Exception
128
     */
129
    public function map()
130
    {
131
        foreach ($this->getProducts() as $name => $data) {
132
            foreach ($this->getMappings() as $class => $mappings) {
133
                $this->mapToObject($class, $mappings, $data);
134
                $this->currentUniqueFields = [];
135
            }
136
        }
137
        ImportTask::output("Imported and updated $this->importCount products.");
138
    }
139
140
    /**
141
     * @param $mappings
142
     * @return \Generator
143
     */
144
    protected function getFieldMappings($mappings)
145
    {
146
        foreach ($mappings as $dbField => $salsifyField) {
147
            yield $dbField => $salsifyField;
148
        }
149
    }
150
151
    /**
152
     * @param string|DataObject $class
153
     * @param array $mappings The mapping for a specific class
154
     * @param array $data
155
     * @param DataObject|null $object
156
     *
157
     * @return DataObject
158
     * @throws \Exception
159
     */
160
    public function mapToObject($class, $mappings, $data, $object = null)
161
    {
162
        // if object was not passed
163
        if ($object === null) {
164
            $object = $this->findObjectByUnique($class, $mappings, $data);
165
            // if no existing object was found
166
            if (!$object) {
0 ignored issues
show
introduced by
$object is of type SilverStripe\ORM\DataObject, thus it always evaluated to true.
Loading history...
167
                $object = $class::create();
168
            }
169
        }
170
171
        $wasPublished = $object->hasExtension(Versioned::class) ? $object->isPublished() : false;
172
        $wasWritten = $object->isInDB();
173
174
        $firstUniqueKey = array_keys($this->uniqueFields($class, $mappings))[0];
175
        if (array_key_exists($mappings[$firstUniqueKey]['salsifyField'], $data)) {
176
            $firstUniqueValue = $data[$mappings[$firstUniqueKey]['salsifyField']];
177
        } else {
178
            $firstUniqueValue = 'NULL';
179
        }
180
        ImportTask::output("Updating $class $firstUniqueKey $firstUniqueValue");
181
182
        if ($this->objectUpToDate($object, $data, $firstUniqueKey, $firstUniqueValue)) {
183
            return $object;
184
        }
185
186
        foreach ($this->getFieldMappings($mappings) as $dbField => $salsifyField) {
187
            $field = $this->getField($salsifyField, $data);
188
            if ($field === false) {
189
                continue;
190
            }
191
192
            $value = null;
193
            $type = $this->getFieldType($salsifyField);
194
            $objectData = $data;
195
196
            if (is_array($salsifyField)) {
197
                if ($this->handleShouldSkip($class, $dbField, $salsifyField, $data)) {
198
                    if (!$this->skipSiliently) {
199
                        ImportTask::output("Skipping $class $firstUniqueKey $firstUniqueValue");
200
                        $this->skipSiliently = false;
201
                    }
202
                    return null;
203
                };
204
205
                $objectData = $this->handleModification($class, $dbField, $salsifyField, $data);
206
            }
207
208
            if (!array_key_exists($field, $objectData)) {
209
                continue;
210
            }
211
212
            $value = $this->handleType($type, $class, $objectData, $field, $salsifyField, $dbField);
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

212
            $value = $this->handleType(/** @scrutinizer ignore-type */ $type, $class, $objectData, $field, $salsifyField, $dbField);
Loading history...
213
            $this->writeValue($object, $dbField, $value);
214
        }
215
216
        if ($object->isChanged()) {
217
            $object->write();
218
            $this->importCount++;
219
            $this->extend('afterObjectWrite', $object, $wasWritten, $wasPublished);
220
        } else {
221
            ImportTask::output("$class $firstUniqueKey $firstUniqueValue was not changed.");
222
        }
223
        return $object;
224
    }
225
226
    /**
227
     * @param DataObject $object
228
     * @param array $data
229
     * @param string $firstUniqueKey
230
     * @param string $firstUniqueValue
231
     * @return bool
232
     */
233
    private function objectUpToDate($object, $data, $firstUniqueKey, $firstUniqueValue)
234
    {
235
        if (
236
            $this->config()->get('skipUpToDate') == true &&
237
            $object->hasField('SalsifyUpdatedAt') &&
238
            $data['salsify:updated_at'] == $object->getField('SalsifyUpdatedAt')
239
        ) {
240
            ImportTask::output("Skipping $firstUniqueKey $firstUniqueValue. It is up to Date.");
241
            return true;
242
        }
243
        return false;
244
    }
245
246
    /**
247
     * @param array $salsifyField
248
     * @param array $data
249
     *
250
     * @return string|false
251
     */
252
    private function getField($salsifyField, $data)
253
    {
254
        if (!is_array($salsifyField)) {
0 ignored issues
show
introduced by
The condition is_array($salsifyField) is always true.
Loading history...
255
            return array_key_exists($salsifyField, $data) ? $salsifyField : false;
256
        }
257
258
        $hasSalsifyField = array_key_exists('salsifyField', $salsifyField);
259
        $isLiteralField = (
260
            $this->getFieldType($salsifyField) === 'Literal' &&
261
            array_key_exists('value', $salsifyField)
262
        );
263
264
        if ($isLiteralField) {
265
            return $salsifyField['value'];
266
        }
267
268
        if (!$hasSalsifyField) {
269
            return false;
270
        }
271
272
        if (array_key_exists($salsifyField['salsifyField'], $data)) {
273
            return $salsifyField['salsifyField'];
274
        } elseif (array_key_exists('fallback', $salsifyField)) {
275
            // make fallback an array
276
            if (!is_array($salsifyField['fallback'])) {
277
                $salsifyField['fallback'] = [$salsifyField['fallback']];
278
            }
279
280
            foreach ($salsifyField['fallback'] as $fallback) {
281
                if (array_key_exists($fallback, $data)) {
282
                    return $fallback;
283
                }
284
            }
285
        } elseif (array_key_exists('modification', $salsifyField)) {
286
            return $salsifyField['salsifyField'];
287
        }
288
289
        return false;
290
    }
291
292
    /**
293
     * @param string $class
294
     * @param array $mappings
295
     * @param array $data
296
     *
297
     * @return \SilverStripe\ORM\DataObject
298
     */
299
    private function findObjectByUnique($class, $mappings, $data)
300
    {
301
        /** @var DataObject $genericObject */
302
        $genericObject = Injector::inst()->get($class);
303
        if (
304
            $genericObject->hasExtension(SalsifyIDExtension::class) ||
305
            $genericObject->hasField('SalsifyID')
306
        ) {
307
            $modifiedData = $data;
308
            if (array_key_exists('salsify:id', $mappings)) {
309
                $modifiedData = $this->handleModification($class, 'salsify:id', $mappings['salsify:id'], $modifiedData);
310
            }
311
            $obj = DataObject::get($class)->filter([
312
                'SalsifyID' => $modifiedData['salsify:id'],
313
            ])->first();
314
            if ($obj) {
0 ignored issues
show
introduced by
$obj is of type SilverStripe\ORM\DataObject, thus it always evaluated to true.
Loading history...
315
                return $obj;
316
            }
317
        }
318
319
        $uniqueFields = $this->uniqueFields($class, $mappings);
320
        // creates a filter
321
        $filter = [];
322
        foreach ($uniqueFields as $dbField => $salsifyField) {
323
            $modifiedData = $data;
324
            $fieldMapping = $mappings[$dbField];
325
326
            $modifiedData = $this->handleModification($class, $dbField, $fieldMapping, $modifiedData);
327
328
            // adds unique fields to filter
329
            if (array_key_exists($salsifyField, $modifiedData)) {
330
                $filter[$dbField] = $modifiedData[$salsifyField];
331
            }
332
        }
333
334
        return DataObject::get($class)->filter($filter)->first();
335
    }
336
337
    /**
338
     * Gets a list of all the unique field keys
339
     *
340
     * @param string class
0 ignored issues
show
Bug introduced by
The type Dynamic\Salsify\Model\class was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
341
     * @param array $mappings
342
     * @return array
343
     */
344
    private function uniqueFields($class, $mappings)
345
    {
346
        // cached after first map
347
        if (array_key_exists($class, $this->currentUniqueFields) && !empty($this->currentUniqueFields[$class])) {
348
            return $this->currentUniqueFields[$class];
349
        }
350
351
        $uniqueFields = [];
352
        foreach ($this->getFieldMappings($mappings) as $dbField => $salsifyField) {
353
            if (!is_array($salsifyField)) {
354
                continue;
355
            }
356
357
            if (
358
                !array_key_exists('unique', $salsifyField) ||
359
                !array_key_exists('salsifyField', $salsifyField)
360
            ) {
361
                continue;
362
            }
363
364
            if ($salsifyField['unique'] !== true) {
365
                continue;
366
            }
367
368
            $uniqueFields[$dbField] = $salsifyField['salsifyField'];
369
        }
370
371
        $this->currentUniqueFields[$class] = $uniqueFields;
372
        return $uniqueFields;
373
    }
374
375
    /**
376
     * @param string $class
377
     * @param string $dbField
378
     * @param array $config
379
     * @param array $data
380
     * @return array
381
     */
382
    private function handleModification($class, $dbField, $config, $data)
383
    {
384
        if (!is_array($config)) {
0 ignored issues
show
introduced by
The condition is_array($config) is always true.
Loading history...
385
            return $data;
386
        }
387
388
        if (array_key_exists('modification', $config)) {
389
            $mod = $config['modification'];
390
            if ($this->hasMethod($mod)) {
391
                return $this->{$mod}($class, $dbField, $config, $data);
392
            }
393
            ImportTask::output("{$mod} is not a valid field modifier. skipping modification for field {$dbField}.");
394
        }
395
        return $data;
396
    }
397
398
    /**
399
     * @param string $class
400
     * @param string $dbField
401
     * @param array $config
402
     * @param array $data
403
     * @return boolean
404
     */
405
    private function handleShouldSkip($class, $dbField, $config, $data)
406
    {
407
        if (!is_array($config)) {
0 ignored issues
show
introduced by
The condition is_array($config) is always true.
Loading history...
408
            return false;
409
        }
410
411
        if (array_key_exists('shouldSkip', $config)) {
412
            $skipMethod = $config['shouldSkip'];
413
            if ($this->hasMethod($skipMethod)) {
414
                return $this->{$skipMethod}($class, $dbField, $config, $data);
415
            }
416
            ImportTask::output(
417
                "{$skipMethod} is not a valid skip test method. Skipping skip test for field {$dbField}."
418
            );
419
        }
420
        return false;
421
    }
422
423
    /**
424
     * @param string|array $field
425
     * @return string
426
     */
427
    public function getFieldType($field)
428
    {
429
        $fieldTypes = $this->config()->get('field_types');
430
        if (is_array($field) && array_key_exists('type', $field)) {
431
            if (in_array($field['type'], $fieldTypes)) {
432
                return $field['type'];
433
            }
434
        }
435
        // default to raw
436
        return 'Raw';
437
    }
438
439
    /**
440
     * @param int $type
441
     * @param string|DataObject $class
442
     * @param array $salsifyData
443
     * @param string $salsifyField
444
     * @param array $dbFieldConfig
445
     * @param string $dbField
446
     *
447
     * @return mixed
448
     */
449
    private function handleType($type, $class, $salsifyData, $salsifyField, $dbFieldConfig, $dbField)
450
    {
451
        if ($this->hasMethod("handle{$type}Type")) {
452
            return $this->{"handle{$type}Type"}($class, $salsifyData, $salsifyField, $dbFieldConfig, $dbField);
453
        }
454
        ImportTask::output("{$type} is not a valid type. skipping field {$dbField}.");
455
        return '';
456
    }
457
458
    /**
459
     * @param DataObject $object
460
     * @param string $dbField
461
     * @param mixed $value
462
     *
463
     * @throws \Exception
464
     */
465
    private function writeValue($object, $dbField, $value)
466
    {
467
        $isManyRelation = array_key_exists($dbField, $object->config()->get('has_many')) ||
468
            array_key_exists($dbField, $object->config()->get('many_many')) ||
469
            array_key_exists($dbField, $object->config()->get('belongs_many_many'));
470
471
        if (!$isManyRelation) {
472
            $object->$dbField = $value;
473
            return;
474
        }
475
476
        // write the object so relations can be written
477
        if (!$object->exists()) {
478
            $object->write();
479
        }
480
481
        // change to an array and filter out empty values
482
        if (!is_array($value)) {
483
            $value = [$value];
484
        }
485
        $value = array_filter($value);
486
487
        // get the ids
488
        $ids = [];
489
        foreach ($value as $v) {
490
            $ids[] = $v->ID;
491
        }
492
493
        /** @var DataList $relation */
494
        $relation = $object->{$dbField}();
495
        // remove all unrelated - removeAll had an odd side effect (relations only got added back half the time)
496
        $relation->removeMany(
497
            $relation->exclude([
498
                'ID' => $ids,
499
            ])->column('ID')
500
        );
501
502
        if (empty($value)) {
503
            return;
504
        }
505
506
        // only add ones that haven't been added
507
        $relationArray = $relation->column('ID');
508
        $toAdd = array_diff($ids, $relationArray);
509
        $relation->addMany($toAdd);
510
    }
511
512
    /**
513
     * @return bool
514
     */
515
    public function hasFile()
516
    {
517
        return $this->file !== null;
518
    }
519
}
520