/
LineItemDimensionWeightRule.php
84 lines (68 loc) · 2.38 KB
/
LineItemDimensionWeightRule.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php declare(strict_types=1);
namespace Shopware\Core\Checkout\Cart\Rule;
use Shopware\Core\Checkout\Cart\Delivery\Struct\DeliveryInformation;
use Shopware\Core\Checkout\Cart\LineItem\LineItem;
use Shopware\Core\Framework\Log\Package;
use Shopware\Core\Framework\Rule\Exception\UnsupportedOperatorException;
use Shopware\Core\Framework\Rule\Rule;
use Shopware\Core\Framework\Rule\RuleComparison;
use Shopware\Core\Framework\Rule\RuleConfig;
use Shopware\Core\Framework\Rule\RuleConstraints;
use Shopware\Core\Framework\Rule\RuleScope;
#[Package('services-settings')]
class LineItemDimensionWeightRule extends Rule
{
final public const RULE_NAME = 'cartLineItemDimensionWeight';
/**
* @internal
*/
public function __construct(
protected string $operator = self::OPERATOR_EQ,
protected ?float $amount = null
) {
parent::__construct();
}
public function match(RuleScope $scope): bool
{
if ($scope instanceof LineItemScope) {
return $this->matchWeightDimension($scope->getLineItem());
}
if (!$scope instanceof CartRuleScope) {
return false;
}
foreach ($scope->getCart()->getLineItems()->filterGoodsFlat() as $lineItem) {
if ($this->matchWeightDimension($lineItem)) {
return true;
}
}
return false;
}
public function getConstraints(): array
{
$constraints = [
'operator' => RuleConstraints::numericOperators(),
];
if ($this->operator === self::OPERATOR_EMPTY) {
return $constraints;
}
$constraints['amount'] = RuleConstraints::float();
return $constraints;
}
public function getConfig(): RuleConfig
{
return (new RuleConfig())
->operatorSet(RuleConfig::OPERATOR_SET_NUMBER, true)
->numberField('amount', ['unit' => RuleConfig::UNIT_WEIGHT]);
}
/**
* @throws UnsupportedOperatorException
*/
private function matchWeightDimension(LineItem $lineItem): bool
{
$deliveryInformation = $lineItem->getDeliveryInformation();
if (!$deliveryInformation instanceof DeliveryInformation) {
return RuleComparison::isNegativeOperator($this->operator);
}
return RuleComparison::numeric($deliveryInformation->getWeight(), $this->amount, $this->operator);
}
}