Completed
Pull Request — master (#2)
by Tom
40:29
created

Carrier::getPackageWeightInKg()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 0
cts 4
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 2
crap 6
1
<?php
2
/**
3
 * Copyright © 2015 Magento. All rights reserved.
4
 * See COPYING.txt for license details.
5
 */
6
namespace Meanbee\MagentoRoyalmail\Model;
7
8
use Magento\Framework\App\Config\ScopeConfigInterface;
9
use Magento\Framework\DataObject;
10
use Magento\Shipping\Model\Carrier\AbstractCarrier;
11
use Magento\Shipping\Model\Carrier\CarrierInterface;
12
use Magento\Shipping\Model\Rate\ResultFactory;
13
use Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory;
14
use Magento\Quote\Model\Quote\Address\RateResult\Method;
15
use Magento\Quote\Model\Quote\Address\RateResult\MethodFactory;
16
use Magento\Quote\Model\Quote\Address\RateRequest;
17
use Meanbee\Royalmail\Carrier as LibCarrier;
18
use Psr\Log\LoggerInterface;
19
20
/**
21
 * Class Carrier Royal Mail shipping model
22
 */
23
class Carrier extends AbstractCarrier implements CarrierInterface
24
{
25
    /**
26
     * Carrier's code
27
     *
28
     * @var string
29
     */
30
    protected $_code = 'rm';
31
32
    /**
33
     * Whether this carrier has fixed rates calculation
34
     *
35
     * @var bool
36
     */
37
    protected $_isFixed = true;
38
39
    /**
40
     * @var ResultFactory
41
     */
42
    protected $rateResultFactory;
43
44
    /**
45
     * @var MethodFactory
46
     */
47
    protected $rateMethodFactory;
48
49
    /**
50
     * @var LibCarrier
51
     */
52
    protected $carrier;
53
54
    /**
55
     * @var Rounder
56
     */
57
    protected $rounder;
58
59
    /**
60
     * @param ScopeConfigInterface $scopeConfig
61
     * @param ErrorFactory $rateErrorFactory
62
     * @param LoggerInterface $logger
63
     * @param ResultFactory $rateResultFactory
64
     * @param MethodFactory $rateMethodFactory
65
     * @param Rounder $rounder
66
     * @param LibCarrier $carrier
67
     * @param array $data
68
     */
69
    public function __construct(
70
        ScopeConfigInterface $scopeConfig,
71
        ErrorFactory $rateErrorFactory,
72
        LoggerInterface $logger,
73
        ResultFactory $rateResultFactory,
74
        MethodFactory $rateMethodFactory,
75
        Rounder $rounder,
76
        LibCarrier $carrier,
77
        array $data = []
78
    ) {
79
        $this->rateResultFactory = $rateResultFactory;
80
        $this->rateMethodFactory = $rateMethodFactory;
81
        $this->rounder = $rounder;
82
        $this->carrier = $carrier;
83
84
        parent::__construct($scopeConfig, $rateErrorFactory, $logger, $data);
85
    }
86
87
    /**
88
     * Collect and get rates for storefront
89
     *
90
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
91
     * @param RateRequest $request
92
     * @return DataObject|bool|null
93
     * @api
94
     */
95
    public function collectRates(RateRequest $request)
96
    {
97
        /**
98
         * Make sure that Shipping method is enabled
99
         */
100
        if (!$this->isActive()) {
101
            return false;
102
        }
103
104
        $unit = $this->_scopeConfig->getValue(
105
            \Magento\Directory\Helper\Data::XML_PATH_WEIGHT_UNIT,
106
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
107
        );
108
109
        $weight = $this->getPackageWeightInKg($request->getPackageWeight(), $unit);
110
111
        $methods = $this->carrier->getRates(
112
            $request->getDestCountryId(),
113
            $request->getPackageValue(),
114
            $weight
115
        );
116
117
        $methods = $this->removeUnusedParcelSizes($methods, $weight);
118
119
        $result = $this->rateResultFactory->create();
120
121
        $allowedMethods = $this->getAllowedMethods();
122
123
        if (empty($allowedMethods)) {
124
            return $result;
125
        }
126
127
        /** @var \Meanbee\RoyalMail\Method $method */
128
        foreach ($methods as $method) {
129
            if (!array_key_exists($method->getCode(), $allowedMethods)) {
130
                continue;
131
            }
132
133
            /** @var Method $rate */
134
            $rate = $this->rateMethodFactory->create();
135
            $rate->setData('carrier', $this->getCarrierCode());
136
            $rate->setData('carrier_title', $this->getConfigData('title'));
137
            $rate->setData('method_title', $method->getName());
138
            $rate->setData('method', $method->getCode());
139
            $rate->setPrice(
140
                $this->rounder->round(
141
                    $this->getConfigData('rounding_rule'),
0 ignored issues
show
Bug introduced by
It seems like $this->getConfigData('rounding_rule') targeting Magento\Shipping\Model\C...arrier::getConfigData() can also be of type false or null; however, Meanbee\MagentoRoyalmail\Model\Rounder::round() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
142
                    $this->getFinalPriceWithHandlingFee($method->getPrice())
143
                )
144
            );
145
            $result->append($rate);
146
        }
147
148
        return $result;
149
    }
150
151
152
    /**
153
     * Gets the methods selected in the admin area of the extension
154
     * to ensure that not allowed methods can be removed in the collect
155
     * rates method
156
     *
157
     * @return array
158
     */
159
    public function getAllowedMethods()
160
    {
161
        $configMethods = explode(',', $this->getConfigData('allowed_methods'));
162
        $allMethods = $this->getMethods();
163
164
        return array_intersect_key($allMethods, array_flip($configMethods));
165
    }
166
    /**
167
     * Gets the clean method names from the royal mail library data
168
     * class. These names link directly to method names, but are used
169
     * to ensure that duplicates are not created as similar names
170
     * exists for multiple methods.
171
     *
172
     * @return array
173
     */
174
    public function getMethods()
175
    {
176
        return $this->carrier->getAllMethods();
177
    }
178
179
    /**
180
     * Get package weight in Kilograms converting from lbs if necessary.
181
     *
182
     * @param $weight
183
     * @param $unit
184
     * @return mixed
185
     */
186
    protected function getPackageWeightInKg($weight, $unit)
187
    {
188
        if ($unit == 'lbs') {
189
            $weight = $weight * 0.453592;
190
        }
191
192
        return $weight;
193
    }
194
195
    /**
196
     * Both small and medium sized parcels can serve up to 2KG.
197
     * Configuration option determines which size we show to customer.
198
     *
199
     * @param \Meanbee\RoyalMail\Method[] $methods
200
     * @param int $weight
201
     * @return \Meanbee\RoyalMail\Method[]
202
     */
203
    protected function removeUnusedParcelSizes($methods, $weight)
204
    {
205
        $parcelSize = $this->getConfigData('parcel_size');
206
        if ($weight <= 2 && $parcelSize) {
207
            foreach ($methods as $key => $method) {
208
                if ($method->getSize() && $method->getSize() != $parcelSize) {
209
                    unset($methods[$key]);
210
                }
211
            }
212
        }
213
214
        return $methods;
215
    }
216
}
217