Completed
Push — master ( c54e22...e7a101 )
by Bart
03:24
created

ImportController::importFromDefinitions()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 0
cts 24
cp 0
rs 8.5706
c 0
b 0
f 0
cc 7
nc 7
nop 2
crap 56
1
<?php
2
3
namespace NerdsAndCompany\Schematic\Controllers;
4
5
use Craft;
6
use NerdsAndCompany\Schematic\Models\Data;
7
use NerdsAndCompany\Schematic\Schematic;
8
use craft\errors\WrongEditionException;
9
10
/**
11
 * Schematic Import Command.
12
 *
13
 * Sync Craft Setups.
14
 *
15
 * @author    Nerds & Company
16
 * @copyright Copyright (c) 2015-2019, Nerds & Company
17
 * @license   MIT
18
 *
19
 * @see      http://www.nerds.company
20
 */
21
class ImportController extends Base
22
{
23
    public $force = false;
24
25
    /**
26
     * {@inheritdoc}
27
     *
28
     * @return array
29
     */
30
    public function options($actionID): array
31
    {
32
        return array_merge(parent::options($actionID), ['force']);
33
    }
34
35
    /**
36
     * Imports the Craft datamodel.
37
     *
38
     * @return int
39
     * @throws \Exception
40
     */
41
    public function actionIndex(): int
42
    {
43
        $dataTypes = $this->getDataTypes();
44
        $definitions = [];
45
        $overrideData = Data::parseYamlFile($this->overrideFile);
46
47
        $this->disableLogging();
48
49
        try {
50
            // Import from single file.
51
            if ($this->getStorageType() === self::SINGLE_FILE) {
52
                $definitions = $this->importDefinitionsFromFile($overrideData);
53
                $this->importFromDefinitions($dataTypes, $definitions);
54
55
                Schematic::info('Loaded schema from '.$this->file);
56
            }
57
58
            // Import from multiple files.
59
            if ($this->getStorageType() === self::MULTIPLE_FILES) {
60
                $definitions = $this->importDefinitionsFromDirectory($overrideData);
61
                $this->importFromDefinitions($dataTypes, $definitions);
62
63
                Schematic::info('Loaded schema from '.$this->path);
64
            }
65
66
            return 0;
67
        } catch (\Exception $e) {
68
            Schematic::error($e->getMessage());
69
            return 1;
70
        }
71
    }
72
73
    /**
74
     * Import definitions from file
75
     *
76
     * @param array $overrideData The overridden data
77
     * @throws \Exception
78
     */
79
    private function importDefinitionsFromFile(array $overrideData): array
80
    {
81
        if (!file_exists($this->file)) {
82
            throw new \Exception('File not found: ' . $this->file);
83
        }
84
85
        // Load data from yam file and replace with override data;
86
        $definitions = Data::parseYamlFile($this->file);
87
        return array_replace_recursive($definitions, $overrideData);
88
    }
89
90
    /**
91
     * Import definitions from directory
92
     *
93
     * @param array $overrideData The overridden data
94
     * @throws \Exception
95
     */
96
    private function importDefinitionsFromDirectory(array $overrideData)
97
    {
98
        if (!file_exists($this->path)) {
99
            throw new \Exception('Directory not found: ' . $this->path);
100
        }
101
102
        // Grab all yaml files in the schema directory.
103
        $schemaFiles = preg_grep('~\.(yml)$~', scandir($this->path));
104
105
        // Read contents of each file and add it to the definitions.
106
        foreach ($schemaFiles as $fileName) {
107
            $schemaStructure = explode('.', $this->fromSafeFileName($fileName));
108
            $dataTypeHandle = $schemaStructure[0];
109
            $recordName = $schemaStructure[1];
110
111
            $definition = Data::parseYamlFile($this->path . $fileName);
112
113
            // Check if there is data in the override file for the current record.
114
            if (isset($overrideData[$dataTypeHandle][$recordName])) {
115
                $definition = array_replace_recursive($definition, $overrideData[$dataTypeHandle][$recordName]);
116
            }
117
118
            $definitions[$dataTypeHandle][$recordName] = $definition;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$definitions was never initialized. Although not strictly required by PHP, it is generally a good practice to add $definitions = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
119
        }
120
121
        return $definitions;
0 ignored issues
show
Bug introduced by
The variable $definitions does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
122
    }
123
124
    /**
125
     * Import from definitions.
126
     *
127
     * @param array $dataTypes   The data types to import
128
     * @param array $definitions The definitions to use
129
     * @throws \Exception
130
     */
131
    private function importFromDefinitions(array $dataTypes, array $definitions)
132
    {
133
        foreach ($dataTypes as $dataTypeHandle) {
134
            $dataType = $this->module->getDataType($dataTypeHandle);
135
            if (null == $dataType) {
136
                continue;
137
            }
138
139
            $mapper = $dataType->getMapperHandle();
140
            if (!$this->module->checkMapper($mapper)) {
141
                continue;
142
            }
143
144
            Schematic::info('Importing '.$dataTypeHandle);
145
            Schematic::$force = $this->force;
146
            if (array_key_exists($dataTypeHandle, $definitions) && is_array($definitions[$dataTypeHandle])) {
147
                $records = $dataType->getRecords();
148
                try {
149
                    $this->module->$mapper->import($definitions[$dataTypeHandle], $records);
150
                    $dataType->afterImport();
151
                } catch (WrongEditionException $e) {
152
                    Schematic::error('Craft Pro is required for datatype '.$dataTypeHandle);
153
                }
154
            }
155
        }
156
    }
157
}
158