<?php declare(strict_types=1);
namespace Acris\Rrp\Components;
use Acris\Rrp\Custom\AcrisRrpEntity;
use Shopware\Core\Content\Rule\RuleCollection;
use Shopware\Core\Framework\DataAbstractionLayer\EntityCollection;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
class RrpPriceService
{
private EntityRepositoryInterface $rrpPriceRepository;
public function __construct(
EntityRepositoryInterface $rrpPriceRepository
) {
$this->rrpPriceRepository = $rrpPriceRepository;
}
public function getValidRrpRule(SalesChannelContext $context): ?AcrisRrpEntity
{
$criteria = new Criteria();
$criteria->addAssociation('rules');
$criteria->addFilter(new EqualsFilter('active', true));
$collection = $this->rrpPriceRepository->search($criteria, $context->getContext())->getEntities();
$this->filterByRules($collection, $context);
if ($collection->count() === 0) {
return null;
}
$collection->sort(function (AcrisRrpEntity $a, AcrisRrpEntity $b) {
$prioA = $a->getPriority() ?? 0;
$prioB = $b->getPriority() ?? 0;
return $prioA < $prioB;
});
return $collection->first();
}
private function filterByRules(EntityCollection $collection, SalesChannelContext $salesChannelContext): void
{
foreach ($collection->getElements() as $entity) {
if ($this->rulesValid($entity->getRules(), $salesChannelContext) !== true) {
$collection->remove($entity->getId());
}
}
}
private function rulesValid(?RuleCollection $ruleCollection, SalesChannelContext $salesChannelContext): bool
{
if (empty($ruleCollection) || $ruleCollection->count() === 0) {
return true;
}
$rules = $salesChannelContext->getRuleIds();
foreach ($ruleCollection->getElements() as $rule) {
if (in_array($rule->getId(), $rules)) {
return true;
}
}
return false;
}
}