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
Push — master ( 979e92...1cc351 )
by Bob Olde
9s
created

ShippingMethods::getCategoryDefinition()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 6
cts 6
cp 1
rs 9.6666
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 1
crap 1
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 2
    public function export(array $shippingMethods = [])
33
    {
34 2
        if (!count($shippingMethods)) {
35
            $shippingMethods = Craft::app()->commerce_shippingMethods->getAllShippingMethods();
36
        }
37
38 2
        Craft::log(Craft::t('Exporting Commerce Shipping Methods'));
39
40 2
        $shippingMethodDefinitions = [];
41
42 2
        foreach ($shippingMethods as $shippingMethod) {
43 2
            $shippingMethodDefinitions[$shippingMethod->handle] = $this->getShippingMethodDefinition($shippingMethod);
44 2
        }
45
46 2
        return $shippingMethodDefinitions;
47
    }
48
49
    /**
50
     * Get shipping methods definition.
51
     *
52
     * @param Commerce_ShippingMethodModel $shippingMethod
53
     *
54
     * @return array
55
     */
56 2
    private function getShippingMethodDefinition(Commerce_ShippingMethodModel $shippingMethod)
57
    {
58
        return [
59 2
            'name' => $shippingMethod->name,
60 2
            'enabled' => $shippingMethod->enabled,
61 2
            'rules' => $this->getRuleDefinitions($shippingMethod->getRules()),
62 2
        ];
63
    }
64
65
    /**
66
     * Get rule definitions.
67
     *
68
     * @param Commerce_ShippingRuleModel[] $rules
69
     *
70
     * @return array
71
     */
72 2
    private function getRuleDefinitions(array $rules)
73
    {
74 2
        $ruleDefinitions = [];
75
76 2
        foreach ($rules as $rule) {
77 2
            $ruleDefinitions[$rule->name] = $this->getRuleDefinition($rule);
78 2
        }
79
80 2
        return $ruleDefinitions;
81
    }
82
83
    /**
84
     * Get rule definition.
85
     *
86
     * @param Commerce_ShippingRuleModel $rule
87
     *
88
     * @return array
89
     */
90 2
    private function getRuleDefinition(Commerce_ShippingRuleModel $rule)
91
    {
92
        return [
93 2
            'name' => $rule->name,
94 2
            'description' => $rule->description,
95 2
            'shippingZone' => $rule->shippingZone ? $rule->shippingZone->name : null,
96 2
            'priority' => $rule->priority,
97 2
            'enabled' => $rule->enabled,
98 2
            'minQty' => $rule->minQty,
99 2
            'maxQty' => $rule->maxQty,
100 2
            'minTotal' => $rule->minTotal,
101 2
            'maxTotal' => $rule->maxTotal,
102 2
            'minWeight' => $rule->minWeight,
103 2
            'maxWeight' => $rule->maxWeight,
104 2
            'baseRate' => $rule->baseRate,
105 2
            'perItemRate' => $rule->perItemRate,
106 2
            'weightRate' => $rule->weightRate,
107 2
            'percentageRate' => $rule->percentageRate,
108 2
            'minRate' => $rule->minRate,
109 2
            'maxRate' => $rule->maxRate,
110 2
            'categories' => $this->getCategoryDefinitions($rule->getShippingRuleCategories()),
111 2
        ];
112
    }
113
114
    /**
115
     * Get category definitions.
116
     *
117
     * @param Commerce_ShippingRuleCategoryModel[] $categories
118
     *
119
     * @return array
120
     */
121 2
    private function getCategoryDefinitions(array $categories)
122
    {
123 2
        $categoryDefinitions = [];
124
125 2
        foreach ($categories as $category) {
126 2
            $categoryDefinitions[$category->getCategory()->handle] = $this->getCategoryDefinition($category);
127 2
        }
128
129 2
        return $categoryDefinitions;
130
    }
131
132
    /**
133
     * Get category definition.
134
     *
135
     * @param Commerce_ShippingRuleCategoryModel $category
136
     *
137
     * @return array
138
     */
139 2
    private function getCategoryDefinition(Commerce_ShippingRuleCategoryModel $category)
140
    {
141
        return [
142 2
            'condition' => $category->condition,
143 2
            'perItemRate' => $category->perItemRate,
144 2
            'weightRate' => $category->weightRate,
145 2
            'percentageRate' => $category->percentageRate,
146 2
        ];
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 4
    public function import(array $shippingMethodDefinitions, $force = false)
158
    {
159 4
        Craft::log(Craft::t('Importing Commerce Shipping Methods'));
160
161 4
        $this->resetCraftShippingMethodsServiceCache();
162 4
        $shippingMethods = [];
163 4
        foreach (Craft::app()->commerce_shippingMethods->getAllShippingMethods() as $shippingMethod) {
164
            $shippingMethods[$shippingMethod->handle] = $shippingMethod;
165 4
        }
166
167 4
        foreach ($shippingMethodDefinitions as $shippingMethodHandle => $shippingMethodDefinition) {
168 2
            $shippingMethod = array_key_exists($shippingMethodHandle, $shippingMethods)
169 2
                ? $shippingMethods[$shippingMethodHandle]
170 2
                : new Commerce_ShippingMethodModel();
171
172 2
            unset($shippingMethods[$shippingMethodHandle]);
173
174 2
            $this->populateShippingMethod($shippingMethod, $shippingMethodDefinition, $shippingMethodHandle);
175
176 2
            if (!Craft::app()->commerce_shippingMethods->saveShippingMethod($shippingMethod)) { // Save shippingmethod via craft
177 2
                $this->addErrors($shippingMethod->getAllErrors());
178
179 2
                continue;
180
            }
181
182
            $this->populateShippingMethodRules($shippingMethod, $shippingMethodDefinition['rules'], $force);
183 4
        }
184
185 4
        if ($force) {
186 2
            foreach ($shippingMethods as $shippingMethod) {
187
                Craft::app()->commerce_shippingMethods->delete($shippingMethod);
188 2
            }
189 2
        }
190
191 4
        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 2
    private function populateShippingMethod(Commerce_ShippingMethodModel $shippingMethod, array $shippingMethodDefinition, $shippingMethodHandle)
202
    {
203 2
        $shippingMethod->setAttributes([
204 2
            'handle' => $shippingMethodHandle,
205 2
            'name' => $shippingMethodDefinition['name'],
206 2
            'enabled' => $shippingMethodDefinition['enabled'],
207 2
        ]);
208 2
    }
209
210
    /**
211
     * Populate shipping method rules.
212
     *
213
     * @param Commerce_ShippingMethodModel $shippingMethod
214
     * @param array                        $ruleDefinitions
215
     * @param bool                         $force
216
     */
217
    private function populateShippingMethodRules(Commerce_ShippingMethodModel $shippingMethod, $ruleDefinitions, $force = false)
218
    {
219
        $rules = [];
220
        foreach ($shippingMethod->getRules() as $rule) {
221
            $rules[$rule->name] = $rule;
222
        }
223
224
        foreach ($ruleDefinitions as $ruleName => $ruleDef) {
225
            $rule = array_key_exists($ruleName, $rules) ? $rules[$ruleName] : new Commerce_ShippingRuleModel();
226
227
            unset($rules[$ruleName]);
228
229
            $shippingZone = Commerce_ShippingZoneRecord::model()->findByAttributes(['name' => $ruleDef['shippingZone']]);
230
231
            $rule->setAttributes([
232
                'name' => $ruleName,
233
                'description' => $ruleDef['description'],
234
                'shippingZoneId' => $shippingZone ? $shippingZone->id : null,
235
                'methodId' => $shippingMethod->id,
236
                'priority' => $ruleDef['priority'],
237
                'enabled' => $ruleDef['enabled'],
238
                'minQty' => $ruleDef['minQty'],
239
                'maxQty' => $ruleDef['maxQty'],
240
                'minTotal' => $ruleDef['minTotal'],
241
                'maxTotal' => $ruleDef['maxTotal'],
242
                'minWeight' => $ruleDef['minWeight'],
243
                'maxWeight' => $ruleDef['maxWeight'],
244
                'baseRate' => $ruleDef['baseRate'],
245
                'perItemRate' => $ruleDef['perItemRate'],
246
                'weightRate' => $ruleDef['weightRate'],
247
                'percentageRate' => $ruleDef['percentageRate'],
248
                'minRate' => $ruleDef['minRate'],
249
                'maxRate' => $ruleDef['maxRate'],
250
            ]);
251
252
            $this->populateShippingMethodRuleCategories($rule, $ruleDef['categories']);
253
254
            if (!Craft::app()->commerce_shippingRules->saveShippingRule($rule)) { // Save shippingrule via craft
255
                $this->addErrors($rule->getAllErrors());
256
257
                continue;
258
            }
259
        }
260
261
        if ($force) {
262
            foreach ($rules as $rule) {
263
                Craft::app()->commerce_shippingRules->deleteShippingRuleById($rule->id);
264
            }
265
        }
266
    }
267
268
    /**
269
     * Populate shipping method rule categories.
270
     *
271
     * @param Commerce_ShippingRuleModel $rule
272
     * @param $categoryDefinitions
273
     */
274
    private function populateShippingMethodRuleCategories(Commerce_ShippingRuleModel $rule, $categoryDefinitions)
275
    {
276
        $this->resetCraftShippingCategoriesServiceCache();
277
278
        $categories = [];
279
        foreach ($rule->getShippingRuleCategories() as $category) {
280
            $categories[$category->getCategory()->handle] = $category;
281
        }
282
283
        foreach ($categoryDefinitions as $categoryHandle => $categoryDef) {
284
            $category = array_key_exists($categoryHandle, $categories) ? $categories[$categoryHandle] : new Commerce_ShippingRuleCategoryModel();
285
286
            $category->setAttributes([
287
                'shippingCategoryId' => Craft::app()->commerce_shippingCategories->getShippingCategoryByHandle($categoryHandle)->id,
288
                'condition' => $categoryDef['condition'],
289
                'perItemRate' => $categoryDef['perItemRate'],
290
                'weightRate' => $categoryDef['weightRate'],
291
                'percentageRate' => $categoryDef['percentageRate'],
292
            ]);
293
294
            $categories[$category->shippingCategoryId] = $category;
295
        }
296
297
        $rule->setShippingRuleCategories($categories);
298
    }
299
300
    /**
301
     * Reset service cache using reflection.
302
     */
303 4
    private function resetCraftShippingMethodsServiceCache()
304
    {
305 4
        $obj = Craft::app()->commerce_shippingMethods;
306 4
        $refObject = new \ReflectionObject($obj);
307 4
        if ($refObject->hasProperty('_shippingMethods')) {
308
            $refProperty = $refObject->getProperty('_shippingMethods');
309
            $refProperty->setAccessible(true);
310
            $refProperty->setValue($obj, null);
311
        }
312 4
    }
313
314
    /**
315
     * Reset service cache using reflection.
316
     */
317
    private function resetCraftShippingCategoriesServiceCache()
318
    {
319
        $obj = Craft::app()->commerce_shippingCategories;
320
        $refObject = new \ReflectionObject($obj);
321
        if ($refObject->hasProperty('_fetchedAllShippingCategories')) {
322
            $refProperty = $refObject->getProperty('_fetchedAllShippingCategories');
323
            $refProperty->setAccessible(true);
324
            $refProperty->setValue($obj, false);
325
        }
326
        if ($refObject->hasProperty('_shippingCategoriesById')) {
327
            $refProperty = $refObject->getProperty('_shippingCategoriesById');
328
            $refProperty->setAccessible(true);
329
            $refProperty->setValue($obj, []);
330
        }
331
        if ($refObject->hasProperty('_shippingCategoriesByHandle')) {
332
            $refProperty = $refObject->getProperty('_shippingCategoriesByHandle');
333
            $refProperty->setAccessible(true);
334
            $refProperty->setValue($obj, []);
335
        }
336
    }
337
}
338