1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Plane\Shop package. |
5
|
|
|
* |
6
|
|
|
* (c) Dariusz Korsak <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Plane\Shop; |
13
|
|
|
|
14
|
|
|
use Money\Money; |
15
|
|
|
use Money\Currency; |
16
|
|
|
use InvalidArgumentException; |
17
|
|
|
use Money\Currencies\ISOCurrencies; |
18
|
|
|
use Money\Parser\DecimalMoneyParser; |
19
|
|
|
|
20
|
|
|
class Shipping implements ShippingInterface |
21
|
|
|
{ |
22
|
|
|
private $id; |
23
|
|
|
|
24
|
|
|
private $name; |
25
|
|
|
|
26
|
|
|
private $description; |
27
|
|
|
|
28
|
|
|
private $cost; |
29
|
|
|
|
30
|
|
|
private $requiredFields = [ |
31
|
|
|
'id', |
32
|
|
|
'name', |
33
|
|
|
'cost', |
34
|
|
|
]; |
35
|
|
|
|
36
|
3 |
View Code Duplication |
public function __construct(array $data) |
|
|
|
|
37
|
|
|
{ |
38
|
3 |
|
if (count(array_intersect_key(array_flip($this->requiredFields), $data)) !== count($this->requiredFields)) { |
39
|
1 |
|
throw new InvalidArgumentException( |
40
|
1 |
|
'Cannot create object, required array keys: '. implode(', ', $this->requiredFields) |
41
|
|
|
); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
// waiting for typed properties in PHP 7.4 |
45
|
2 |
|
foreach ($data as $property => $value) { |
46
|
2 |
|
$this->$property = $value; |
47
|
|
|
} |
48
|
2 |
|
} |
49
|
|
|
|
50
|
1 |
|
public function getId(): int |
51
|
|
|
{ |
52
|
1 |
|
return $this->id; |
53
|
|
|
} |
54
|
|
|
|
55
|
1 |
|
public function getName(): string |
56
|
|
|
{ |
57
|
1 |
|
return $this->name; |
58
|
|
|
} |
59
|
|
|
|
60
|
1 |
|
public function getDescription(): string |
61
|
|
|
{ |
62
|
1 |
|
return $this->description; |
63
|
|
|
} |
64
|
|
|
|
65
|
2 |
|
public function getCost(string $currency): Money |
66
|
|
|
{ |
67
|
2 |
|
$moneyParser = new DecimalMoneyParser(new ISOCurrencies()); |
68
|
|
|
|
69
|
2 |
|
return $moneyParser->parse((string) $this->cost, new Currency($currency)); |
70
|
|
|
} |
71
|
|
|
public function toArray(): array |
72
|
|
|
{ |
73
|
|
|
return [ |
74
|
|
|
'id' => $this->getId(), |
75
|
|
|
'name' => $this->getName(), |
76
|
|
|
'desc' => $this->getDescription(), |
77
|
|
|
]; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.