Completed
Push — after-import-callback ( 808d90...eae689 )
by
unknown
15:02 queued 11:10
created

ModelMapper::import()   B

Complexity

Conditions 9
Paths 12

Size

Total Lines 39

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 37.783

Importance

Changes 0
Metric Value
dl 0
loc 39
ccs 7
cts 24
cp 0.2917
rs 7.7404
c 0
b 0
f 0
cc 9
nc 12
nop 4
crap 37.783
1
<?php
2
3
namespace NerdsAndCompany\Schematic\Mappers;
4
5
use Craft;
6
use craft\base\Model;
7
use craft\helpers\ArrayHelper;
8
use yii\base\Component as BaseComponent;
9
use NerdsAndCompany\Schematic\Schematic;
10
use NerdsAndCompany\Schematic\Interfaces\MapperInterface;
11
12
/**
13
 * Schematic Model Mapper.
14
 *
15
 * Sync Craft Setups.
16
 *
17
 * @author    Nerds & Company
18
 * @copyright Copyright (c) 2015-2018, Nerds & Company
19
 * @license   MIT
20
 *
21
 * @see      http://www.nerds.company
22
 */
23
class ModelMapper extends BaseComponent implements MapperInterface
24
{
25
    /**
26
     * {@inheritdoc}
27
     */
28 1
    public function export(array $records): array
29
    {
30 1
        $result = [];
31 1
        foreach ($records as $record) {
32
            $modelClass = get_class($record);
33
            $converter = Craft::$app->controller->module->getConverter($modelClass);
34
            if ($converter) {
35
                $result[$record->handle] = $converter->getRecordDefinition($record);
36
            }
37
        }
38
39 1
        return $result;
40
    }
41
42
    /**
43
     * Import records.
44
     *
45
     * @param array $definitions
46
     * @param Model $records           The existing records
47
     * @param array $defaultAttributes Default attributes to use for each record
48
     * @param bool  $persist           Whether to persist the parsed records
49
     *
50
     * @return array
51
     */
52 4
    public function import(array $definitions, array $records, array $defaultAttributes = [], $persist = true): array
53
    {
54 4
        $imported = [];
55 4
        $recordsByHandle = ArrayHelper::index($records, 'handle');
56 4
        foreach ($definitions as $handle => $definition) {
57
            $modelClass = $definition['class'];
58
            $converter = Craft::$app->controller->module->getConverter($modelClass);
59
            if ($converter) {
60
                $record = $this->findOrNewRecord($recordsByHandle, $definition, $handle);
61
62
                if ($converter->getRecordDefinition($record) === $definition) {
63
                    Schematic::info('- Skipping '.get_class($record).' '.$handle);
64
                } else {
65
                    $converter->setRecordAttributes($record, $definition, $defaultAttributes);
66
                    if ($persist) {
67
                        Schematic::info('- Saving '.get_class($record).' '.$handle);
68
                        if (!$converter->saveRecord($record, $definition)) {
69
                            Schematic::importError($record, $handle);
70
                        }
71
                    }
72
                }
73
74
                $imported[] = $record;
75
            }
76
            unset($recordsByHandle[$handle]);
77
        }
78
79 4
        if (Schematic::$force && $persist) {
80
            // Delete records not in definitions
81 2
            foreach ($recordsByHandle as $handle => $record) {
82
                $modelClass = get_class($record);
83
                Schematic::info('- Deleting '.get_class($record).' '.$handle);
84
                $converter = Craft::$app->controller->module->getConverter($modelClass);
85
                $converter->deleteRecord($record);
86
            }
87
        }
88
89 4
        return $imported;
90
    }
91
92
    /**
93
     * Find record from records by handle or new record.
94
     *
95
     * @param Model[] $recordsByHandle
96
     * @param array   $definition
97
     * @param string  $handle
98
     *
99
     * @return Model
100
     */
101
    private function findOrNewRecord(array $recordsByHandle, array $definition, string $handle): Model
102
    {
103
        $record = new $definition['class']();
104
        if (array_key_exists($handle, $recordsByHandle)) {
105
            $existing = $recordsByHandle[$handle];
106
            if (get_class($record) == get_class($existing)) {
107
                $record = $existing;
108
            } else {
109
                $record->id = $existing->id;
110
                $record->setAttributes($existing->getAttributes());
111
            }
112
        }
113
114
        return $record;
115
    }
116
}
117