/** * {@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)); }
/** * {@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; }
/** * 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)); }
/** * 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); }
/** * 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; }
public function testBeforeSave() { $this->pageMock->expects($this->any())->method('getData')->willReturnMap([['identifier', null, 'test'], ['custom_theme_from', null, null], ['custom_theme_to', null, '10/02/2016']]); $this->dateTimeMock->expects($this->once())->method('formatDate')->with('10/02/2016')->willReturn('10 Feb 2016'); $this->pageMock->expects($this->any())->method('setData')->withConsecutive(['custom_theme_from', null], ['custom_theme_to', '10 Feb 2016']); $this->model->beforeSave($this->pageMock); }
/** * 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; }
/** * Test case when module is enabled in config * * @return void */ public function testReportOrderPlaced() { $testCustomerId = 1; $testTotal = '1.00'; $testBaseTotal = '1.00'; $testItemCount = null; $testTotalQtyOrderedCount = 1; $testUpdated = '1970-01-01 00:00:00'; /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ $eventObserver = $this->getMockBuilder('Magento\\Framework\\Event\\Observer')->disableOriginalConstructor()->getMock(); $this->config->expects($this->once())->method('isNewRelicEnabled')->willReturn(true); $this->dateTime->expects($this->once())->method('formatDate')->willReturn($testUpdated); $event = $this->getMockBuilder('Magento\\Framework\\Event')->setMethods(['getOrder'])->disableOriginalConstructor()->getMock(); $eventObserver->expects($this->once())->method('getEvent')->willReturn($event); $order = $this->getMockBuilder('Magento\\Sales\\Model\\Order')->disableOriginalConstructor()->getMock(); $event->expects($this->once())->method('getOrder')->willReturn($order); $order->expects($this->once())->method('getCustomerId')->willReturn($testCustomerId); $order->expects($this->once())->method('getGrandTotal')->willReturn($testTotal); $order->expects($this->once())->method('getBaseGrandTotal')->willReturn($testBaseTotal); $order->expects($this->once())->method('getTotalItemCount')->willReturn($testItemCount); $order->expects($this->once())->method('getTotalQtyOrdered')->willReturn($testTotalQtyOrderedCount); $this->ordersModel->expects($this->once())->method('setData')->with(['customer_id' => $testCustomerId, 'total' => $testTotal, 'total_base' => $testBaseTotal, 'item_count' => $testTotalQtyOrderedCount, 'updated_at' => $testUpdated])->willReturnSelf(); $this->ordersModel->expects($this->once())->method('save'); $this->model->execute($eventObserver); }
public function testBeforeSave() { $timeStamp = '0000'; $this->dateTimeMock->expects($this->exactly(2))->method('formatDate')->will($this->returnValue($timeStamp)); $this->integrationModel->beforeSave(); $this->assertEquals($timeStamp, $this->integrationModel->getCreatedAt()); $this->assertEquals($timeStamp, $this->integrationModel->getUpdatedAt()); }
/** * Set created date * * @param \Magento\Core\Model\Object $object * @return $this */ public function beforeSave($object) { $attributeCode = $this->getAttribute()->getAttributeCode(); if ($object->isObjectNew() && is_null($object->getData($attributeCode))) { $object->setData($attributeCode, $this->dateTime->now()); } return $this; }
/** * {@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)]; }
/** * @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)); }
/** * 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; }
/** * 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; } }
/** * 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; }
/** * 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; } }
/** * 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); }
/** * Prepare data for save * * @param \Magento\Framework\Model\AbstractModel $object * @return array */ protected function _prepareDataForSave(\Magento\Framework\Model\AbstractModel $object) { $currentTime = $this->dateTime->now(); if ((!$object->getId() || $object->isObjectNew()) && !$object->getCreatedAt()) { $object->setCreatedAt($currentTime); } $object->setUpdatedAt($currentTime); $data = parent::_prepareDataForSave($object); return $data; }
/** * 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; }
/** * @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]; }
/** * Filters the summaries by some period * * @param string $periodType * @param string|int|null $customStart * @param string|int|null $customEnd * @return $this */ public function setSelectPeriod($periodType, $customStart = null, $customEnd = null) { switch ($periodType) { case "24h": $customStart = $this->dateTime->toTimestamp(true) - 86400; $customEnd = $this->dateTime->toTimestamp(true); break; case "7d": $customStart = $this->dateTime->toTimestamp(true) - 604800; $customEnd = $this->dateTime->toTimestamp(true); break; case "30d": $customStart = $this->dateTime->toTimestamp(true) - 2592000; $customEnd = $this->dateTime->toTimestamp(true); break; case "1y": $customStart = $this->dateTime->toTimestamp(true) - 31536000; $customEnd = $this->dateTime->toTimestamp(true); break; default: if (is_string($customStart)) { $customStart = strtotime($customStart); } if (is_string($customEnd)) { $customEnd = strtotime($customEnd); } break; } 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(); } }
/** * 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); }
public function testGetValueDefaultModeSaving() { $this->appState->expects($this->once())->method('getMode')->will($this->returnValue(\Magento\Framework\App\State::MODE_DEFAULT)); $storageException = new \UnexpectedValueException('Does not exist in the storage'); $this->versionStorage->expects($this->once())->method('load')->will($this->throwException($storageException)); $this->dateTime->expects($this->once())->method('toTimestamp')->will($this->returnValue('123')); $this->versionStorage->expects($this->once())->method('save')->with('123'); $this->assertEquals('123', $this->object->getValue()); $this->object->getValue(); // Ensure caching in memory }
/** * 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; }
public function testGetDiscountCollection() { $ruleCollection = $this->getMock('Magento\\SalesRule\\Model\\Resource\\Rule\\Collection', ['addWebsiteGroupDateFilter', 'addFieldToFilter', 'setOrder', 'load'], [], '', false); $this->dateTime->expects($this->once())->method('now'); $this->collectionFactory->expects($this->once())->method('create')->will($this->returnValue($ruleCollection)); $ruleCollection->expects($this->once())->method('addWebsiteGroupDateFilter')->will($this->returnSelf()); $ruleCollection->expects($this->once())->method('addFieldToFilter')->will($this->returnSelf()); $ruleCollection->expects($this->once())->method('setOrder')->will($this->returnSelf()); $ruleCollection->expects($this->once())->method('load')->will($this->returnSelf()); $this->assertEquals($ruleCollection, $this->discounts->getDiscountCollection(1, 1)); }
/** * Setup * * @return void */ public function setUp() { $this->config = $this->getMockBuilder('Magento\\NewRelicReporting\\Model\\Config')->disableOriginalConstructor()->setMethods(['isNewRelicEnabled'])->getMock(); $this->collect = $this->getMockBuilder('Magento\\NewRelicReporting\\Model\\Module\\Collect')->disableOriginalConstructor()->setMethods(['getModuleData'])->getMock(); $this->systemFactory = $this->getMockBuilder('Magento\\NewRelicReporting\\Model\\SystemFactory')->disableOriginalConstructor()->setMethods(['create'])->getMock(); $this->systemModel = $this->getMockBuilder('Magento\\NewRelicReporting\\Model\\System')->disableOriginalConstructor()->getMock(); $this->jsonEncoder = $this->getMockBuilder('Magento\\Framework\\Json\\EncoderInterface')->getMock(); $this->dateTime = $this->getMockBuilder('Magento\\Framework\\Stdlib\\DateTime')->disableOriginalConstructor()->setMethods(['formatDate'])->getMock(); $this->systemFactory->expects($this->any())->method('create')->willReturn($this->systemModel); $this->jsonEncoder->expects($this->any())->method('encode')->willReturn('json_string'); $this->dateTime->expects($this->any())->method('formatDate')->willReturn('1970-01-01 00:00:00'); $this->model = new ReportModulesInfo($this->config, $this->collect, $this->systemFactory, $this->jsonEncoder, $this->dateTime); }
/** * 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(); } }