Completed
Pull Request — master (#64)
by Bart
04:29
created

Schematic::doImport()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 12
rs 9.2
ccs 11
cts 11
cp 1
cc 4
eloc 8
nc 4
nop 4
crap 4
1
<?php
2
3
namespace NerdsAndCompany\Schematic\Services;
4
5
use Craft\Craft;
6
use Craft\BaseApplicationComponent as BaseApplication;
7
use Craft\IOHelper;
8
use NerdsAndCompany\Schematic\Models\Data;
9
use NerdsAndCompany\Schematic\Models\Result;
10
11
/**
12
 * Schematic Service.
13
 *
14
 * Sync Craft Setups.
15
 *
16
 * @author    Nerds & Company
17
 * @copyright Copyright (c) 2015-2016, Nerds & Company
18
 * @license   MIT
19
 *
20
 * @link      http://www.nerds.company
21
 */
22
class Schematic extends BaseApplication
23
{
24
    const SCHEMATIC_METHOD_IMPORT = 'import';
25
    const SCHEMATIC_METHOD_EXPORT = 'export';
26
27
    /**
28
     * Returns data from import model or default.
29
     *
30
     * @param array  $data
31
     * @param string $handle
32
     * @param array  $default
33
     *
34
     * @return array
35
     */
36 1
    private function getPluginData(array $data, $handle, array $default = [])
37
    {
38 1
        return (array_key_exists($handle, $data) && !is_null($data[$handle])) ? $data[$handle] : $default;
39
    }
40
41
    /**
42
     * Import from Yaml file.
43
     *
44
     * @param string $file
45
     * @param string $override
46
     * @param bool   $force    if set to true items not included in import will be deleted
47
     *
48
     * @return Result
49
     */
50 1
    public function importFromYaml($file, $override = null, $force = false)
51
    {
52 1
        Craft::app()->config->maxPowerCaptain();
53 1
        Craft::app()->setComponent('userSession', $this);
54
55 1
        $yaml = IOHelper::getFileContents($file);
56 1
        $yaml_override = IOHelper::getFileContents($override);
57 1
        $dataModel = Data::fromYaml($yaml, $yaml_override);
58
59 1
        return $this->importDataModel($dataModel, $force);
60
    }
61
62
    /**
63
     * Export to Yaml file.
64
     *
65
     * @param string $file
66
     * @param bool   $autoCreate
67
     *
68
     * @return Result
69
     */
70 2
    public function exportToYaml($file, $autoCreate = true)
71
    {
72 2
        Craft::app()->config->maxPowerCaptain();
73 2
        Craft::app()->setComponent('userSession', $this);
74
75 2
        $result = new Result();
76 2
        $dataModel = $this->exportDataModel();
77 2
        $yaml = Data::toYaml($dataModel);
78
79 2
        if (!IOHelper::writeToFile($file, $yaml, $autoCreate)) { // Do not auto create
80 1
            $result->addError('errors', "Failed to write contents to \"$file\"");
81 1
        }
82
83 2
        return $result;
84
    }
85
86
    /**
87
     * Import data model.
88
     *
89
     * @param Data $model
90
     * @param bool $force if set to true items not in the import will be deleted
91
     *
92
     * @return Result
93
     */
94 3
    private function importDataModel(Data $model, $force)
95
    {
96
        // Import schema
97 1
        $localesImportResult = Craft::app()->schematic_locales->import($model->getAttribute('locales', $force));
98 1
        $pluginImportResult = Craft::app()->schematic_plugins->import($model->getAttribute('plugins', $force));
99 1
        $fieldImportResult = Craft::app()->schematic_fields->import($model->getAttribute('fields'), $force);
100 1
        $assetSourcesImportResult = Craft::app()->schematic_assetSources->import($model->getAttribute('assetSources'), $force);
101 1
        $globalSetsImportResult = Craft::app()->schematic_globalSets->import($model->getAttribute('globalSets'), $force);
102 1
        $sectionImportResult = Craft::app()->schematic_sections->import($model->getAttribute('sections'), $force);
103 1
        $categoryGroupImportResult = Craft::app()->schematic_categoryGroups->import($model->getAttribute('categoryGroups'), $force);
104 1
        $tagGroupImportResult = Craft::app()->schematic_tagGroups->import($model->getAttribute('tagGroups'), $force);
105 1
        $userGroupImportResult = Craft::app()->schematic_userGroups->import($model->getAttribute('userGroups'), $force);
106 1
        $userImportResult = Craft::app()->schematic_users->import($model->getAttribute('users'), true);
107 1
        $fieldImportResultFinal = Craft::app()->schematic_fields->import($model->getAttribute('fields'), $force);
108
109
        // Element index settings are supported from Craft 2.5
110 1
        if (version_compare(CRAFT_VERSION, '2.5', '>=')) {
111 1
            $elementIndexSettingsImportResult = Craft::app()->schematic_elementIndexSettings->import($model->getAttribute('elementIndexSettings'), $force);
112 1
        }
113
114
        // Verify results
115 1
        $result = new Result();
116 1
        $result->consume($localesImportResult);
117 1
        $result->consume($pluginImportResult);
118 1
        $result->consume($fieldImportResult);
119 1
        $result->consume($assetSourcesImportResult);
120 1
        $result->consume($globalSetsImportResult);
121 1
        $result->consume($sectionImportResult);
122 1
        $result->consume($categoryGroupImportResult);
123 1
        $result->consume($tagGroupImportResult);
124 1
        $result->consume($userGroupImportResult);
125 3
        $result->consume($userImportResult);
126 1
        $result->consume($fieldImportResultFinal);
127
128
        // Element index settings are supported from Craft 2.5
129 1
        if (version_compare(CRAFT_VERSION, '2.5', '>=')) {
130 1
            $result->consume($elementIndexSettingsImportResult);
0 ignored issues
show
Bug introduced by
The variable $elementIndexSettingsImportResult 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...
131 1
        }
132
133 1
        $services = Craft::app()->plugins->call('registerMigrationService');
134 1
        $this->doImport($result, $model->pluginData, $services, $force);
135
136 1
        return $result;
137
    }
138
139
    /**
140
     * Handles importing.
141
     *
142
     * @param Result       $result
143
     * @param array        $data
144
     * @param array|Base[] $services
145
     * @param bool         $force
146
     */
147 1
    private function doImport(Result $result, array $data, $services, $force)
148
    {
149 1
        foreach ($services as $handle => $service) {
150 1
            if (is_array($service)) {
151 1
                $this->doImport($result, $data, $service, $force);
152 1
            } elseif ($service instanceof Base) {
153 1
                $pluginData = $this->getPluginData($data, $handle);
154 1
                $hookResult = $service->import($pluginData, $force);
155 1
                $result->consume($hookResult);
156 1
            }
157 1
        }
158 1
    }
159
160
    /**
161
     * Export data model.
162
     *
163
     * @return array
164
     */
165 2
    private function exportDataModel()
166
    {
167 2
        $fieldGroups = Craft::app()->fields->getAllGroups();
168 2
        $sections = Craft::app()->sections->getAllSections();
169 2
        $globals = Craft::app()->globals->getAllSets();
170 2
        $userGroups = Craft::app()->userGroups->getAllGroups();
171 2
        $categoryGroups = Craft::app()->categories->getAllGroups();
172 2
        $tagGroups = Craft::app()->tags->getAllTagGroups();
173
174
        $export = [
175 2
            'locales' => Craft::app()->schematic_locales->export(),
176 2
            'assetSources' => Craft::app()->schematic_assetSources->export(),
177 2
            'fields' => Craft::app()->schematic_fields->export($fieldGroups),
178 2
            'plugins' => Craft::app()->schematic_plugins->export(),
179 2
            'sections' => Craft::app()->schematic_sections->export($sections),
180 2
            'globalSets' => Craft::app()->schematic_globalSets->export($globals),
181 2
            'userGroups' => Craft::app()->schematic_userGroups->export($userGroups),
182 2
            'users' => Craft::app()->schematic_users->export(),
183 2
            'categoryGroups' => Craft::app()->schematic_categoryGroups->export($categoryGroups),
184 2
            'tagGroups' => Craft::app()->schematic_tagGroups->export($tagGroups),
185 2
        ];
186
187
        // Element index settings are supported from Craft 2.5
188 2
        if (version_compare(CRAFT_VERSION, '2.5', '>=')) {
189 2
            $export['elementIndexSettings'] = Craft::app()->schematic_elementIndexSettings->export();
190 2
        }
191
192 2
        $export['pluginData'] = [];
193 2
        $services = Craft::app()->plugins->call('registerMigrationService');
194 2
        $this->doExport($services, $export['pluginData']);
195
196 2
        return $export;
197
    }
198
199
    /**
200
     * Handles exporting.
201
     *
202
     * @param array $services
203
     * @param array $data
204
     */
205 2
    private function doExport(array $services, array &$data)
206
    {
207 2
        foreach ($services as $handle => $service) {
208 2
            if (is_array($service)) {
209 2
                $this->doExport($service, $data);
210 2
            } elseif ($service instanceof Base) {
211 2
                if ($service instanceof Base) {
212 2
                    $data[$handle] = $service->export();
213 2
                }
214 2
            }
215 2
        }
216 2
    }
217
218
    /**
219
     * Always return the super user
220
     *
221
     * @return Craft\UserModel
222
     */
223
    public function getUser()
224
    {
225
        return Craft::app()->users->getUserById(1);
226
    }
227
228
    /**
229
     * Assume schematic can do anything.
230
     *
231
     * @return bool
232
     */
233
    public function checkPermission()
234
    {
235
        return true;
236
    }
237
}
238