Example #1
0
 /**
  * Process testimonial data before saving
  *
  * @param \Magento\Framework\Model\AbstractModel $object
  * @return $this
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object)
 {
     if (!$object->getId() || !$object->getDate()) {
         $object->setDate($this->_date->gmtDate());
     }
     return parent::_beforeSave($object);
 }
 /**
  * Implements what IntlDateFormatter::formatObject() is in PHP 5.5+
  *
  * @param \IntlCalendar|\DateTime $object
  * @param string|int|array|null $format
  * @param string|null $locale
  * @return string
  * @throws LocalizedException
  */
 protected function doFormatObject($object, $format = null, $locale = null)
 {
     $pattern = $dateFormat = $timeFormat = $calendar = null;
     if (is_array($format)) {
         list($dateFormat, $timeFormat) = $format;
     } elseif (is_numeric($format)) {
         $dateFormat = $format;
     } elseif (is_string($format) || null == $format) {
         $dateFormat = $timeFormat = \IntlDateFormatter::MEDIUM;
         $pattern = $format;
     } else {
         throw new LocalizedException(new Phrase('Format type is invalid'));
     }
     $timezone = $object->getTimezone();
     if ($object instanceof \IntlCalendar) {
         $timezone = $timezone->toDateTimeZone();
     }
     $timezone = $timezone->getName();
     if ($timezone === '+00:00') {
         $timezone = 'UTC';
     } elseif ($timezone[0] === '+' || $timezone[0] === '-') {
         // $timezone[0] is first symbol of string
         $timezone = 'GMT' . $timezone;
     }
     return (new \IntlDateFormatter($locale, $dateFormat, $timeFormat, $timezone, $calendar, $pattern))->format($object);
 }
Example #3
0
 /**
  * Update the status of a queue record and check to confirm the exclusive change
  *
  * @param \Magento\Framework\Model\AbstractModel $object
  * @return bool
  */
 public function changeQueueStatusWithLocking(AbstractModel $object)
 {
     /* @var $object \ClassyLlama\AvaTax\Model\Queue */
     $object->setUpdatedAt($this->dateTime->gmtDate());
     $data = $this->prepareDataForUpdate($object);
     $originalQueueStatus = $object->getOrigData(self::QUEUE_STATUS_FIELD_NAME);
     $originalUpdatedAt = $object->getOrigData(self::UPDATED_AT_FIELD_NAME);
     // A conditional update does a read lock on update so we use the condition on the old
     // queue status here to guarantee that nothing else has modified the status for processing
     $condition = array();
     // update only the queue record identified by Id
     $condition[] = $this->getConnection()->quoteInto($this->getIdFieldName() . '=?', $object->getId());
     // only update the record if it is still pending
     $condition[] = $this->getConnection()->quoteInto(self::QUEUE_STATUS_FIELD_NAME . '=?', $originalQueueStatus);
     // only update the record if nothing else has updated it
     if ($originalUpdatedAt === null) {
         $condition[] = self::UPDATED_AT_FIELD_NAME . ' IS NULL';
     } else {
         $condition[] = $this->getConnection()->quoteInto(self::UPDATED_AT_FIELD_NAME . '=?', $originalUpdatedAt);
     }
     // update the record and get the number of affected records
     $affectedRowCount = $this->getConnection()->update($this->getMainTable(), $data, $condition);
     $result = false;
     if ($affectedRowCount > 0) {
         $object->setHasDataChanges(false);
         $result = true;
     }
     return $result;
 }
Example #4
0
 /**
  * Filter expired sessions
  *
  * @param int $sessionLifeTime
  * @return $this
  */
 public function filterExpiredSessions($sessionLifeTime)
 {
     $connection = $this->getConnection();
     $gmtTimestamp = $this->dateTime->gmtTimestamp();
     $this->addFieldToFilter('updated_at', ['gt' => $connection->formatDate($gmtTimestamp - $sessionLifeTime)]);
     return $this;
 }
Example #5
0
 public function testGetGmtOffset()
 {
     $this->assertSame(-28800, $this->dateTime->getGmtOffset('seconds'));
     $this->assertSame(-28800, $this->dateTime->getGmtOffset('seconds11'));
     $this->assertSame(-480, $this->dateTime->getGmtOffset('minutes'));
     $this->assertSame(-8, $this->dateTime->getGmtOffset('hours'));
 }
Example #6
0
 /**
  * Save action
  *
  * @return \Magento\Framework\Controller\ResultInterface
  */
 public function execute()
 {
     $post = $this->getRequest()->getPostValue();
     /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
     $resultRedirect = $this->resultRedirectFactory->create();
     if ($post) {
         $model = $this->_objectManager->create('OuterEdge\\Layout\\Model\\Groups');
         $data = $this->getRequest()->getParam('group');
         if (isset($data['group_id'])) {
             $model->load($data['group_id']);
         } else {
             $data['created_at'] = $this->datetime->date();
         }
         $model->setData($data);
         try {
             $model->save();
             $this->messageManager->addSuccess(__('The data has been saved.'));
             $this->_objectManager->get('Magento\\Backend\\Model\\Session')->setFormData(false);
             if ($this->getRequest()->getParam('back')) {
                 return $resultRedirect->setPath('*/*/edit', ['group_id' => $model->getId(), '_current' => true]);
             }
             return $resultRedirect->setPath('*/*/');
         } catch (\Magento\Framework\Exception\LocalizedException $e) {
             $this->messageManager->addError($e->getMessage());
         } catch (\RuntimeException $e) {
             $this->messageManager->addError($e->getMessage());
         } catch (\Exception $e) {
             $this->messageManager->addException($e, __('Something went wrong while saving the data.'));
         }
         $this->_getSession()->setFormData($data);
         return $resultRedirect->setPath('*/*/edit', ['group_id' => $this->getRequest()->getParam('group_record_id')]);
     }
     return $resultRedirect->setPath('*/*/');
 }
Example #7
0
 /**
  * Process post data before saving
  *
  * @param \Magento\Framework\Model\AbstractModel $object
  * @return $this
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object)
 {
     if (!$this->isValidNewsblock($object)) {
         throw new \Magento\Framework\Exception\LocalizedException(__('Please fill out newsblock fields.'));
     }
     $object->setUpdateTime($this->_date->gmtDate());
     return parent::_beforeSave($object);
 }
 /**
  * Before saving the object, add the created or updated times
  *
  * @param \Magento\Framework\Model\AbstractModel $object
  * @return $this
  */
 protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object)
 {
     if ($object->isObjectNew() && !$object->hasCreationTime()) {
         $object->setCreationTime($this->_date->gmtDate());
     }
     $object->setUpdateTime($this->_date->gmtDate());
     return parent::_beforeSave($object);
 }
 /**
  * @test
  */
 public function testGmtTimestamp()
 {
     $timezone = $this->getMockBuilder('Magento\\Framework\\Stdlib\\DateTime\\TimezoneInterface')->getMock();
     $timezone->expects($this->any())->method('date')->willReturn(new \DateTime('2015-04-02 21:03:00'));
     /** @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone */
     $dateTime = new DateTime($timezone);
     $this->assertEquals(gmdate('U', strtotime('2015-04-02 21:03:00')), $dateTime->gmtTimestamp('2015-04-02 21:03:00'));
 }
Example #10
0
 /**
  * @return void
  */
 public function testFilterExpiredSessions()
 {
     $sessionLifeTime = '600';
     $timestamp = time();
     $this->dateTimeMock->expects($this->once())->method('gmtTimestamp')->willReturn($timestamp);
     $this->collectionMock->expects($this->once())->method('addFieldToFilter')->with('updated_at', ['gt' => $this->collectionMock->getConnection()->formatDate($timestamp - $sessionLifeTime)])->willReturnSelf();
     $this->assertEquals($this->collectionMock, $this->collectionMock->filterExpiredSessions($sessionLifeTime));
 }
Example #11
0
 /**
  * @return void
  */
 public function testFilterByLifetime()
 {
     $lifetime = 600;
     $timestamp = time();
     $this->dateTimeMock->expects($this->once())->method('gmtTimestamp')->willReturn($timestamp);
     $this->collectionMock->expects($this->once())->method('addFieldToFilter')->with('created_at', ['gt' => $this->collectionMock->getConnection()->formatDate($timestamp - $lifetime)])->willReturnSelf();
     $this->assertEquals($this->collectionMock, $this->collectionMock->filterByLifetime($lifetime));
 }
 /**
  * @param bool $expectedResult
  * @param string $sessionLifetime
  * @dataProvider dataProviderSessionLifetime
  */
 public function testSessionExpired($expectedResult, $sessionLifetime)
 {
     $timestamp = time();
     $this->securityConfigMock->expects($this->once())->method('getAdminSessionLifetime')->will($this->returnValue($sessionLifetime));
     $this->dateTimeMock->expects($this->once())->method('gmtTimestamp')->willReturn($timestamp);
     $this->model->setUpdatedAt(date("Y-m-d H:i:s", $timestamp - 1));
     $this->assertEquals($expectedResult, $this->model->isSessionExpired());
 }
Example #13
0
 protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object)
 {
     if (!$object->getId()) {
         $object->setCreatedAt($this->_date->gmtDate());
     }
     $object->setUpdatedAt($this->_date->gmtDate());
     return $this;
 }
Example #14
0
 /**
  * Prepare online visitors for collection
  *
  * @param \Magento\Log\Model\Visitor\Online $object
  * @return $this
  * @throws \Exception
  */
 public function prepare(\Magento\Log\Model\Visitor\Online $object)
 {
     if ($object->getUpdateFrequency() + $object->getPrepareAt() > time()) {
         return $this;
     }
     $readAdapter = $this->_getReadAdapter();
     $writeAdapter = $this->_getWriteAdapter();
     $writeAdapter->beginTransaction();
     try {
         $writeAdapter->delete($this->getMainTable());
         $visitors = array();
         $lastUrls = array();
         // retrieve online visitors general data
         $lastDate = $this->_date->gmtTimestamp() - $object->getOnlineInterval() * 60;
         $select = $readAdapter->select()->from($this->getTable('log_visitor'), array('visitor_id', 'first_visit_at', 'last_visit_at', 'last_url_id'))->where('last_visit_at >= ?', $readAdapter->formatDate($lastDate));
         $query = $readAdapter->query($select);
         while ($row = $query->fetch()) {
             $visitors[$row['visitor_id']] = $row;
             $lastUrls[$row['last_url_id']] = $row['visitor_id'];
             $visitors[$row['visitor_id']]['visitor_type'] = \Magento\Customer\Model\Visitor::VISITOR_TYPE_VISITOR;
             $visitors[$row['visitor_id']]['customer_id'] = null;
         }
         if (!$visitors) {
             $this->commit();
             return $this;
         }
         // retrieve visitor remote addr
         $select = $readAdapter->select()->from($this->getTable('log_visitor_info'), array('visitor_id', 'remote_addr'))->where('visitor_id IN(?)', array_keys($visitors));
         $query = $readAdapter->query($select);
         while ($row = $query->fetch()) {
             $visitors[$row['visitor_id']]['remote_addr'] = $row['remote_addr'];
         }
         // retrieve visitor last URLs
         $select = $readAdapter->select()->from($this->getTable('log_url_info'), array('url_id', 'url'))->where('url_id IN(?)', array_keys($lastUrls));
         $query = $readAdapter->query($select);
         while ($row = $query->fetch()) {
             $visitorId = $lastUrls[$row['url_id']];
             $visitors[$visitorId]['last_url'] = $row['url'];
         }
         // retrieve customers
         $select = $readAdapter->select()->from($this->getTable('log_customer'), array('visitor_id', 'customer_id'))->where('visitor_id IN(?)', array_keys($visitors));
         $query = $readAdapter->query($select);
         while ($row = $query->fetch()) {
             $visitors[$row['visitor_id']]['visitor_type'] = \Magento\Customer\Model\Visitor::VISITOR_TYPE_CUSTOMER;
             $visitors[$row['visitor_id']]['customer_id'] = $row['customer_id'];
         }
         foreach ($visitors as $visitorData) {
             unset($visitorData['last_url_id']);
             $writeAdapter->insertForce($this->getMainTable(), $visitorData);
         }
         $writeAdapter->commit();
     } catch (\Exception $e) {
         $writeAdapter->rollBack();
         throw $e;
     }
     $object->setPrepareAt();
     return $this;
 }
Example #15
0
 /**
  * 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;
     }
 }
 /**
  * Print credit memos for selected orders
  *
  * @param AbstractCollection $collection
  * @return ResponseInterface|ResultInterface
  */
 protected function massAction(AbstractCollection $collection)
 {
     $creditmemoCollection = $this->collectionFactory->create()->setOrderFilter(['in' => $collection->getAllIds()]);
     if (!$creditmemoCollection->getSize()) {
         $this->messageManager->addError(__('There are no printable documents related to selected orders.'));
         return $this->resultRedirectFactory->create()->setPath($this->getComponentRefererUrl());
     }
     return $this->fileFactory->create(sprintf('creditmemo%s.pdf', $this->dateTime->date('Y-m-d_H-i-s')), $this->pdfCreditmemo->getPdf($creditmemoCollection->getItems())->render(), DirectoryList::VAR_DIR, 'application/pdf');
 }
Example #17
0
 public function testSendPerSubscriberZeroSize()
 {
     $this->queue->setQueueStatus(1);
     $this->queue->setQueueStartAt(1);
     $this->subscribersCollection->expects($this->once())->method('getQueueJoinedFlag')->willReturn(false);
     $this->subscribersCollection->expects($this->once())->method('useQueue')->with($this->queue)->willReturnSelf();
     $this->subscribersCollection->expects($this->once())->method('getSize')->willReturn(0);
     $this->date->expects($this->once())->method('gmtDate')->willReturn('any_date');
     $this->assertEquals($this->queue, $this->queue->sendPerSubscriber());
 }
Example #18
0
 /**
  * Init collection select
  *
  * @return $this
  */
 protected function _initSelect()
 {
     parent::_initSelect();
     $connection = $this->getConnection();
     $lastDate = $this->date->gmtTimestamp() - $this->visitorModel->getOnlineInterval() * self::SECONDS_IN_MINUTE;
     $this->getSelect()->joinLeft(['customer' => $this->getTable('customer_entity')], 'customer.entity_id = main_table.customer_id', ['email', 'firstname', 'lastname'])->where('main_table.last_visit_at >= ?', $connection->formatDate($lastDate));
     $expression = $connection->getCheckSql('main_table.customer_id IS NOT NULL AND main_table.customer_id != 0', $connection->quote(Visitor::VISITOR_TYPE_CUSTOMER), $connection->quote(Visitor::VISITOR_TYPE_VISITOR));
     $this->getSelect()->columns(['visitor_type' => $expression]);
     return $this;
 }
Example #19
0
 /**
  * {@inheritdoc}
  */
 public function validateConsumer($consumer)
 {
     // Must use consumer within expiration period.
     $consumerTS = strtotime($consumer->getCreatedAt());
     $expiry = $this->_dataHelper->getConsumerExpirationPeriod();
     if ($this->_date->timestamp() - $consumerTS > $expiry) {
         throw new \Magento\Framework\Oauth\Exception('Consumer key has expired');
     }
     return true;
 }
 public function testGenerate()
 {
     $orderId = '1';
     $orderIncrementId = '0000000001';
     $timestamp = 12345678;
     $try = 2;
     $order = $this->getOrderMock($orderId, $orderIncrementId);
     $this->transactionResource->expects($this->once())->method('getLastTryByOrderId')->with($this->equalTo($orderId))->willReturn($try);
     $this->dateTime->expects($this->once())->method('timestamp')->willReturn($timestamp);
     $this->assertEquals($orderIncrementId . ':' . $timestamp . ':' . ($try + 1), $this->model->generate($order));
 }
Example #21
0
 /**
  * Perform operations before object save
  *
  * @param \Magento\Framework\Model\AbstractModel $object
  * @return $this
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object)
 {
     if (!$this->getIsUniqueBlockToStores($object)) {
         throw new \Magento\Framework\Exception\LocalizedException(__('A block identifier with the same properties already exists in the selected store.'));
     }
     if (!$object->getId()) {
         $object->setCreationTime($this->_date->gmtDate());
     }
     $object->setUpdateTime($this->_date->gmtDate());
     return $this;
 }
Example #22
0
 /**
  * Process post data before saving
  *
  * @param \Magento\Framework\Model\AbstractModel $object
  * @return $this
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object)
 {
     if (!$this->isValidPostUrlKey($object)) {
         throw new \Magento\Framework\Exception\LocalizedException(__('The post URL key contains capital letters or disallowed symbols.'));
     }
     if ($this->isNumericPostUrlKey($object)) {
         throw new \Magento\Framework\Exception\LocalizedException(__('The post URL key cannot be made of only numbers.'));
     }
     if ($object->isObjectNew() && !$object->hasCreationTime()) {
         $object->setCreationTime($this->_date->gmtDate());
     }
     $object->setUpdateTime($this->_date->gmtDate());
     return parent::_beforeSave($object);
 }
Example #23
0
 /**
  * {@inheritdoc}
  */
 public function check($securityEventType, $accountReference = null, $longIp = null)
 {
     $isEnabled = $this->securityConfig->getPasswordResetProtectionType() != ResetMethod::OPTION_NONE;
     $limitTimeBetweenRequests = $this->securityConfig->getMinTimeBetweenPasswordResetRequests();
     if ($isEnabled && $limitTimeBetweenRequests) {
         if (null === $longIp) {
             $longIp = $this->remoteAddress->getRemoteAddress();
         }
         $lastRecordCreationTimestamp = $this->loadLastRecordCreationTimestamp($securityEventType, $accountReference, $longIp);
         if ($lastRecordCreationTimestamp && $limitTimeBetweenRequests > $this->dateTime->gmtTimestamp() - $lastRecordCreationTimestamp) {
             throw new SecurityViolationException(__('Too many password reset requests. Please wait and try again or contact %1.', $this->securityConfig->getCustomerServiceEmail()));
         }
     }
 }
Example #24
0
 /**
  * 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;
 }
Example #25
0
 /**
  * Finish queue: set status SENT and update finish date
  *
  * @return $this
  */
 protected function _finishQueue()
 {
     $this->setQueueFinishAt($this->_date->gmtDate());
     $this->setQueueStatus(self::STATUS_SENT);
     $this->save();
     return $this;
 }
Example #26
0
 /**
  * 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);
 }
Example #27
0
 /**
  * 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;
 }
Example #28
0
 /**
  * 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);
 }
 public function testSave()
 {
     $productId = 1;
     $this->stockItemMock->expects($this->any())->method('getProductId')->willReturn($productId);
     $this->productMock->expects($this->once())->method('load')->with($productId)->willReturnSelf();
     $this->productMock->expects($this->once())->method('getId')->willReturn($productId);
     $this->productMock->expects($this->once())->method('getTypeId')->willReturn('typeId');
     $this->stockConfigurationMock->expects($this->once())->method('isQty')->with('typeId')->willReturn(true);
     $this->stockStateProviderMock->expects($this->once())->method('verifyStock')->with($this->stockItemMock)->willReturn(false);
     $this->stockItemMock->expects($this->once())->method('getManageStock')->willReturn(true);
     $this->stockItemMock->expects($this->once())->method('setIsInStock')->with(false)->willReturnSelf();
     $this->stockItemMock->expects($this->once())->method('setStockStatusChangedAutomaticallyFlag')->with(true)->willReturnSelf();
     $this->stockItemMock->expects($this->any())->method('setLowStockDate')->willReturnSelf();
     $this->stockStateProviderMock->expects($this->once())->method('verifyNotification')->with($this->stockItemMock)->willReturn(true);
     $this->dateTime->expects($this->once())->method('gmtDate');
     $this->stockItemMock->expects($this->atLeastOnce())->method('setStockStatusChangedAuto')->willReturnSelf();
     $this->stockItemMock->expects($this->once())->method('hasStockStatusChangedAutomaticallyFlag')->willReturn(true);
     $this->stockItemMock->expects($this->once())->method('getStockStatusChangedAutomaticallyFlag')->willReturn(true);
     $this->stockItemMock->expects($this->once())->method('getWebsiteId')->willReturn(1);
     $this->stockItemMock->expects($this->once())->method('setWebsiteId')->with(1)->willReturnSelf();
     $this->stockItemMock->expects($this->once())->method('getStockId')->willReturn(1);
     $this->stockItemMock->expects($this->once())->method('setStockId')->with(1)->willReturnSelf();
     $this->stockItemResourceMock->expects($this->once())->method('save')->with($this->stockItemMock)->willReturnSelf();
     $this->indexProcessorMock->expects($this->once())->method('reindexRow')->with($productId);
     $this->assertEquals($this->stockItemMock, $this->model->save($this->stockItemMock));
 }
Example #30
-6
 /**
  * Print all documents for selected orders
  *
  * @param AbstractCollection $collection
  * @return ResponseInterface|\Magento\Backend\Model\View\Result\Redirect
  *
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  */
 protected function massAction(AbstractCollection $collection)
 {
     $orderIds = $collection->getAllIds();
     $shipments = $this->shipmentCollectionFactory->create()->setOrderFilter(['in' => $orderIds]);
     $invoices = $this->invoiceCollectionFactory->create()->setOrderFilter(['in' => $orderIds]);
     $creditmemos = $this->creditmemoCollectionFactory->create()->setOrderFilter(['in' => $orderIds]);
     $documents = [];
     if ($invoices->getSize()) {
         $documents[] = $this->pdfInvoice->getPdf($invoices);
     }
     if ($shipments->getSize()) {
         $documents[] = $this->pdfShipment->getPdf($shipments);
     }
     if ($creditmemos->getSize()) {
         $documents[] = $this->pdfCreditmemo->getPdf($creditmemos);
     }
     if (empty($documents)) {
         $this->messageManager->addError(__('There are no printable documents related to selected orders.'));
         return $this->resultRedirectFactory->create()->setPath($this->getComponentRefererUrl());
     }
     $pdf = array_shift($documents);
     foreach ($documents as $document) {
         $pdf->pages = array_merge($pdf->pages, $document->pages);
     }
     return $this->fileFactory->create(sprintf('docs%s.pdf', $this->dateTime->date('Y-m-d_H-i-s')), $pdf->render(), DirectoryList::VAR_DIR, 'application/pdf');
 }