GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#2)
by Bob Olde
04:50
created

ShippingMethods::import()   C

Complexity

Conditions 7
Paths 20

Size

Total Lines 36
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 36
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 20
nc 20
nop 2
1
<?php
2
3
namespace NerdsAndCompany\Schematic\Commerce\Services;
4
5
use Craft\Craft;
6
use Craft\Commerce_ShippingMethodModel;
7
use Craft\Commerce_ShippingRuleModel;
8
use Craft\Commerce_ShippingRuleCategoryModel;
9
use Craft\Commerce_ShippingZoneRecord;
10
use NerdsAndCompany\Schematic\Services\Base;
11
12
/**
13
 * Schematic Commerce Shipping Methods Service.
14
 *
15
 * Sync Craft Setups.
16
 *
17
 * @author    Nerds & Company
18
 * @copyright Copyright (c) 2015-2017, Nerds & Company
19
 * @license   MIT
20
 *
21
 * @see      http://www.nerds.company
22
 */
23
class ShippingMethods extends Base
24
{
25
    /**
26
     * Export shippingMethods.
27
     *
28
     * @param ShippingMethodModel[] $shippingMethods
29
     *
30
     * @return array
31
     */
32
    public function export(array $shippingMethods = [])
33
    {
34
        if (!count($shippingMethods)) {
35
            $shippingMethods = Craft::app()->commerce_shippingMethods->getAllShippingMethods();
36
        }
37
38
        Craft::log(Craft::t('Exporting Commerce Shipping Methods'));
39
40
        $shippingMethodDefinitions = [];
41
42
        foreach ($shippingMethods as $shippingMethod) {
43
            $shippingMethodDefinitions[$shippingMethod->handle] = $this->getShippingMethodDefinition($shippingMethod);
44
        }
45
46
        return $shippingMethodDefinitions;
47
    }
48
49
    /**
50
     * Get shipping methods definition.
51
     *
52
     * @param Commerce_ShippingMethodModel $shippingMethod
53
     *
54
     * @return array
55
     */
56
    private function getShippingMethodDefinition(Commerce_ShippingMethodModel $shippingMethod)
57
    {
58
        return [
59
            'name' => $shippingMethod->name,
60
            'enabled' => $shippingMethod->enabled,
61
            'rules' => $this->getRuleDefinitions($shippingMethod->getRules()),
62
        ];
63
    }
64
65
    /**
66
     * Get rule definitions.
67
     *
68
     * @param Commerce_ShippingRuleModel[] $rules
69
     *
70
     * @return array
71
     */
72
    private function getRuleDefinitions(array $rules)
73
    {
74
        $ruleDefinitions = [];
75
76
        foreach ($rules as $rule) {
77
            $ruleDefinitions[$rule->name] = $this->getRuleDefinition($rule);
78
        }
79
80
        return $ruleDefinitions;
81
    }
82
83
    /**
84
     * Get rule definition.
85
     *
86
     * @param Commerce_ShippingRuleModel $rule
87
     *
88
     * @return array
89
     */
90
    private function getRuleDefinition(Commerce_ShippingRuleModel $rule)
91
    {
92
        return [
93
            'name' => $rule->name,
94
            'description' => $rule->description,
95
            'shippingZone' => $rule->shippingZone ? $rule->shippingZone->name : null,
96
            'priority' => $rule->priority,
97
            'enabled' => $rule->enabled,
98
            'minQty' => $rule->minQty,
99
            'maxQty' => $rule->maxQty,
100
            'minTotal' => $rule->minTotal,
101
            'maxTotal' => $rule->maxTotal,
102
            'minWeight' => $rule->minWeight,
103
            'maxWeight' => $rule->maxWeight,
104
            'baseRate' => $rule->baseRate,
105
            'perItemRate' => $rule->perItemRate,
106
            'weightRate' => $rule->weightRate,
107
            'percentageRate' => $rule->percentageRate,
108
            'minRate' => $rule->minRate,
109
            'maxRate' => $rule->maxRate,
110
            'categories' => $this->getCategoryDefinitions($rule->getShippingRuleCategories()),
111
        ];
112
    }
113
114
    /**
115
     * Get category definitions.
116
     *
117
     * @param Commerce_ShippingRuleCategoryModel[] $categories
118
     *
119
     * @return array
120
     */
121
    private function getCategoryDefinitions(array $categories)
122
    {
123
        $categoryDefinitions = [];
124
125
        foreach ($categories as $category) {
126
            $categoryDefinitions[$category->getCategory()->handle] = $this->getCategoryDefinition($category);
127
        }
128
129
        return $categoryDefinitions;
130
    }
131
132
    /**
133
     * Get category definition.
134
     *
135
     * @param Commerce_ShippingRuleCategoryModel $category
136
     *
137
     * @return array
138
     */
139
    private function getCategoryDefinition(Commerce_ShippingRuleCategoryModel $category)
140
    {
141
        return [
142
            'condition' => $category->condition,
143
            'perItemRate' => $category->perItemRate,
144
            'weightRate' => $category->weightRate,
145
            'percentageRate' => $category->percentageRate,
146
        ];
147
    }
148
149
    /**
150
     * Attempt to import shipping methods.
151
     *
152
     * @param array $shippingMethodDefinitions
153
     * @param bool  $force                     If set to true shipping methods not included in the import will be deleted
154
     *
155
     * @return Result
156
     */
157
    public function import(array $shippingMethodDefinitions, $force = false)
158
    {
159
        Craft::log(Craft::t('Importing Commerce Shipping Methods'));
160
161
        $this->resetCraftShippingMethodsServiceCache();
162
        $shippingMethods = array();
163
        foreach (Craft::app()->commerce_shippingMethods->getAllShippingMethods() as $shippingMethod) {
164
            $shippingMethods[$shippingMethod->handle] = $shippingMethod;
165
        }
166
167
        foreach ($shippingMethodDefinitions as $shippingMethodHandle => $shippingMethodDefinition) {
168
            $shippingMethod = array_key_exists($shippingMethodHandle, $shippingMethods)
169
                ? $shippingMethods[$shippingMethodHandle]
170
                : new Commerce_ShippingMethodModel();
171
172
            unset($shippingMethods[$shippingMethodHandle]);
173
174
            $this->populateShippingMethod($shippingMethod, $shippingMethodDefinition, $shippingMethodHandle);
175
176
            if (!Craft::app()->commerce_shippingMethods->saveShippingMethod($shippingMethod)) { // Save shippingmethod via craft
177
                $this->addErrors($shippingMethod->getAllErrors());
178
179
                continue;
180
            }
181
182
            $this->populateShippingMethodRules($shippingMethod, $shippingMethodDefinition['rules']);
183
        }
184
185
        if ($force) {
186
            foreach ($shippingMethods as $shippingMethod) {
187
                Craft::app()->commerce_shippingMethods->deleteShippingMethodById($shippingMethod->id);
188
            }
189
        }
190
191
        return $this->getResultModel();
192
    }
193
194
    /**
195
     * Populate shippingmethod.
196
     *
197
     * @param Commerce_ShippingMethodModel $shippingMethod
198
     * @param array                        $shippingMethodDefinition
199
     * @param string                       $shippingMethodHandle
200
     */
201
    private function populateShippingMethod(Commerce_ShippingMethodModel $shippingMethod, array $shippingMethodDefinition, $shippingMethodHandle)
202
    {
203
        $shippingMethod->setAttributes([
204
            'handle' => $shippingMethodHandle,
205
            'name' => $shippingMethodDefinition['name'],
206
            'enabled' => $shippingMethodDefinition['enabled'],
207
        ]);
208
    }
209
210
    /**
211
     * Populate shipping method rules.
212
     *
213
     * @param Commerce_ShippingMethodModel $shippingMethod
214
     * @param $ruleDefinitions
215
     */
216
    private function populateShippingMethodRules(Commerce_ShippingMethodModel $shippingMethod, $ruleDefinitions)
217
    {
218
        $rules = array();
219
        foreach ($shippingMethod->getRules() as $rule) {
220
            $rules[$rule->name] = $rule;
221
        }
222
223
        foreach ($ruleDefinitions as $ruleName => $ruleDef) {
224
            $rule = array_key_exists($ruleName, $rules) ? $rules[$ruleName] : new Commerce_ShippingRuleModel();
225
226
            $shippingZone = Commerce_ShippingZoneRecord::model()->findByAttributes(array('name' => $ruleDef['shippingZone']));
227
228
            $rule->setAttributes([
229
                'name' => $ruleName,
230
                'description' => $ruleDef['description'],
231
                'shippingZoneId' => $shippingZone ? $shippingZone->id : null,
232
                'methodId' => $shippingMethod->id,
233
                'priority' => $ruleDef['priority'],
234
                'enabled' => $ruleDef['enabled'],
235
                'minQty' => $ruleDef['minQty'],
236
                'maxQty' => $ruleDef['maxQty'],
237
                'minTotal' => $ruleDef['minTotal'],
238
                'maxTotal' => $ruleDef['maxTotal'],
239
                'minWeight' => $ruleDef['minWeight'],
240
                'maxWeight' => $ruleDef['maxWeight'],
241
                'baseRate' => $ruleDef['baseRate'],
242
                'perItemRate' => $ruleDef['perItemRate'],
243
                'weightRate' => $ruleDef['weightRate'],
244
                'percentageRate' => $ruleDef['percentageRate'],
245
                'minRate' => $ruleDef['minRate'],
246
                'maxRate' => $ruleDef['maxRate'],
247
            ]);
248
249
            $this->populateShippingMethodRuleCategories($rule, $ruleDef['categories']);
250
251
            if (!Craft::app()->commerce_shippingRules->saveShippingRule($rule)) { // Save shippingrule via craft
252
                $this->addErrors($rule->getAllErrors());
253
254
                continue;
255
            }
256
        }
257
    }
258
259
    /**
260
     * Populate shipping method rule categories.
261
     *
262
     * @param Commerce_ShippingRuleModel $rule
263
     * @param $categoryDefinitions
264
     */
265
    private function populateShippingMethodRuleCategories(Commerce_ShippingRuleModel $rule, $categoryDefinitions)
266
    {
267
        $categories = array();
268
        foreach ($rule->getShippingRuleCategories() as $category) {
269
            $categories[$category->getCategory()->handle] = $category;
270
        }
271
272
        foreach ($categoryDefinitions as $categoryHandle => $categoryDef) {
273
            $category = array_key_exists($categoryHandle, $categories) ? $categories[$categoryHandle] : new Commerce_ShippingRuleCategoryModel();
274
275
            $category->setAttributes([
276
                'shippingCategoryId' => Craft::app()->commerce_shippingCategories->getShippingCategoryByHandle($categoryHandle)->id,
277
                'condition' => $categoryDef['condition'],
278
                'perItemRate' => $categoryDef['perItemRate'],
279
                'weightRate' => $categoryDef['weightRate'],
280
                'percentageRate' => $categoryDef['percentageRate'],
281
            ]);
282
283
            $categories[$category->shippingCategoryId] = $category;
284
        }
285
286
        $rule->setShippingRuleCategories($categories);
287
    }
288
289
    /**
290
     * Reset service cache using reflection.
291
     */
292
    private function resetCraftShippingMethodsServiceCache()
293
    {
294
        $obj = Craft::app()->commerce_shippingMethods;
295
        $refObject = new \ReflectionObject($obj);
296
        if ($refObject->hasProperty('_shippingMethods')) {
297
            $refProperty = $refObject->getProperty('_shippingMethods');
298
            $refProperty->setAccessible(true);
299
            $refProperty->setValue($obj, null);
300
        }
301
    }
302
}
303