custom/plugins/AcrisRrpCS/src/Components/RrpPriceService.php line 24

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Acris\Rrp\Components;
  3. use Acris\Rrp\Custom\AcrisRrpEntity;
  4. use Shopware\Core\Content\Rule\RuleCollection;
  5. use Shopware\Core\Framework\DataAbstractionLayer\EntityCollection;
  6. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  7. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  8. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  9. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  10. class RrpPriceService
  11. {
  12.     private EntityRepositoryInterface $rrpPriceRepository;
  13.     public function __construct(
  14.         EntityRepositoryInterface $rrpPriceRepository
  15.     ) {
  16.         $this->rrpPriceRepository $rrpPriceRepository;
  17.     }
  18.     public function getValidRrpRule(SalesChannelContext $context): ?AcrisRrpEntity
  19.     {
  20.         $criteria = new Criteria();
  21.         $criteria->addAssociation('rules');
  22.         $criteria->addFilter(new EqualsFilter('active'true));
  23.         $collection $this->rrpPriceRepository->search($criteria$context->getContext())->getEntities();
  24.         $this->filterByRules($collection$context);
  25.         if ($collection->count() === 0) {
  26.             return null;
  27.         }
  28.         $collection->sort(function (AcrisRrpEntity $aAcrisRrpEntity $b) {
  29.             $prioA $a->getPriority() ?? 0;
  30.             $prioB $b->getPriority() ?? 0;
  31.             return $prioA $prioB;
  32.         });
  33.         return $collection->first();
  34.     }
  35.     private function filterByRules(EntityCollection $collectionSalesChannelContext $salesChannelContext): void
  36.     {
  37.         foreach ($collection->getElements() as $entity) {
  38.             if ($this->rulesValid($entity->getRules(), $salesChannelContext) !== true) {
  39.                 $collection->remove($entity->getId());
  40.             }
  41.         }
  42.     }
  43.     private function rulesValid(?RuleCollection $ruleCollectionSalesChannelContext $salesChannelContext): bool
  44.     {
  45.         if (empty($ruleCollection) || $ruleCollection->count() === 0) {
  46.             return true;
  47.         }
  48.         $rules $salesChannelContext->getRuleIds();
  49.         foreach ($ruleCollection->getElements() as $rule) {
  50.             if (in_array($rule->getId(), $rules)) {
  51.                 return true;
  52.             }
  53.         }
  54.         return false;
  55.     }
  56. }