PageRenderTime 25ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/magento/module-sales-rule/Model/Coupon/Massgenerator.php

https://gitlab.com/yousafsyed/easternglamor
PHP | 256 lines | 138 code | 26 blank | 92 comment | 20 complexity | cd72dfad4708b227802b7eef7e1cc38f MD5 | raw file
  1. <?php
  2. /**
  3. * Copyright © 2016 Magento. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\SalesRule\Model\Coupon;
  7. /**
  8. * SalesRule Mass Coupon Generator
  9. *
  10. * @method \Magento\SalesRule\Model\ResourceModel\Coupon getResource()
  11. *
  12. * @author Magento Core Team <core@magentocommerce.com>
  13. */
  14. class Massgenerator extends \Magento\Framework\Model\AbstractModel implements
  15. \Magento\SalesRule\Model\Coupon\CodegeneratorInterface
  16. {
  17. /**
  18. * Maximum probability of guessing the coupon on the first attempt
  19. */
  20. const MAX_PROBABILITY_OF_GUESSING = 0.25;
  21. /**
  22. * Number of attempts to generate
  23. */
  24. const MAX_GENERATE_ATTEMPTS = 10;
  25. /**
  26. * Count of generated Coupons
  27. * @var int
  28. */
  29. protected $generatedCount = 0;
  30. /**
  31. * @var array
  32. */
  33. protected $generatedCodes = [];
  34. /**
  35. * Sales rule coupon
  36. *
  37. * @var \Magento\SalesRule\Helper\Coupon
  38. */
  39. protected $salesRuleCoupon;
  40. /**
  41. * @var \Magento\Framework\Stdlib\DateTime\DateTime
  42. */
  43. protected $date;
  44. /**
  45. * @var \Magento\SalesRule\Model\CouponFactory
  46. */
  47. protected $couponFactory;
  48. /**
  49. * @var \Magento\Framework\Stdlib\DateTime
  50. */
  51. protected $dateTime;
  52. /**
  53. * @param \Magento\Framework\Model\Context $context
  54. * @param \Magento\Framework\Registry $registry
  55. * @param \Magento\SalesRule\Helper\Coupon $salesRuleCoupon
  56. * @param \Magento\SalesRule\Model\CouponFactory $couponFactory
  57. * @param \Magento\Framework\Stdlib\DateTime\DateTime $date
  58. * @param \Magento\Framework\Stdlib\DateTime $dateTime
  59. * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource
  60. * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection
  61. * @param array $data
  62. */
  63. public function __construct(
  64. \Magento\Framework\Model\Context $context,
  65. \Magento\Framework\Registry $registry,
  66. \Magento\SalesRule\Helper\Coupon $salesRuleCoupon,
  67. \Magento\SalesRule\Model\CouponFactory $couponFactory,
  68. \Magento\Framework\Stdlib\DateTime\DateTime $date,
  69. \Magento\Framework\Stdlib\DateTime $dateTime,
  70. \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
  71. \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
  72. array $data = []
  73. ) {
  74. $this->salesRuleCoupon = $salesRuleCoupon;
  75. $this->date = $date;
  76. $this->couponFactory = $couponFactory;
  77. $this->dateTime = $dateTime;
  78. parent::__construct($context, $registry, $resource, $resourceCollection, $data);
  79. }
  80. /**
  81. * Initialize resource
  82. *
  83. * @return void
  84. */
  85. protected function _construct()
  86. {
  87. $this->_init('Magento\SalesRule\Model\ResourceModel\Coupon');
  88. }
  89. /**
  90. * Generate coupon code
  91. *
  92. * @return string
  93. */
  94. public function generateCode()
  95. {
  96. $format = $this->getFormat();
  97. if (empty($format)) {
  98. $format = \Magento\SalesRule\Helper\Coupon::COUPON_FORMAT_ALPHANUMERIC;
  99. }
  100. $splitChar = $this->getDelimiter();
  101. $charset = $this->salesRuleCoupon->getCharset($format);
  102. $code = '';
  103. $charsetSize = count($charset);
  104. $split = max(0, (int)$this->getDash());
  105. $length = max(1, (int)$this->getLength());
  106. for ($i = 0; $i < $length; ++$i) {
  107. $char = $charset[\Magento\Framework\Math\Random::getRandomNumber(0, $charsetSize - 1)];
  108. if (($split > 0) && (($i % $split) === 0) && ($i !== 0)) {
  109. $char = $splitChar . $char;
  110. }
  111. $code .= $char;
  112. }
  113. return $this->getPrefix() . $code . $this->getSuffix();
  114. }
  115. /**
  116. * Retrieve delimiter
  117. *
  118. * @return string
  119. */
  120. public function getDelimiter()
  121. {
  122. if ($this->hasData('delimiter')) {
  123. return $this->getData('delimiter');
  124. } else {
  125. return $this->salesRuleCoupon->getCodeSeparator();
  126. }
  127. }
  128. /**
  129. * Generate Coupons Pool
  130. *
  131. * @throws \Magento\Framework\Exception\LocalizedException
  132. * @return $this
  133. */
  134. public function generatePool()
  135. {
  136. $this->generatedCount = 0;
  137. $this->generatedCodes = [];
  138. $size = $this->getQty();
  139. $maxAttempts = $this->getMaxAttempts() ? $this->getMaxAttempts() : self::MAX_GENERATE_ATTEMPTS;
  140. $this->increaseLength();
  141. /** @var $coupon \Magento\SalesRule\Model\Coupon */
  142. $coupon = $this->couponFactory->create();
  143. $nowTimestamp = $this->dateTime->formatDate($this->date->gmtTimestamp());
  144. for ($i = 0; $i < $size; $i++) {
  145. $attempt = 0;
  146. do {
  147. if ($attempt >= $maxAttempts) {
  148. throw new \Magento\Framework\Exception\LocalizedException(
  149. __('We cannot create the requested Coupon Qty. Please check your settings and try again.')
  150. );
  151. }
  152. $code = $this->generateCode();
  153. ++$attempt;
  154. } while ($this->getResource()->exists($code));
  155. $expirationDate = $this->getToDate();
  156. if ($expirationDate instanceof \DateTime) {
  157. $expirationDate = $expirationDate->format('Y-m-d H:i:s');
  158. }
  159. $coupon->setId(null)
  160. ->setRuleId($this->getRuleId())
  161. ->setUsageLimit($this->getUsesPerCoupon())
  162. ->setUsagePerCustomer($this->getUsagePerCustomer())
  163. ->setExpirationDate($expirationDate)
  164. ->setCreatedAt($nowTimestamp)
  165. ->setType(\Magento\SalesRule\Helper\Coupon::COUPON_TYPE_SPECIFIC_AUTOGENERATED)
  166. ->setCode($code)
  167. ->save();
  168. $this->generatedCount += 1;
  169. $this->generatedCodes[] = $code;
  170. }
  171. return $this;
  172. }
  173. /**
  174. * Increase the length of Code if probability is low
  175. *
  176. * @return void
  177. */
  178. protected function increaseLength()
  179. {
  180. $maxProbability = $this->getMaxProbability() ? $this->getMaxProbability() : self::MAX_PROBABILITY_OF_GUESSING;
  181. $chars = count($this->salesRuleCoupon->getCharset($this->getFormat()));
  182. $size = $this->getQty();
  183. $length = (int)$this->getLength();
  184. $maxCodes = pow($chars, $length);
  185. $probability = $size / $maxCodes;
  186. if ($probability > $maxProbability) {
  187. do {
  188. $length++;
  189. $maxCodes = pow($chars, $length);
  190. $probability = $size / $maxCodes;
  191. } while ($probability > $maxProbability);
  192. $this->setLength($length);
  193. }
  194. }
  195. /**
  196. * Validate data input
  197. *
  198. * @param array $data
  199. * @return bool
  200. */
  201. public function validateData($data)
  202. {
  203. return !empty($data)
  204. && !empty($data['qty'])
  205. && !empty($data['rule_id'])
  206. && !empty($data['length'])
  207. && !empty($data['format'])
  208. && (int)$data['qty'] > 0
  209. && (int)$data['rule_id'] > 0
  210. && (int)$data['length'] > 0;
  211. }
  212. /**
  213. * Return the generated coupon codes
  214. *
  215. * @return array
  216. */
  217. public function getGeneratedCodes()
  218. {
  219. return $this->generatedCodes;
  220. }
  221. /**
  222. * Retrieve count of generated Coupons
  223. *
  224. * @return int
  225. */
  226. public function getGeneratedCount()
  227. {
  228. return $this->generatedCount;
  229. }
  230. }