Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Rule.php
Go to the documentation of this file.
1 <?php
7 
11 
69 {
74 
76 
77  const COUPON_TYPE_AUTO = 3;
78 
82  const TO_PERCENT_ACTION = 'to_percent';
83 
84  const BY_PERCENT_ACTION = 'by_percent';
85 
86  const TO_FIXED_ACTION = 'to_fixed';
87 
88  const BY_FIXED_ACTION = 'by_fixed';
89 
90  const CART_FIXED_ACTION = 'cart_fixed';
91 
92  const BUY_X_GET_Y_ACTION = 'buy_x_get_y';
93 
100 
106  protected $_eventPrefix = 'salesrule_rule';
107 
115  protected $_eventObject = 'rule';
116 
122  protected $_primaryCoupon;
123 
129  protected $_coupons;
130 
136  protected $_couponTypes;
137 
143  protected $_validatedAddresses = [];
144 
148  protected $_couponFactory;
149 
153  protected $_codegenFactory;
154 
159 
164 
169 
173  protected $_storeManager;
174 
197  public function __construct(
198  \Magento\Framework\Model\Context $context,
199  \Magento\Framework\Registry $registry,
200  \Magento\Framework\Data\FormFactory $formFactory,
201  \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
202  \Magento\SalesRule\Model\CouponFactory $couponFactory,
203  \Magento\SalesRule\Model\Coupon\CodegeneratorFactory $codegenFactory,
204  \Magento\SalesRule\Model\Rule\Condition\CombineFactory $condCombineFactory,
205  \Magento\SalesRule\Model\Rule\Condition\Product\CombineFactory $condProdCombineF,
206  \Magento\SalesRule\Model\ResourceModel\Coupon\Collection $couponCollection,
208  \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
209  \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
210  array $data = [],
211  ExtensionAttributesFactory $extensionFactory = null,
213  \Magento\Framework\Serialize\Serializer\Json $serializer = null
214  ) {
215  $this->_couponFactory = $couponFactory;
216  $this->_codegenFactory = $codegenFactory;
217  $this->_condCombineFactory = $condCombineFactory;
218  $this->_condProdCombineF = $condProdCombineF;
219  $this->_couponCollection = $couponCollection;
220  $this->_storeManager = $storeManager;
221  parent::__construct(
222  $context,
223  $registry,
224  $formFactory,
225  $localeDate,
226  $resource,
227  $resourceCollection,
228  $data,
229  $extensionFactory,
232  );
233  }
234 
240  protected function _construct()
241  {
242  parent::_construct();
243  $this->_init(\Magento\SalesRule\Model\ResourceModel\Rule::class);
244  $this->setIdFieldName('rule_id');
245  }
246 
252  protected function _afterLoad()
253  {
254  $this->loadRelations();
255  return parent::_afterLoad();
256  }
257 
263  public function loadRelations()
264  {
265  $this->loadCouponCode();
266  }
267 
273  public function loadCouponCode()
274  {
275  $this->setCouponCode($this->getPrimaryCoupon()->getCode());
276  if ($this->getUsesPerCoupon() == null && !$this->getUseAutoGeneration()) {
277  $this->setUsesPerCoupon($this->getPrimaryCoupon()->getUsageLimit());
278  }
279  }
280 
286  public function afterSave()
287  {
288  $couponCode = trim($this->getCouponCode());
289  if (strlen(
291  ) && $this->getCouponType() == self::COUPON_TYPE_SPECIFIC && !$this->getUseAutoGeneration()
292  ) {
293  $this->getPrimaryCoupon()->setCode(
295  )->setUsageLimit(
296  $this->getUsesPerCoupon() ? $this->getUsesPerCoupon() : null
297  )->setUsagePerCustomer(
298  $this->getUsesPerCustomer() ? $this->getUsesPerCustomer() : null
299  )->setExpirationDate(
300  $this->getToDate()
301  )->save();
302  } else {
303  $this->getPrimaryCoupon()->delete();
304  }
305 
306  parent::afterSave();
307  return $this;
308  }
309 
316  public function loadPost(array $data)
317  {
318  parent::loadPost($data);
319 
320  if (isset($data['store_labels'])) {
321  $this->setStoreLabels($data['store_labels']);
322  }
323 
324  return $this;
325  }
326 
332  public function getConditionsInstance()
333  {
334  return $this->_condCombineFactory->create();
335  }
336 
342  public function getActionsInstance()
343  {
344  return $this->_condProdCombineF->create();
345  }
346 
352  public function getCouponCodeGenerator()
353  {
354  if (!$this->_couponCodeGenerator) {
355  return $this->_codegenFactory->create(['data' => ['length' => 16]]);
356  }
358  }
359 
366  public function setCouponCodeGenerator(\Magento\SalesRule\Model\Coupon\CodegeneratorInterface $codeGenerator)
367  {
368  $this->_couponCodeGenerator = $codeGenerator;
369  }
370 
376  public function getPrimaryCoupon()
377  {
378  if ($this->_primaryCoupon === null) {
379  $this->_primaryCoupon = $this->_couponFactory->create();
380  $this->_primaryCoupon->loadPrimaryByRule($this->getId());
381  $this->_primaryCoupon->setRule($this)->setIsPrimary(true);
382  }
383  return $this->_primaryCoupon;
384  }
385 
391  public function getCustomerGroupIds()
392  {
393  if (!$this->hasCustomerGroupIds()) {
394  $customerGroupIds = $this->_getResource()->getCustomerGroupIds($this->getId());
395  $this->setData('customer_group_ids', (array)$customerGroupIds);
396  }
397  return $this->_getData('customer_group_ids');
398  }
399 
406  public function getStoreLabel($store = null)
407  {
408  $storeId = $this->_storeManager->getStore($store)->getId();
409  $labels = (array)$this->getStoreLabels();
410 
411  if (isset($labels[$storeId])) {
412  return $labels[$storeId];
413  } elseif (isset($labels[0]) && $labels[0]) {
414  return $labels[0];
415  }
416 
417  return false;
418  }
419 
425  public function getStoreLabels()
426  {
427  if (!$this->hasStoreLabels()) {
428  $labels = $this->_getResource()->getStoreLabels($this->getId());
429  $this->setStoreLabels($labels);
430  }
431 
432  return $this->_getData('store_labels');
433  }
434 
440  public function getCoupons()
441  {
442  if ($this->_coupons === null) {
443  $this->_couponCollection->addRuleToFilter($this);
444  $this->_coupons = $this->_couponCollection->getItems();
445  }
446  return $this->_coupons;
447  }
448 
454  public function getCouponTypes()
455  {
456  if ($this->_couponTypes === null) {
457  $this->_couponTypes = [
460  ];
461  $transport = new \Magento\Framework\DataObject(
462  ['coupon_types' => $this->_couponTypes, 'is_coupon_type_auto_visible' => false]
463  );
464  $this->_eventManager->dispatch('salesrule_rule_get_coupon_types', ['transport' => $transport]);
465  $this->_couponTypes = $transport->getCouponTypes();
466  if ($transport->getIsCouponTypeAutoVisible()) {
467  $this->_couponTypes[\Magento\SalesRule\Model\Rule::COUPON_TYPE_AUTO] = __('Auto');
468  }
469  }
470  return $this->_couponTypes;
471  }
472 
483  public function acquireCoupon($saveNewlyCreated = true, $saveAttemptCount = 10)
484  {
485  if ($this->getCouponType() == self::COUPON_TYPE_NO_COUPON) {
486  return null;
487  }
488  if ($this->getCouponType() == self::COUPON_TYPE_SPECIFIC) {
489  return $this->getPrimaryCoupon();
490  }
492  $coupon = $this->_couponFactory->create();
493  $coupon->setRule(
494  $this
495  )->setIsPrimary(
496  false
497  )->setUsageLimit(
498  $this->getUsesPerCoupon() ? $this->getUsesPerCoupon() : null
499  )->setUsagePerCustomer(
500  $this->getUsesPerCustomer() ? $this->getUsesPerCustomer() : null
501  )->setExpirationDate(
502  $this->getToDate()
503  )->setType(
504  \Magento\SalesRule\Api\Data\CouponInterface::TYPE_GENERATED
505  );
506 
507  $couponCode = self::getCouponCodeGenerator()->generateCode();
508  $coupon->setCode($couponCode);
509 
510  $ok = false;
511  if (!$saveNewlyCreated) {
512  $ok = true;
513  } else {
514  if ($this->getId()) {
515  for ($attemptNum = 0; $attemptNum < $saveAttemptCount; $attemptNum++) {
516  try {
517  $coupon->save();
518  } catch (\Exception $e) {
519  if ($e instanceof \Magento\Framework\Exception\LocalizedException || $coupon->getId()) {
520  throw $e;
521  }
522  $coupon->setCode(
523  $couponCode . self::getCouponCodeGenerator()->getDelimiter() . sprintf(
524  '%04u',
525  random_int(0, 9999)
526  )
527  );
528  continue;
529  }
530  $ok = true;
531  break;
532  }
533  }
534  }
535  if (!$ok) {
536  throw new \Magento\Framework\Exception\LocalizedException(__('Can\'t acquire coupon.'));
537  }
538 
539  return $coupon;
540  }
541 
548  public function getFromDate()
549  {
550  return $this->getData('from_date');
551  }
552 
559  public function getToDate()
560  {
561  return $this->getData('to_date');
562  }
563 
571  {
572  $addressId = $this->_getAddressId($address);
573  return isset($this->_validatedAddresses[$addressId]) ? true : false;
574  }
575 
583  public function setIsValidForAddress($address, $validationResult)
584  {
585  $addressId = $this->_getAddressId($address);
586  $this->_validatedAddresses[$addressId] = $validationResult;
587  return $this;
588  }
589 
598  {
599  $addressId = $this->_getAddressId($address);
600  return isset($this->_validatedAddresses[$addressId]) ? $this->_validatedAddresses[$addressId] : false;
601  }
602 
609  private function _getAddressId($address)
610  {
611  if ($address instanceof Address) {
612  return $address->getId();
613  }
614  return $address;
615  }
616 
624  public function getConditionsFieldSetId($formName = '')
625  {
626  return $formName . 'rule_conditions_fieldset_' . $this->getId();
627  }
628 
636  public function getActionsFieldSetId($formName = '')
637  {
638  return $formName . 'rule_actions_fieldset_' . $this->getId();
639  }
640 }
setIsValidForAddress($address, $validationResult)
Definition: Rule.php:583
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17
loadPost(array $data)
Definition: Rule.php:316
getStoreLabel($store=null)
Definition: Rule.php:406
getActionsFieldSetId($formName='')
Definition: Rule.php:636
$coupon
getConditionsFieldSetId($formName='')
Definition: Rule.php:624
$storeManager
__()
Definition: __.php:13
$resource
Definition: bulk.php:12
$address
Definition: customer.php:38
$formName
Definition: gallery.phtml:11
getIsValidForAddress($address)
Definition: Rule.php:597
setCouponCodeGenerator(\Magento\SalesRule\Model\Coupon\CodegeneratorInterface $codeGenerator)
Definition: Rule.php:366
hasIsValidForAddress($address)
Definition: Rule.php:570
__construct(\Magento\Framework\Model\Context $context, \Magento\Framework\Registry $registry, \Magento\Framework\Data\FormFactory $formFactory, \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate, \Magento\SalesRule\Model\CouponFactory $couponFactory, \Magento\SalesRule\Model\Coupon\CodegeneratorFactory $codegenFactory, \Magento\SalesRule\Model\Rule\Condition\CombineFactory $condCombineFactory, \Magento\SalesRule\Model\Rule\Condition\Product\CombineFactory $condProdCombineF, \Magento\SalesRule\Model\ResourceModel\Coupon\Collection $couponCollection, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Framework\Model\ResourceModel\AbstractResource $resource=null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection=null, array $data=[], ExtensionAttributesFactory $extensionFactory=null, AttributeValueFactory $customAttributeFactory=null, \Magento\Framework\Serialize\Serializer\Json $serializer=null)
Definition: Rule.php:197