/** * {@inheritdoc} * * @param \Magento\Framework\Model\AbstractModel $change * @return $this */ protected function _beforeSave(\Magento\Framework\Model\AbstractModel $change) { if (!$change->getChangeTime()) { $change->setChangeTime($this->dateTime->formatDate(true)); } return $this; }
/** * Update auto generated Specific Coupon if it's rule changed * * @param \Magento\SalesRule\Model\Rule $rule * @return $this */ public function updateSpecificCoupons(\Magento\SalesRule\Model\Rule $rule) { if (!$rule || !$rule->getId() || !$rule->hasDataChanges()) { return $this; } $updateArray = []; if ($rule->dataHasChangedFor('uses_per_coupon')) { $updateArray['usage_limit'] = $rule->getUsesPerCoupon(); } if ($rule->dataHasChangedFor('uses_per_customer')) { $updateArray['usage_per_customer'] = $rule->getUsesPerCustomer(); } $ruleNewDate = $this->dateTime->formatDate($rule->getToDate()); $ruleOldDate = $this->dateTime->formatDate($rule->getOrigData('to_date')); if ($ruleNewDate != $ruleOldDate) { $updateArray['expiration_date'] = $rule->getToDate(); } if (!empty($updateArray)) { $this->getConnection()->update($this->getTable('salesrule_coupon'), $updateArray, ['rule_id = ?' => $rule->getId(), 'generated_by_dotmailer is null']); } //update coupons generated by dotmailer. not to change expiration date $dotmailerUpdateArray = $updateArray; unset($dotmailerUpdateArray['expiration_date']); if (!empty($dotmailerUpdateArray)) { $this->getConnection()->update($this->getTable('salesrule_coupon'), $dotmailerUpdateArray, ['rule_id = ?' => $rule->getId(), 'generated_by_dotmailer is 1']); } return $this; }
/** * Perform actions before object save * * @param \Magento\Framework\Model\AbstractModel $object * @return $this * @throws \Magento\Framework\Model\Exception */ public function _beforeSave(\Magento\Framework\Model\AbstractModel $object) { if ($date = $object->getDateFrom()) { $object->setDateFrom($this->dateTime->formatDate($date)); } else { $object->setDateFrom(null); } if ($date = $object->getDateTo()) { $object->setDateTo($this->dateTime->formatDate($date)); } else { $object->setDateTo(null); } if (!is_null($object->getDateFrom()) && !is_null($object->getDateTo()) && $this->dateTime->toTimestamp($object->getDateFrom()) > $this->dateTime->toTimestamp($object->getDateTo())) { throw new \Magento\Framework\Model\Exception(__('Start date cannot be greater than end date.')); } $check = $this->_checkIntersection($object->getStoreId(), $object->getDateFrom(), $object->getDateTo(), $object->getId()); if ($check) { throw new \Magento\Framework\Model\Exception(__('Your design change for the specified store intersects with another one, please specify another date range.')); } if ($object->getDateFrom() === null) { $object->setDateFrom(new \Zend_Db_Expr('null')); } if ($object->getDateTo() === null) { $object->setDateTo(new \Zend_Db_Expr('null')); } parent::_beforeSave($object); }
/** * @return void */ public function testDeleteRecordsOlderThen() { $timestamp = 12345; $this->resourceMock->expects($this->once())->method('getConnection')->willReturn($this->dbAdapterMock); $this->dbAdapterMock->expects($this->once())->method('delete')->with($this->model->getMainTable(), ['created_at < ?' => $this->dateTimeMock->formatDate($timestamp)])->willReturnSelf(); $this->assertEquals($this->model, $this->model->deleteRecordsOlderThen($timestamp)); }
/** * Process role before saving * * @param \Magento\Framework\Model\AbstractModel $role * @return $this */ protected function _beforeSave(\Magento\Framework\Model\AbstractModel $role) { if (!$role->getId()) { $role->setCreated($this->dateTime->formatDate(true)); } $role->setModified($this->dateTime->formatDate(true)); if ($role->getId() == '') { if ($role->getIdFieldName()) { $role->unsetData($role->getIdFieldName()); } else { $role->unsetData('id'); } } if (!$role->getTreeLevel()) { if ($role->getPid() > 0) { $select = $this->_getReadAdapter()->select()->from($this->getMainTable(), array('tree_level'))->where("{$this->getIdFieldName()} = :pid"); $binds = array('pid' => (int) $role->getPid()); $treeLevel = $this->_getReadAdapter()->fetchOne($select, $binds); } else { $treeLevel = 0; } $role->setTreeLevel($treeLevel + 1); } if ($role->getName()) { $role->setRoleName($role->getName()); } return $this; }
/** * Reports Modules and module changes to the database reporting_module_status table * * @return \Magento\NewRelicReporting\Model\Cron\ReportModulesInfo */ public function report() { if ($this->config->isNewRelicEnabled()) { $moduleData = $this->collect->getModuleData(); if (count($moduleData['changes']) > 0) { foreach ($moduleData['changes'] as $change) { switch ($change['type']) { case Config::ENABLED: $modelData = ['type' => Config::MODULE_ENABLED, 'action' => $this->jsonEncoder->encode($change), 'updated_at' => $this->dateTime->formatDate(true)]; break; case Config::DISABLED: $modelData = ['type' => Config::MODULE_DISABLED, 'action' => $this->jsonEncoder->encode($change), 'updated_at' => $this->dateTime->formatDate(true)]; break; case Config::INSTALLED: $modelData = ['type' => Config::MODULE_INSTALLED, 'action' => $this->jsonEncoder->encode($change), 'updated_at' => $this->dateTime->formatDate(true)]; break; case Config::UNINSTALLED: $modelData = ['type' => Config::MODULE_UNINSTALLED, 'action' => $this->jsonEncoder->encode($change), 'updated_at' => $this->dateTime->formatDate(true)]; break; } /** @var \Magento\NewRelicReporting\Model\System $systemModel */ $systemModel = $this->systemFactory->create(); $systemModel->setData($modelData); $systemModel->save(); } } } return $this; }
/** * Perform actions before object save * * @param \Magento\Framework\Model\AbstractModel $object * @return $this * @throws \Magento\Framework\Exception\LocalizedException */ public function _beforeSave(\Magento\Framework\Model\AbstractModel $object) { if ($date = $object->getDateFrom()) { $object->setDateFrom($this->dateTime->formatDate($date)); } else { $object->setDateFrom(null); } if ($date = $object->getDateTo()) { $object->setDateTo($this->dateTime->formatDate($date)); } else { $object->setDateTo(null); } if (!is_null($object->getDateFrom()) && !is_null($object->getDateTo()) && (new \DateTime($object->getDateFrom()))->getTimestamp() > (new \DateTime($object->getDateTo()))->getTimestamp()) { throw new \Magento\Framework\Exception\LocalizedException(__('The start date can\'t follow the end date.')); } $check = $this->_checkIntersection($object->getStoreId(), $object->getDateFrom(), $object->getDateTo(), $object->getId()); if ($check) { throw new \Magento\Framework\Exception\LocalizedException(__('The date range for this design change overlaps another design change for the specified store.')); } if ($object->getDateFrom() === null) { $object->setDateFrom(new \Zend_Db_Expr('null')); } if ($object->getDateTo() === null) { $object->setDateTo(new \Zend_Db_Expr('null')); } parent::_beforeSave($object); }
/** * {@inheritdoc} */ public function processAuthenticationFailure($customerId) { $now = new \DateTime(); $lockThreshold = $this->getLockThreshold(); $maxFailures = $this->getMaxFailures(); $customerSecure = $this->customerRegistry->retrieveSecureData($customerId); if (!($lockThreshold && $maxFailures)) { return false; } $failuresNum = (int) $customerSecure->getFailuresNum() + 1; $firstFailureDate = $customerSecure->getFirstFailure(); if ($firstFailureDate) { $firstFailureDate = new \DateTime($firstFailureDate); } $lockThreshInterval = new \DateInterval('PT' . $lockThreshold . 'S'); // set first failure date when this is first failure or last first failure expired if (1 === $failuresNum || !$firstFailureDate || $now->diff($firstFailureDate) > $lockThreshInterval) { $customerSecure->setFirstFailure($this->dateTime->formatDate($now)); $failuresNum = 1; // otherwise lock customer } elseif ($failuresNum >= $maxFailures) { $customerSecure->setLockExpires($this->dateTime->formatDate($now->add($lockThreshInterval))); } $customerSecure->setFailuresNum($failuresNum); $this->customerRepository->save($this->customerRepository->getById($customerId)); }
/** * Prepare data to be saved to database * @param \Magento\Framework\Model\AbstractModel|\Magento\Framework\Object $object * * @return $this */ protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object) { if ($object->isObjectNew()) { $object->setCreatedAt($this->dateTime->formatDate(true)); } $object->setUpdatedAt($this->dateTime->formatDate(true)); return $this; }
/** * @return void */ public function testFilterExpiredSessions() { $sessionLifeTime = '600'; $timestamp = time(); $this->securityConfigMock->expects($this->once())->method('getCurrentTimestamp')->willReturn($timestamp); $this->collectionMock->expects($this->once())->method('addFieldToFilter')->with('updated_at', ['gt' => $this->dateTimeMock->formatDate($timestamp - $sessionLifeTime)])->willReturnSelf(); $this->assertEquals($this->collectionMock, $this->collectionMock->filterExpiredSessions($sessionLifeTime)); }
/** * {@inheritdoc} */ public function build($productId) { $timestamp = $this->localeDate->scopeTimeStamp($this->storeManager->getStore()); $currentDate = $this->dateTime->formatDate($timestamp, false); $linkField = $this->metadataPool->getMetadata(ProductInterface::class)->getLinkField(); $productTable = $this->resource->getTableName('catalog_product_entity'); return [$this->resource->getConnection()->select()->from(['parent' => $productTable], '')->joinInner(['link' => $this->resource->getTableName('catalog_product_relation')], "link.parent_id = parent.{$linkField}", [])->joinInner(['child' => $productTable], "child.entity_id = link.child_id", ['entity_id'])->joinInner(['t' => $this->resource->getTableName('catalogrule_product_price')], 't.product_id = child.entity_id', [])->where('parent.entity_id = ? ', $productId)->where('t.website_id = ?', $this->storeManager->getStore()->getWebsiteId())->where('t.customer_group_id = ?', $this->customerSession->getCustomerGroupId())->where('t.rule_date = ?', $currentDate)->order('t.rule_price ' . Select::SQL_ASC)->limit(1)]; }
/** * Delete old entries * * @param int $minutes * @return int */ public function deleteOldEntries($minutes) { if ($minutes > 0) { $connection = $this->getConnection(); return $connection->delete($this->getMainTable(), $connection->quoteInto('type = "' . \Magento\Integration\Model\Oauth\Token::TYPE_REQUEST . '" AND created_at <= ?', $this->_dateTime->formatDate($this->date->gmtTimestamp() - $minutes * 60))); } else { return 0; } }
/** * Set template type, added at and modified at time * * @param \Magento\Framework\Model\AbstractModel $object * @return $this */ protected function _beforeSave(AbstractModel $object) { if ($object->isObjectNew()) { $object->setAddedAt($this->dateTime->formatDate(true)); } $object->setModifiedAt($this->dateTime->formatDate(true)); $object->setTemplateType((int) $object->getTemplateType()); return parent::_beforeSave($object); }
/** * Delete old entries * * @param int $minutes * @return int */ public function deleteOldEntries($minutes) { if ($minutes > 0) { $adapter = $this->_getWriteAdapter(); return $adapter->delete($this->getMainTable(), $adapter->quoteInto('type = "' . \Magento\Integration\Model\Oauth\Token::TYPE_REQUEST . '" AND created_at <= ?', $this->_dateTime->formatDate(time() - $minutes * 60))); } else { return 0; } }
/** * Filter collection by created at date older than specified seconds before now * * @param int $secondsBeforeNow * @return $this */ public function addCreatedAtBeforeFilter($secondsBeforeNow) { $datetime = new \DateTime('now', new \DateTimeZone('UTC')); $storeInterval = new \DateInterval('PT' . $secondsBeforeNow . 'S'); $datetime->sub($storeInterval); $formattedDate = $this->dateTime->formatDate($datetime->getTimestamp()); $this->addFieldToFilter(Log::CREATED_AT_FIELD_NAME, ['lt' => $formattedDate]); return $this; }
/** * @param Collection $productCollection * @param bool $printQuery * @param bool $logQuery * @return array */ public function beforeLoad(Collection $productCollection, $printQuery = false, $logQuery = false) { if (!$productCollection->hasFlag('catalog_rule_loaded')) { $connection = $this->resource->getConnection(); $store = $this->storeManager->getStore(); $productCollection->getSelect()->joinLeft(['catalog_rule' => $this->resource->getTableName('catalogrule_product_price')], implode(' AND ', ['catalog_rule.product_id = e.entity_id', $connection->quoteInto('catalog_rule.website_id = ?', $store->getWebsiteId()), $connection->quoteInto('catalog_rule.customer_group_id = ?', $this->customerSession->getCustomerGroupId()), $connection->quoteInto('catalog_rule.rule_date = ?', $this->dateTime->formatDate($this->localeDate->scopeDate($store->getId()), false))]), [CatalogRulePrice::PRICE_CODE => 'rule_price']); $productCollection->setFlag('catalog_rule_loaded', true); } return [$printQuery, $logQuery]; }
/** * Prepare data to be saved to database. * * @return $this * @codingStandardsIgnoreStart */ public function beforeSave() { //@codingStandardsIgnoreEnd parent::beforeSave(); if ($this->isObjectNew()) { $this->setCreatedAt($this->dateTime->formatDate(true)); } $this->setUpdatedAt($this->dateTime->formatDate(true)); return $this; }
/** * Reports a system cache flush to the database reporting_system_updates table * * @param Observer $observer * @return void * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function execute(Observer $observer) { if ($this->config->isNewRelicEnabled()) { $jsonData = ['status' => 'updated']; $modelData = ['type' => Config::FLUSH_CACHE, 'action' => $this->jsonEncoder->encode($jsonData), 'updated_at' => $this->dateTime->formatDate(true)]; /** @var \Magento\NewRelicReporting\Model\System $systemModel */ $systemModel = $this->systemFactory->create(); $systemModel->setData($modelData); $systemModel->save(); } }
/** * Add date filter to collection * * @param null|int|string|\DateTime $date * @return $this */ public function addDateFilter($date = null) { if ($date === null) { $date = $this->dateTime->formatDate(true); } else { $date = $this->dateTime->formatDate($date); } $this->addFieldToFilter('date_from', ['lteq' => $date]); $this->addFieldToFilter('date_to', ['gteq' => $date]); return $this; }
/** * Update status by user ID * * @param int $status * @param int $userId * @param array $withStatuses * @param array $excludedSessionIds * @param int|null $updateOlderThen * @return int The number of affected rows. * @throws \Magento\Framework\Exception\LocalizedException */ public function updateStatusByUserId($status, $userId, array $withStatuses = [], array $excludedSessionIds = [], $updateOlderThen = null) { $whereStatement = ['updated_at > ?' => $this->dateTime->formatDate($updateOlderThen), 'user_id = ?' => (int) $userId]; if (!empty($excludedSessionIds)) { $whereStatement['session_id NOT IN (?)'] = $excludedSessionIds; } if (!empty($withStatuses)) { $whereStatement['status IN (?)'] = $withStatuses; } return $this->getConnection()->update($this->getMainTable(), ['status' => (int) $status], $whereStatement); }
/** * Updates the count for a specific model in the database * * @param int $count * @param \Magento\NewRelicReporting\Model\Counts $model * @param string $type * @return void */ protected function updateCount($count, \Magento\NewRelicReporting\Model\Counts $model, $type) { /** @var \Magento\NewRelicReporting\Model\ResourceModel\Counts\Collection $collection */ $collection = $this->countsCollectionFactory->create()->addFieldToFilter('type', ['eq' => $type])->addOrder('updated_at', 'DESC')->setPageSize(1); $latestUpdate = $collection->getFirstItem(); if (!$latestUpdate || $count != $latestUpdate->getCount()) { $model->setEntityId(null); $model->setType($type); $model->setCount($count); $model->setUpdatedAt($this->dateTime->formatDate(true)); $model->save(); } }
/** * Reports any products deleted to the database reporting_system_updates table * * @param Observer $observer * @return void */ public function execute(Observer $observer) { if ($this->config->isNewRelicEnabled()) { /** @var \Magento\Catalog\Model\Product $product */ $product = $observer->getEvent()->getProduct(); $jsonData = ['id' => $product->getId(), 'status' => 'deleted']; $modelData = ['type' => Config::PRODUCT_CHANGE, 'action' => $this->jsonEncoder->encode($jsonData), 'updated_at' => $this->dateTime->formatDate(true)]; /** @var \Magento\NewRelicReporting\Model\System $systemModel */ $systemModel = $this->systemFactory->create(); $systemModel->setData($modelData); $systemModel->save(); } }
/** * Test of prolong user action * * @magentoDbIsolation enabled */ public function testProcessProlong() { $this->auth->login(\Magento\TestFramework\Bootstrap::ADMIN_NAME, \Magento\TestFramework\Bootstrap::ADMIN_PASSWORD); $sessionId = $this->authSession->getSessionId(); $dateInPast = $this->dateTime->formatDate($this->authSession->getUpdatedAt() - 100); $this->adminSessionsManager->getCurrentSession()->setData('updated_at', $dateInPast)->save(); $this->adminSessionInfo->load($sessionId, 'session_id'); $oldUpdatedAt = $this->adminSessionInfo->getUpdatedAt(); $this->authSession->prolong(); $this->adminSessionInfo->load($sessionId, 'session_id'); $updatedAt = $this->adminSessionInfo->getUpdatedAt(); $this->assertGreaterThan($oldUpdatedAt, $updatedAt); }
/** * Reports concurrent users to the database reporting_users table * * @param Observer $observer * @return void * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function execute(Observer $observer) { if ($this->config->isNewRelicEnabled()) { if ($this->customerSession->isLoggedIn()) { $customer = $this->customerRepository->getById($this->customerSession->getCustomerId()); $jsonData = ['id' => $customer->getId(), 'name' => $customer->getFirstname() . ' ' . $customer->getLastname(), 'store' => $this->storeManager->getStore()->getName(), 'website' => $this->storeManager->getWebsite()->getName()]; $modelData = ['type' => 'user_action', 'action' => $this->jsonEncoder->encode($jsonData), 'updated_at' => $this->dateTime->formatDate(true)]; /** @var \Magento\NewRelicReporting\Model\Users $usersModel */ $usersModel = $this->usersFactory->create(); $usersModel->setData($modelData); $usersModel->save(); } } }
/** * Reports concurrent admins to the database reporting_users table * * @param Observer $observer * @return void * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function execute(Observer $observer) { if ($this->config->isNewRelicEnabled()) { if ($this->backendAuthSession->isLoggedIn()) { $user = $this->backendAuthSession->getUser(); $jsonData = ['id' => $user->getId(), 'username' => $user->getUsername(), 'name' => $user->getFirstname() . ' ' . $user->getLastname()]; $modelData = ['type' => 'admin_activity', 'action' => $this->jsonEncoder->encode($jsonData), 'updated_at' => $this->dateTime->formatDate(true)]; /** @var \Magento\NewRelicReporting\Model\Users $usersModel */ $usersModel = $this->usersFactory->create(); $usersModel->setData($modelData); $usersModel->save(); } } }
/** * Process page data before saving * * @param \Magento\Framework\Model\AbstractModel $object * @return $this * @throws \Magento\Framework\Model\Exception */ protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object) { /* * For two attributes which represent timestamp data in DB * we should make converting such as: * If they are empty we need to convert them into DB * type NULL so in DB they will be empty and not some default value */ foreach (array('custom_theme_from', 'custom_theme_to') as $field) { $value = !$object->getData($field) ? null : $object->getData($field); $object->setData($field, $this->dateTime->formatDate($value)); } if (!$object->getData('identifier')) { $object->setData('identifier', $this->filter->translitUrl($object->getData('title'))); } if (!$this->getIsUniquePageToStores($object)) { throw new \Magento\Framework\Model\Exception(__('A page URL key for specified store already exists.')); } if (!$this->isValidPageIdentifier($object)) { throw new \Magento\Framework\Model\Exception(__('The page URL key contains capital letters or disallowed symbols.')); } if ($this->isNumericPageIdentifier($object)) { throw new \Magento\Framework\Model\Exception(__('The page URL key cannot be made of only numbers.')); } // modify create / update dates if ($object->isObjectNew() && !$object->hasCreationTime()) { $object->setCreationTime($this->_date->gmtDate()); } $object->setUpdateTime($this->_date->gmtDate()); return parent::_beforeSave($object); }
/** * Clean visitor's outdated records * * @param \Magento\Customer\Model\Visitor $object * @return $this */ public function clean(\Magento\Customer\Model\Visitor $object) { $cleanTime = $object->getCleanTime(); $connection = $this->getConnection(); $timeLimit = $this->dateTime->formatDate($this->date->gmtTimestamp() - $cleanTime); while (true) { $select = $connection->select()->from(['visitor_table' => $this->getTable('customer_visitor')], ['visitor_id' => 'visitor_table.visitor_id'])->where('visitor_table.last_visit_at < ?', $timeLimit)->limit(100); $visitorIds = $connection->fetchCol($select); if (!$visitorIds) { break; } $condition = ['visitor_id IN (?)' => $visitorIds]; $connection->delete($this->getTable('customer_visitor'), $condition); } return $this; }
/** * before save callback * * @param AbstractModel|\Sample\News\Model\Author $object * @return $this */ protected function _beforeSave(AbstractModel $object) { foreach (['dob'] as $field) { $value = !$object->getData($field) ? null : $object->getData($field); $object->setData($field, $this->dateTime->formatDate($value)); } $object->setUpdatedAt($this->date->gmtDate()); if ($object->isObjectNew()) { $object->setCreatedAt($this->date->gmtDate()); } $urlKey = $object->getData('url_key'); if ($urlKey == '') { $urlKey = $object->getName(); } $urlKey = $object->formatUrlKey($urlKey); $object->setUrlKey($urlKey); $validKey = false; while (!$validKey) { if ($this->getIsUniqueAuthorToStores($object)) { $validKey = true; } else { $parts = explode('-', $urlKey); $last = $parts[count($parts) - 1]; if (!is_numeric($last)) { $urlKey = $urlKey . '-1'; } else { $suffix = '-' . ($last + 1); unset($parts[count($parts) - 1]); $urlKey = implode('-', $parts) . $suffix; } $object->setData('url_key', $urlKey); } } return parent::_beforeSave($object); }
/** * Prepare website current dates table * * @return \Magento\Catalog\Model\Indexer\Product\Price\AbstractAction */ protected function _prepareWebsiteDateTable() { $baseCurrency = $this->_config->getValue(\Magento\Directory\Model\Currency::XML_PATH_CURRENCY_BASE); $select = $this->_connection->select()->from(['cw' => $this->_defaultIndexerResource->getTable('store_website')], ['website_id'])->join(['csg' => $this->_defaultIndexerResource->getTable('store_group')], 'cw.default_group_id = csg.group_id', ['store_id' => 'default_store_id'])->where('cw.website_id != 0'); $data = []; foreach ($this->_connection->fetchAll($select) as $item) { /** @var $website \Magento\Store\Model\Website */ $website = $this->_storeManager->getWebsite($item['website_id']); if ($website->getBaseCurrencyCode() != $baseCurrency) { $rate = $this->_currencyFactory->create()->load($baseCurrency)->getRate($website->getBaseCurrencyCode()); if (!$rate) { $rate = 1; } } else { $rate = 1; } /** @var $store \Magento\Store\Model\Store */ $store = $this->_storeManager->getStore($item['store_id']); if ($store) { $timestamp = $this->_localeDate->scopeTimeStamp($store); $data[] = ['website_id' => $website->getId(), 'website_date' => $this->_dateTime->formatDate($timestamp, false), 'rate' => $rate]; } } $table = $this->_defaultIndexerResource->getTable('catalog_product_index_website'); $this->_emptyTable($table); if ($data) { foreach ($data as $row) { $this->_connection->insertOnDuplicate($table, $row, array_keys($row)); } } return $this; }
/** * Generate Coupons Pool * * @throws \Magento\Framework\Exception\LocalizedException * @return $this */ public function generatePool() { $this->generatedCount = 0; $size = $this->getQty(); $maxAttempts = $this->getMaxAttempts() ? $this->getMaxAttempts() : self::MAX_GENERATE_ATTEMPTS; $this->increaseLength(); /** @var $coupon \Magento\SalesRule\Model\Coupon */ $coupon = $this->couponFactory->create(); $nowTimestamp = $this->dateTime->formatDate($this->date->gmtTimestamp()); for ($i = 0; $i < $size; $i++) { $attempt = 0; do { if ($attempt >= $maxAttempts) { throw new \Magento\Framework\Exception\LocalizedException(__('We cannot create the requested Coupon Qty. Please check your settings and try again.')); } $code = $this->generateCode(); ++$attempt; } while ($this->getResource()->exists($code)); $expirationDate = $this->getToDate(); if ($expirationDate instanceof \DateTime) { $expirationDate = $expirationDate->format('Y-m-d H:i:s'); } $coupon->setId(null)->setRuleId($this->getRuleId())->setUsageLimit($this->getUsesPerCoupon())->setUsagePerCustomer($this->getUsesPerCustomer())->setExpirationDate($expirationDate)->setCreatedAt($nowTimestamp)->setType(\Magento\SalesRule\Helper\Coupon::COUPON_TYPE_SPECIFIC_AUTOGENERATED)->setCode($code)->save(); $this->generatedCount += 1; } return $this; }