DotmailerCouponCodeGenerator.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace Dotdigitalgroup\Email\Model\SalesRule;
  3. use Magento\Framework\Math\Random;
  4. use Magento\SalesRule\Helper\Coupon;
  5. use Magento\SalesRule\Model\Coupon\CodegeneratorInterface;
  6. class DotmailerCouponCodeGenerator implements CodegeneratorInterface
  7. {
  8. /**
  9. * @var Coupon
  10. */
  11. private $salesRuleCoupon;
  12. /**
  13. * @param Coupon $salesRuleCoupon
  14. */
  15. public function __construct(
  16. Coupon $salesRuleCoupon
  17. ) {
  18. $this->salesRuleCoupon = $salesRuleCoupon;
  19. }
  20. /**
  21. * @return string
  22. * @throws \Magento\Framework\Exception\LocalizedException
  23. */
  24. public function generateCode()
  25. {
  26. $format = Coupon::COUPON_FORMAT_ALPHANUMERIC;
  27. $splitChar = $this->getDelimiter();
  28. $charset = $this->salesRuleCoupon->getCharset($format);
  29. $code = '';
  30. $charsetSize = count($charset);
  31. $split = 3;
  32. $length = 9;
  33. for ($i = 0; $i < $length; ++$i) {
  34. $char = $charset[Random::getRandomNumber(0, $charsetSize - 1)];
  35. if (($split > 0) && (($i % $split) === 0) && ($i !== 0)) {
  36. $char = $splitChar . $char;
  37. }
  38. $code .= $char;
  39. }
  40. return 'DOT-' . $code;
  41. }
  42. /**
  43. * Retrieve delimiter
  44. *
  45. * @return string
  46. */
  47. public function getDelimiter()
  48. {
  49. return $this->salesRuleCoupon->getCodeSeparator();
  50. }
  51. }