Codegenerator.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\SalesRule\Model\Coupon;
  7. class Codegenerator extends \Magento\Framework\DataObject implements CodegeneratorInterface
  8. {
  9. /**
  10. * The minimum length of the default
  11. */
  12. const DEFAULT_LENGTH_MIN = 16;
  13. /**
  14. * The maximal length of the default
  15. */
  16. const DEFAULT_LENGTH_MAX = 32;
  17. /**
  18. * Collection of the default symbols
  19. */
  20. const SYMBOLS_COLLECTION = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  21. /**
  22. * Delimiter default
  23. */
  24. const DEFAULT_DELIMITER = '-';
  25. /**
  26. * Retrieve generated code
  27. *
  28. * @return string
  29. */
  30. public function generateCode()
  31. {
  32. $alphabet = $this->getAlphabet() ? $this->getAlphabet() : static::SYMBOLS_COLLECTION;
  33. $length = $this->getActualLength();
  34. $code = '';
  35. for ($i = 0, $indexMax = strlen($alphabet) - 1; $i < $length; ++$i) {
  36. $code .= substr($alphabet, random_int(0, $indexMax), 1);
  37. }
  38. return $code;
  39. }
  40. /**
  41. * Getting actual code length
  42. *
  43. * @return int
  44. */
  45. protected function getActualLength()
  46. {
  47. $lengthMin = $this->getLengthMin() ? $this->getLengthMin() : static::DEFAULT_LENGTH_MIN;
  48. $lengthMax = $this->getLengthMax() ? $this->getLengthMax() : static::DEFAULT_LENGTH_MAX;
  49. return $this->getLength() ? $this->getLength() : random_int($lengthMin, $lengthMax);
  50. }
  51. /**
  52. * Retrieve delimiter
  53. *
  54. * @return string
  55. */
  56. public function getDelimiter()
  57. {
  58. return $this->hasData('delimiter') ? $this->getData('delimiter') : static::DEFAULT_DELIMITER;
  59. }
  60. }