vendor/shopware/core/Checkout/Promotion/Validator/PromotionValidator.php line 72

  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\Checkout\Promotion\Validator;
  3. use Doctrine\DBAL\ArrayParameterType;
  4. use Doctrine\DBAL\Connection;
  5. use Doctrine\DBAL\Exception;
  6. use Shopware\Core\Checkout\Promotion\Aggregate\PromotionDiscount\PromotionDiscountDefinition;
  7. use Shopware\Core\Checkout\Promotion\Aggregate\PromotionDiscount\PromotionDiscountEntity;
  8. use Shopware\Core\Checkout\Promotion\PromotionDefinition;
  9. use Shopware\Core\Framework\Api\Exception\ResourceNotFoundException;
  10. use Shopware\Core\Framework\DataAbstractionLayer\Write\Command\InsertCommand;
  11. use Shopware\Core\Framework\DataAbstractionLayer\Write\Command\UpdateCommand;
  12. use Shopware\Core\Framework\DataAbstractionLayer\Write\Command\WriteCommand;
  13. use Shopware\Core\Framework\DataAbstractionLayer\Write\Validation\PreWriteValidationEvent;
  14. use Shopware\Core\Framework\Log\Package;
  15. use Shopware\Core\Framework\Validation\WriteConstraintViolationException;
  16. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  17. use Symfony\Component\Validator\ConstraintViolation;
  18. use Symfony\Component\Validator\ConstraintViolationInterface;
  19. use Symfony\Component\Validator\ConstraintViolationList;
  20. /**
  21.  * @internal
  22.  */
  23. #[Package('checkout')]
  24. class PromotionValidator implements EventSubscriberInterface
  25. {
  26.     /**
  27.      * this is the min value for all types
  28.      * (absolute, percentage, ...)
  29.      */
  30.     private const DISCOUNT_MIN_VALUE 0.00;
  31.     /**
  32.      * this is used for the maximum allowed
  33.      * percentage discount.
  34.      */
  35.     private const DISCOUNT_PERCENTAGE_MAX_VALUE 100.0;
  36.     /**
  37.      * @var list<array<string, mixed>>
  38.      */
  39.     private array $databasePromotions;
  40.     /**
  41.      * @var list<array<string, mixed>>
  42.      */
  43.     private array $databaseDiscounts;
  44.     /**
  45.      * @internal
  46.      */
  47.     public function __construct(private readonly Connection $connection)
  48.     {
  49.     }
  50.     public static function getSubscribedEvents(): array
  51.     {
  52.         return [
  53.             PreWriteValidationEvent::class => 'preValidate',
  54.         ];
  55.     }
  56.     /**
  57.      * This function validates our incoming delta-values for promotions
  58.      * and its aggregation. It does only check for business relevant rules and logic.
  59.      * All primitive "required" constraints are done inside the definition of the entity.
  60.      *
  61.      * @throws WriteConstraintViolationException
  62.      */
  63.     public function preValidate(PreWriteValidationEvent $event): void
  64.     {
  65.         $this->collect($event->getCommands());
  66.         $violationList = new ConstraintViolationList();
  67.         $writeCommands $event->getCommands();
  68.         foreach ($writeCommands as $index => $command) {
  69.             if (!$command instanceof InsertCommand && !$command instanceof UpdateCommand) {
  70.                 continue;
  71.             }
  72.             switch ($command->getDefinition()::class) {
  73.                 case PromotionDefinition::class:
  74.                     /** @var string $promotionId */
  75.                     $promotionId $command->getPrimaryKey()['id'];
  76.                     try {
  77.                         $promotion $this->getPromotionById($promotionId);
  78.                     } catch (ResourceNotFoundException) {
  79.                         $promotion = [];
  80.                     }
  81.                     $this->validatePromotion(
  82.                         $promotion,
  83.                         $command->getPayload(),
  84.                         $violationList,
  85.                         $index
  86.                     );
  87.                     break;
  88.                 case PromotionDiscountDefinition::class:
  89.                     /** @var string $discountId */
  90.                     $discountId $command->getPrimaryKey()['id'];
  91.                     try {
  92.                         $discount $this->getDiscountById($discountId);
  93.                     } catch (ResourceNotFoundException) {
  94.                         $discount = [];
  95.                     }
  96.                     $this->validateDiscount(
  97.                         $discount,
  98.                         $command->getPayload(),
  99.                         $violationList,
  100.                         $index
  101.                     );
  102.                     break;
  103.             }
  104.         }
  105.         if ($violationList->count() > 0) {
  106.             $event->getExceptions()->add(new WriteConstraintViolationException($violationList));
  107.         }
  108.     }
  109.     /**
  110.      * This function collects all database data that might be
  111.      * required for any of the received entities and values.
  112.      *
  113.      * @param list<WriteCommand> $writeCommands
  114.      *
  115.      * @throws ResourceNotFoundException
  116.      * @throws Exception
  117.      */
  118.     private function collect(array $writeCommands): void
  119.     {
  120.         $promotionIds = [];
  121.         $discountIds = [];
  122.         foreach ($writeCommands as $command) {
  123.             if (!$command instanceof InsertCommand && !$command instanceof UpdateCommand) {
  124.                 continue;
  125.             }
  126.             switch ($command->getDefinition()::class) {
  127.                 case PromotionDefinition::class:
  128.                     $promotionIds[] = $command->getPrimaryKey()['id'];
  129.                     break;
  130.                 case PromotionDiscountDefinition::class:
  131.                     $discountIds[] = $command->getPrimaryKey()['id'];
  132.                     break;
  133.             }
  134.         }
  135.         // why do we have inline sql queries in here?
  136.         // because we want to avoid any other private functions that accidentally access
  137.         // the database. all private getters should only access the local in-memory list
  138.         // to avoid additional database queries.
  139.         $this->databasePromotions = [];
  140.         if (!empty($promotionIds)) {
  141.             $promotionQuery $this->connection->executeQuery(
  142.                 'SELECT * FROM `promotion` WHERE `id` IN (:ids)',
  143.                 ['ids' => $promotionIds],
  144.                 ['ids' => ArrayParameterType::STRING]
  145.             );
  146.             $this->databasePromotions $promotionQuery->fetchAllAssociative();
  147.         }
  148.         $this->databaseDiscounts = [];
  149.         if (!empty($discountIds)) {
  150.             $discountQuery $this->connection->executeQuery(
  151.                 'SELECT * FROM `promotion_discount` WHERE `id` IN (:ids)',
  152.                 ['ids' => $discountIds],
  153.                 ['ids' => ArrayParameterType::STRING]
  154.             );
  155.             $this->databaseDiscounts $discountQuery->fetchAllAssociative();
  156.         }
  157.     }
  158.     /**
  159.      * Validates the provided Promotion data and adds
  160.      * violations to the provided list of violations, if found.
  161.      *
  162.      * @param array<string, mixed>    $promotion     the current promotion from the database as array type
  163.      * @param array<string, mixed>    $payload       the incoming delta-data
  164.      * @param ConstraintViolationList $violationList the list of violations that needs to be filled
  165.      * @param int                     $index         the index of this promotion in the command queue
  166.      *
  167.      * @throws \Exception
  168.      */
  169.     private function validatePromotion(array $promotion, array $payloadConstraintViolationList $violationListint $index): void
  170.     {
  171.         /** @var string|null $validFrom */
  172.         $validFrom $this->getValue($payload'valid_from'$promotion);
  173.         /** @var string|null $validUntil */
  174.         $validUntil $this->getValue($payload'valid_until'$promotion);
  175.         /** @var bool $useCodes */
  176.         $useCodes $this->getValue($payload'use_codes'$promotion);
  177.         /** @var bool $useCodesIndividual */
  178.         $useCodesIndividual $this->getValue($payload'use_individual_codes'$promotion);
  179.         /** @var string|null $pattern */
  180.         $pattern $this->getValue($payload'individual_code_pattern'$promotion);
  181.         /** @var string|null $promotionId */
  182.         $promotionId $this->getValue($payload'id'$promotion);
  183.         /** @var string|null $code */
  184.         $code $this->getValue($payload'code'$promotion);
  185.         if ($code === null) {
  186.             $code '';
  187.         }
  188.         if ($pattern === null) {
  189.             $pattern '';
  190.         }
  191.         $trimmedCode trim($code);
  192.         // if we have both a date from and until, make sure that
  193.         // the dateUntil is always in the future.
  194.         if ($validFrom !== null && $validUntil !== null) {
  195.             // now convert into real date times
  196.             // and start comparing them
  197.             $dateFrom = new \DateTime($validFrom);
  198.             $dateUntil = new \DateTime($validUntil);
  199.             if ($dateUntil $dateFrom) {
  200.                 $violationList->add($this->buildViolation(
  201.                     'Expiration Date of Promotion must be after Start of Promotion',
  202.                     $payload['valid_until'],
  203.                     'validUntil',
  204.                     'PROMOTION_VALID_UNTIL_VIOLATION',
  205.                     $index
  206.                 ));
  207.             }
  208.         }
  209.         // check if we use global codes
  210.         if ($useCodes && !$useCodesIndividual) {
  211.             // make sure the code is not empty
  212.             if ($trimmedCode === '') {
  213.                 $violationList->add($this->buildViolation(
  214.                     'Please provide a valid code',
  215.                     $code,
  216.                     'code',
  217.                     'PROMOTION_EMPTY_CODE_VIOLATION',
  218.                     $index
  219.                 ));
  220.             }
  221.             // if our code length is greater than the trimmed one,
  222.             // this means we have leading or trailing whitespaces
  223.             if (mb_strlen($code) > mb_strlen($trimmedCode)) {
  224.                 $violationList->add($this->buildViolation(
  225.                     'Code may not have any leading or ending whitespaces',
  226.                     $code,
  227.                     'code',
  228.                     'PROMOTION_CODE_WHITESPACE_VIOLATION',
  229.                     $index
  230.                 ));
  231.             }
  232.         }
  233.         if ($pattern !== '' && $this->isCodePatternAlreadyUsed($pattern$promotionId)) {
  234.             $violationList->add($this->buildViolation(
  235.                 'Code Pattern already exists in other promotion. Please provide a different pattern.',
  236.                 $pattern,
  237.                 'individualCodePattern',
  238.                 'PROMOTION_DUPLICATE_PATTERN_VIOLATION',
  239.                 $index
  240.             ));
  241.         }
  242.         // lookup global code if it does already exist in database
  243.         if ($trimmedCode !== '' && $this->isCodeAlreadyUsed($trimmedCode$promotionId)) {
  244.             $violationList->add($this->buildViolation(
  245.                 'Code already exists in other promotion. Please provide a different code.',
  246.                 $trimmedCode,
  247.                 'code',
  248.                 'PROMOTION_DUPLICATED_CODE_VIOLATION',
  249.                 $index
  250.             ));
  251.         }
  252.     }
  253.     /**
  254.      * Validates the provided PromotionDiscount data and adds
  255.      * violations to the provided list of violations, if found.
  256.      *
  257.      * @param array<string, mixed>    $discount      the discount as array from the database
  258.      * @param array<string, mixed>    $payload       the incoming delta-data
  259.      * @param ConstraintViolationList $violationList the list of violations that needs to be filled
  260.      */
  261.     private function validateDiscount(array $discount, array $payloadConstraintViolationList $violationListint $index): void
  262.     {
  263.         /** @var string $type */
  264.         $type $this->getValue($payload'type'$discount);
  265.         /** @var float|null $value */
  266.         $value $this->getValue($payload'value'$discount);
  267.         if ($value === null) {
  268.             return;
  269.         }
  270.         if ($value self::DISCOUNT_MIN_VALUE) {
  271.             $violationList->add($this->buildViolation(
  272.                 'Value must not be less than ' self::DISCOUNT_MIN_VALUE,
  273.                 $value,
  274.                 'value',
  275.                 'PROMOTION_DISCOUNT_MIN_VALUE_VIOLATION',
  276.                 $index
  277.             ));
  278.         }
  279.         switch ($type) {
  280.             case PromotionDiscountEntity::TYPE_PERCENTAGE:
  281.                 if ($value self::DISCOUNT_PERCENTAGE_MAX_VALUE) {
  282.                     $violationList->add($this->buildViolation(
  283.                         'Absolute value must not greater than ' self::DISCOUNT_PERCENTAGE_MAX_VALUE,
  284.                         $value,
  285.                         'value',
  286.                         'PROMOTION_DISCOUNT_MAX_VALUE_VIOLATION',
  287.                         $index
  288.                     ));
  289.                 }
  290.                 break;
  291.         }
  292.     }
  293.     /**
  294.      * Gets a value from an array. It also does clean checks if
  295.      * the key is set, and also provides the option for default values.
  296.      *
  297.      * @param array<string, mixed> $data  the data array
  298.      * @param string               $key   the requested key in the array
  299.      * @param array<string, mixed> $dbRow the db row of from the database
  300.      *
  301.      * @return mixed the object found in the key, or the default value
  302.      */
  303.     private function getValue(array $datastring $key, array $dbRow)
  304.     {
  305.         // try in our actual data set
  306.         if (isset($data[$key])) {
  307.             return $data[$key];
  308.         }
  309.         // try in our db row fallback
  310.         if (isset($dbRow[$key])) {
  311.             return $dbRow[$key];
  312.         }
  313.         // use default
  314.         return null;
  315.     }
  316.     /**
  317.      * @throws ResourceNotFoundException
  318.      *
  319.      * @return array<string, mixed>
  320.      */
  321.     private function getPromotionById(string $id)
  322.     {
  323.         foreach ($this->databasePromotions as $promotion) {
  324.             if ($promotion['id'] === $id) {
  325.                 return $promotion;
  326.             }
  327.         }
  328.         throw new ResourceNotFoundException('promotion', [$id]);
  329.     }
  330.     /**
  331.      * @throws ResourceNotFoundException
  332.      *
  333.      * @return array<string, mixed>
  334.      */
  335.     private function getDiscountById(string $id)
  336.     {
  337.         foreach ($this->databaseDiscounts as $discount) {
  338.             if ($discount['id'] === $id) {
  339.                 return $discount;
  340.             }
  341.         }
  342.         throw new ResourceNotFoundException('promotion_discount', [$id]);
  343.     }
  344.     /**
  345.      * This helper function builds an easy violation
  346.      * object for our validator.
  347.      *
  348.      * @param string $message      the error message
  349.      * @param mixed  $invalidValue the actual invalid value
  350.      * @param string $propertyPath the property path from the root value to the invalid value without initial slash
  351.      * @param string $code         the error code of the violation
  352.      * @param int    $index        the position of this entity in the command queue
  353.      *
  354.      * @return ConstraintViolationInterface the built constraint violation
  355.      */
  356.     private function buildViolation(string $messagemixed $invalidValuestring $propertyPathstring $codeint $index): ConstraintViolationInterface
  357.     {
  358.         $formattedPath "/{$index}/{$propertyPath}";
  359.         return new ConstraintViolation(
  360.             $message,
  361.             '',
  362.             [
  363.                 'value' => $invalidValue,
  364.             ],
  365.             $invalidValue,
  366.             $formattedPath,
  367.             $invalidValue,
  368.             null,
  369.             $code
  370.         );
  371.     }
  372.     /**
  373.      * True, if the provided pattern is already used in another promotion.
  374.      */
  375.     private function isCodePatternAlreadyUsed(string $pattern, ?string $promotionId): bool
  376.     {
  377.         $qb $this->connection->createQueryBuilder();
  378.         $query $qb
  379.             ->select('id')
  380.             ->from('promotion')
  381.             ->where($qb->expr()->eq('individual_code_pattern'':pattern'))
  382.             ->setParameter('pattern'$pattern);
  383.         $promotions $query->executeQuery()->fetchFirstColumn();
  384.         /** @var string $id */
  385.         foreach ($promotions as $id) {
  386.             // if we have a promotion id to verify
  387.             // and a promotion with another id exists, then return that is used
  388.             if ($promotionId !== null && $id !== $promotionId) {
  389.                 return true;
  390.             }
  391.         }
  392.         return false;
  393.     }
  394.     /**
  395.      * True, if the provided code is already used as global
  396.      * or individual code in another promotion.
  397.      */
  398.     private function isCodeAlreadyUsed(string $code, ?string $promotionId): bool
  399.     {
  400.         $qb $this->connection->createQueryBuilder();
  401.         // check if individual code.
  402.         // if we dont have a promotion Id only
  403.         // check if its existing somewhere,
  404.         // if we have an Id, verify if it's existing in another promotion
  405.         $query $qb
  406.             ->select('COUNT(*)')
  407.             ->from('promotion_individual_code')
  408.             ->where($qb->expr()->eq('code'':code'))
  409.             ->setParameter('code'$code);
  410.         if ($promotionId !== null) {
  411.             $query->andWhere($qb->expr()->neq('promotion_id'':promotion_id'))
  412.                 ->setParameter('promotion_id'$promotionId);
  413.         }
  414.         $existingIndividual = ((int) $query->executeQuery()->fetchOne()) > 0;
  415.         if ($existingIndividual) {
  416.             return true;
  417.         }
  418.         $qb $this->connection->createQueryBuilder();
  419.         // check if it is a global promotion code.
  420.         // again with either an existing promotion Id
  421.         // or without one.
  422.         $query
  423.             $qb->select('COUNT(*)')
  424.             ->from('promotion')
  425.             ->where($qb->expr()->eq('code'':code'))
  426.             ->setParameter('code'$code);
  427.         if ($promotionId !== null) {
  428.             $query->andWhere($qb->expr()->neq('id'':id'))
  429.                 ->setParameter('id'$promotionId);
  430.         }
  431.         return ((int) $query->executeQuery()->fetchOne()) > 0;
  432.     }
  433. }