<?php declare(strict_types=1);
namespace NetzpEvents6\Components;
use Shopware\Core\Checkout\Cart\LineItem\LineItem;
use Shopware\Core\Checkout\Cart\Rule\CartRuleScope;
use Shopware\Core\Checkout\Cart\Rule\LineItemScope;
use Shopware\Core\Framework\Rule\Rule;
use Shopware\Core\Framework\Rule\RuleScope;
use Symfony\Component\Validator\Constraints\Type;
class HasEventsRule extends Rule
{
protected bool $hasEvents;
public function __construct()
{
parent::__construct();
$this->shouldHaveEvents = false;
}
public function getName(): string
{
return 'netzpEventsRule';
}
public function match(RuleScope $scope): bool
{
if ($scope instanceof LineItemScope) {
return $this->lineItemHasEvents($scope->getLineItem());
}
if ( ! $scope instanceof CartRuleScope) {
return false;
}
$hasEvents = false;
foreach($scope->getCart()->getLineItems() as $lineItem) {
if($this->lineItemHasEvents($lineItem)) {
$hasEvents = true;
break;
}
}
if ($this->shouldHaveEvents) {
return $hasEvents;
}
return ! $hasEvents;
}
private function lineItemHasEvents(LineItem $lineItem)
{
if(array_key_exists('netzp_event', $lineItem->getPayload())) {
return true;
}
return false;
}
public function getConstraints(): array
{
return [
'shouldHaveEvents' => [new Type('bool')]
];
}
}