Passed
Push — master ( fea822...a43bd7 )
by Christian
14:56 queued 04:20
created

TaxRuleCollection::get()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 9
ccs 4
cts 4
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace Shopware\Core\Checkout\Cart\Tax\Struct;
4
5
use Shopware\Core\Framework\Struct\Collection;
6
7
/**
8
 * @method TaxRule[]    getIterator()
9 113
 * @method TaxRule[]    getElements()
10
 * @method TaxRule|null first()
11 113
 * @method TaxRule|null last()
12 113
 */
13
class TaxRuleCollection extends Collection
14 1
{
15
    /**
16 1
     * @param TaxRule $taxRule
17 1
     */
18
    public function add($taxRule): void
19 65
    {
20
        $this->set($this->getKey($taxRule), $taxRule);
21 65
    }
22
23
    /**
24 2
     * @param string|int $key
25
     * @param TaxRule    $taxRule
26 2
     */
27
    public function set($key, $taxRule): void
28 2
    {
29 1
        parent::set($this->getKey($taxRule), $taxRule);
30
    }
31
32 1
    public function removeElement(TaxRule $taxRule): void
33
    {
34
        $this->remove($this->getKey($taxRule));
35 88
    }
36
37 88
    public function exists(TaxRule $taxRule): bool
38
    {
39 88
        return $this->has($this->getKey($taxRule));
40
    }
41 65
42 65
    public function get($taxRate): ?TaxRule
43
    {
44 88
        $key = (string) $taxRate;
45
46
        if ($this->has($key)) {
47 88
            return $this->elements[$key];
48
        }
49
50 113
        return null;
51
    }
52 113
53
    public function merge(self $rules): self
54
    {
55 113
        $new = new self($this->elements);
56
57 113
        $rules->map(
58
            function (TaxRule $rule) use ($new): void {
59
                if (!$new->exists($rule)) {
60
                    $new->add($rule);
61
                }
62
            }
63
        );
64
65
        return $new;
66
    }
67
68
    public function highestRate(): ?TaxRule
69
    {
70
        return $this->reduce(function ($result, $item) {
71
            return $result === null || $item->getTaxRate() > $result->getTaxRate() ? $item : $result;
72
        });
73
    }
74
75
    public function getApiAlias(): string
76
    {
77
        return 'cart_tax_rule_collection';
78
    }
79
80
    protected function getExpectedClass(): ?string
81
    {
82
        return TaxRule::class;
83
    }
84
85
    protected function getKey(TaxRule $element): string
86
    {
87
        return (string) $element->getTaxRate();
88
    }
89
}
90