src/Core/Checkout/Promotion/Validator/PromotionValidator.php line 71

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