public function processCalendarDetails($carrierRate, $carrierGroupDetail) { $calendarDetails = parent::processCalendarDetails($carrierRate, $carrierGroupDetail); //transform for current locale $calendarDetails['start'] = $this->localeDate->date($calendarDetails['start'], null, true)->getTimestamp(); return $calendarDetails; }
/** * Refresh sales order report statistics for last day * * @return void */ public function execute() { $this->localeResolver->emulate(0); $currentDate = $this->localeDate->date(); $date = $currentDate->sub(new \DateInterval('PT25H')); $this->orderFactory->create()->aggregate($date); $this->localeResolver->revert(); }
/** * Refresh sales refunded report statistics for last day * * @return void */ public function execute() { $this->localeResolver->emulate(0); $currentDate = $this->localeDate->date(); $date = $currentDate->subHour(25); $this->refundedFactory->create()->aggregate($date); $this->localeResolver->revert(); }
/** * Refresh sales coupons report statistics for last day * * @return $this */ public function execute() { $this->_localeResolver->emulate(0); $currentDate = $this->_localeDate->date(); $date = $currentDate->modify('-25 hours'); $this->_reportRule->aggregate($date); $this->_localeResolver->revert(); return $this; }
/** * Refresh sales tax report statistics for last day * * @return $this */ public function invoke() { $this->localeResolver->emulate(0); $currentDate = $this->localeDate->date(); $date = $currentDate->modify('-25 hours'); /** @var $reportTax \Magento\Tax\Model\ResourceModel\Report\Tax */ $reportTax = $this->reportTaxFactory->create(); $reportTax->aggregate($date); $this->localeResolver->revert(); return $this; }
/** * Delete completed records older then 30 days from provided table. * * @param $tableName * * @return \Exception|int */ public function cleanup($tableName) { try { $interval = new \DateInterval('P30D'); $date = $this->localeDate->date()->sub($interval)->format('Y-m-d H:i:s'); $conn = $this->getConnection(); $num = $conn->delete($tableName, ['created_at < ?' => $date]); return $num; } catch (\Exception $e) { return $e->getMessage(); } }
/** * @param int $storeId * @return \Magento\Catalog\Model\ResourceModel\Product\Collection */ public function getProductsCollection($storeId) { /** @var $product \Magento\Catalog\Model\Product */ $product = $this->productFactory->create(); $todayStartOfDayDate = $this->localeDate->date()->setTime(0, 0)->format('Y-m-d H:i:s'); $todayEndOfDayDate = $this->localeDate->date()->setTime(23, 59, 59)->format('Y-m-d H:i:s'); /** @var $products \Magento\Catalog\Model\ResourceModel\Product\Collection */ $products = $product->getResourceCollection(); $products->setStoreId($storeId); $products->addStoreFilter()->addAttributeToFilter('news_from_date', ['or' => [0 => ['date' => true, 'to' => $todayEndOfDayDate], 1 => ['is' => new \Zend_Db_Expr('null')]]], 'left')->addAttributeToFilter('news_to_date', ['or' => [0 => ['date' => true, 'from' => $todayStartOfDayDate], 1 => ['is' => new \Zend_Db_Expr('null')]]], 'left')->addAttributeToFilter([['attribute' => 'news_from_date', 'is' => new \Zend_Db_Expr('not null')], ['attribute' => 'news_to_date', 'is' => new \Zend_Db_Expr('not null')]])->addAttributeToSort('news_from_date', 'desc')->addAttributeToSelect(['name', 'short_description', 'description'], 'inner')->addAttributeToSelect(['price', 'special_price', 'special_from_date', 'special_to_date', 'msrp_display_actual_price_type', 'msrp', 'thumbnail'], 'left')->applyFrontendPriceLimitations(); $products->setVisibility($this->visibility->getVisibleInCatalogIds()); return $products; }
/** * @param array $dataSource * @return array */ public function prepareDataSource(array $dataSource) { if (isset($dataSource['data']['items'])) { foreach ($dataSource['data']['items'] as & $item) { if (isset($item[$this->getData('name')])) { $date = $this->timezone->date(new \DateTime($item[$this->getData('name')])); $item[$this->getData('name')] = $date->format('Y-m-d H:i:s'); } } } return $dataSource; }
/** * Retrieve attribute value * * @param \Magento\Framework\Object $object * @return mixed */ public function getValue(\Magento\Framework\Object $object) { $data = ''; $value = parent::getValue($object); $format = $this->_localeDate->getDateFormat(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::FORMAT_TYPE_MEDIUM); if ($value) { try { $data = $this->_localeDate->date($value, \Zend_Date::ISO_8601, null, false)->toString($format); } catch (\Exception $e) { $data = $this->_localeDate->date($value, null, null, false)->toString($format); } } return $data; }
/** * Set specified data to current rule. * Set conditions and actions recursively. * Convert dates into \Zend_Date. * * @param array $data * @return array */ protected function _convertFlatToRecursive(array $data) { $arr = array(); foreach ($data as $key => $value) { if (($key === 'conditions' || $key === 'actions') && is_array($value)) { foreach ($value as $id => $data) { $path = explode('--', $id); $node =& $arr; for ($i = 0, $l = sizeof($path); $i < $l; $i++) { if (!isset($node[$key][$path[$i]])) { $node[$key][$path[$i]] = array(); } $node =& $node[$key][$path[$i]]; } foreach ($data as $k => $v) { $node[$k] = $v; } } } else { /** * Convert dates into \Zend_Date */ if (in_array($key, array('from_date', 'to_date')) && $value) { $value = $this->_localeDate->date($value, \Magento\Framework\Stdlib\DateTime::DATE_INTERNAL_FORMAT, null, false); } $this->setData($key, $value); } } return $arr; }
/** * @param string $expYear * @param string $expMonth * @return bool */ protected function _validateExpDate($expYear, $expMonth) { $date = $this->_localeDate->date(); if (!$expYear || !$expMonth || $date->compareYear($expYear) == 1 || $date->compareYear($expYear) == 0 && $date->compareMonth($expMonth) == 1) { return false; } return true; }
/** * Refresh sales coupons report statistics for last day * * @return $this */ public function aggregateSalesReportCouponsData() { $this->_localeResolver->emulate(0); $currentDate = $this->_localeDate->date(); $date = $currentDate->subHour(25); $this->_reportRule->aggregate($date); $this->_localeResolver->revert(); return $this; }
/** * Refresh bestsellers report statistics for last day * * @param \Magento\Cron\Model\Schedule $schedule * @return $this */ public function aggregateSalesReportBestsellersData($schedule) { $this->_localeResolver->emulate(0); $currentDate = $this->_localeDate->date(); $date = $currentDate->subHour(25); $this->_bestsellersFactory->create()->aggregate($date); $this->_localeResolver->revert(); return $this; }
/** * @return array */ public function getValue() { if ($this->getInputType() == 'date' && !$this->getIsValueParsed()) { // date format intentionally hard-coded $this->setValue($this->_localeDate->date($this->getData('value'), \Magento\Framework\Stdlib\DateTime::DATE_INTERNAL_FORMAT, null, false)->toString(\Magento\Framework\Stdlib\DateTime::DATE_INTERNAL_FORMAT)); $this->setIsValueParsed(true); } return $this->getData('value'); }
/** * Refresh sales tax report statistics for last day * * @param \Magento\Cron\Model\Schedule $schedule * @return $this */ public function aggregateSalesReportTaxData($schedule) { $this->_localeResolver->emulate(0); $currentDate = $this->_localeDate->date(); $date = $currentDate->subHour(25); /** @var $reportTax \Magento\Tax\Model\Resource\Report\Tax */ $reportTax = $this->_reportTaxFactory->create(); $reportTax->aggregate($date); $this->_localeResolver->revert(); return $this; }
/** * Convert given date to default (UTC) timezone * * @param int $date * @param string $locale * @return \DateTime|null */ protected function convertDate($date, $locale) { try { $dateObj = $this->localeDate->date(new \DateTime($date), $locale, false); $dateObj->setTime(0, 0, 0); //convert store date to default date in UTC timezone without DST $dateObj->setTimezone(new \DateTimeZone('UTC')); return $dateObj; } catch (\Exception $e) { return null; } }
/** * Convert document date(UTC) fields to default scope specified * * @param \Magento\Framework\Api\Search\DocumentInterface $document * @param string $componentName * @return void */ public function convertDate($document, $componentName) { if (!isset($this->data[$componentName])) { return; } foreach ($this->data[$componentName] as $field) { $fieldValue = $document->getData($field); if (!$fieldValue) { continue; } $convertedDate = $this->localeDate->date(new \DateTime($fieldValue, new \DateTimeZone('UTC')), $this->locale, true); $document->setData($field, $convertedDate->format($this->dateFormat)); } }
/** * Calculate From and To dates (or times) by given period * * @param string $range * @param string $customStart * @param string $customEnd * @param bool $returnObjects * @return array */ public function getDateRange($range, $customStart, $customEnd, $returnObjects = false) { $dateEnd = $this->_localeDate->date(); $dateStart = clone $dateEnd; // go to the end of a day $dateEnd->setHour(23); $dateEnd->setMinute(59); $dateEnd->setSecond(59); $dateStart->setHour(0); $dateStart->setMinute(0); $dateStart->setSecond(0); switch ($range) { case '24h': $dateEnd = $this->_localeDate->date(); $dateEnd->addHour(1); $dateStart = clone $dateEnd; $dateStart->subDay(1); break; case '7d': // substract 6 days we need to include // only today and not hte last one from range $dateStart->subDay(6); break; case '1m': $dateStart->setDay($this->_scopeConfig->getValue('reports/dashboard/mtd_start', \Magento\Store\Model\ScopeInterface::SCOPE_STORE)); break; case 'custom': $dateStart = $customStart ? $customStart : $dateEnd; $dateEnd = $customEnd ? $customEnd : $dateEnd; break; case '1y': case '2y': $startMonthDay = explode(',', $this->_scopeConfig->getValue('reports/dashboard/ytd_start', \Magento\Store\Model\ScopeInterface::SCOPE_STORE)); $startMonth = isset($startMonthDay[0]) ? (int) $startMonthDay[0] : 1; $startDay = isset($startMonthDay[1]) ? (int) $startMonthDay[1] : 1; $dateStart->setMonth($startMonth); $dateStart->setDay($startDay); if ($range == '2y') { $dateStart->subYear(1); } break; } $dateStart->setTimezone('Etc/UTC'); $dateEnd->setTimezone('Etc/UTC'); if ($returnObjects) { return array($dateStart, $dateEnd); } else { return array('from' => $dateStart, 'to' => $dateEnd, 'datetime' => true); } }
/** * Prepare data for save * * @return $this * @throws Exception */ protected function _beforeSave() { // prevent overriding product data if (isset($this->_data['attribute_code']) && $this->reservedAttributeList->isReservedAttribute($this)) { throw new Exception(__('The attribute code \'%1\' is reserved by system. Please try another attribute code', $this->_data['attribute_code'])); } /** * Check for maximum attribute_code length */ if (isset($this->_data['attribute_code']) && !\Zend_Validate::is($this->_data['attribute_code'], 'StringLength', array('max' => self::ATTRIBUTE_CODE_MAX_LENGTH))) { throw new Exception(__('Maximum length of attribute code must be less than %1 symbols', self::ATTRIBUTE_CODE_MAX_LENGTH)); } $defaultValue = $this->getDefaultValue(); $hasDefaultValue = (string) $defaultValue != ''; if ($this->getBackendType() == 'decimal' && $hasDefaultValue) { if (!\Zend_Locale_Format::isNumber($defaultValue, array('locale' => $this->_localeResolver->getLocaleCode()))) { throw new Exception(__('Invalid default decimal value')); } try { $filter = new \Zend_Filter_LocalizedToNormalized(array('locale' => $this->_localeResolver->getLocaleCode())); $this->setDefaultValue($filter->filter($defaultValue)); } catch (\Exception $e) { throw new Exception(__('Invalid default decimal value')); } } if ($this->getBackendType() == 'datetime') { if (!$this->getBackendModel()) { $this->setBackendModel('Magento\\Eav\\Model\\Entity\\Attribute\\Backend\\Datetime'); } if (!$this->getFrontendModel()) { $this->setFrontendModel('Magento\\Eav\\Model\\Entity\\Attribute\\Frontend\\Datetime'); } // save default date value as timestamp if ($hasDefaultValue) { $format = $this->_localeDate->getDateFormat(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::FORMAT_TYPE_SHORT); try { $defaultValue = $this->_localeDate->date($defaultValue, $format, null, false)->toValue(); $this->setDefaultValue($defaultValue); } catch (\Exception $e) { throw new Exception(__('Invalid default date')); } } } if ($this->getBackendType() == 'gallery') { if (!$this->getBackendModel()) { $this->setBackendModel('Magento\\Eav\\Model\\Entity\\Attribute\\Backend\\DefaultBackend'); } } return parent::_beforeSave(); }
/** * Apply filter to collection * * @param AbstractCollection $collection * @return AbstractCollection */ public function filterEntityCollection(AbstractCollection $collection) { if (!isset($this->_parameters[Export::FILTER_ELEMENT_GROUP]) || !is_array($this->_parameters[Export::FILTER_ELEMENT_GROUP])) { $exportFilter = array(); } else { $exportFilter = $this->_parameters[Export::FILTER_ELEMENT_GROUP]; } /** @var $attribute AbstractAttribute */ foreach ($this->filterAttributeCollection($this->getAttributeCollection()) as $attribute) { $attributeCode = $attribute->getAttributeCode(); // filter applying if (isset($exportFilter[$attributeCode])) { $attributeFilterType = Export::getAttributeFilterType($attribute); if (Export::FILTER_TYPE_SELECT == $attributeFilterType) { if (is_scalar($exportFilter[$attributeCode]) && trim($exportFilter[$attributeCode])) { $collection->addAttributeToFilter($attributeCode, array('eq' => $exportFilter[$attributeCode])); } } elseif (Export::FILTER_TYPE_INPUT == $attributeFilterType) { if (is_scalar($exportFilter[$attributeCode]) && trim($exportFilter[$attributeCode])) { $collection->addAttributeToFilter($attributeCode, array('like' => "%{$exportFilter[$attributeCode]}%")); } } elseif (Export::FILTER_TYPE_DATE == $attributeFilterType) { if (is_array($exportFilter[$attributeCode]) && count($exportFilter[$attributeCode]) == 2) { $from = array_shift($exportFilter[$attributeCode]); $to = array_shift($exportFilter[$attributeCode]); if (is_scalar($from) && !empty($from)) { $date = $this->_localeDate->date($from, null, null, false)->toString('MM/dd/YYYY'); $collection->addAttributeToFilter($attributeCode, array('from' => $date, 'date' => true)); } if (is_scalar($to) && !empty($to)) { $date = $this->_localeDate->date($to, null, null, false)->toString('MM/dd/YYYY'); $collection->addAttributeToFilter($attributeCode, array('to' => $date, 'date' => true)); } } } elseif (Export::FILTER_TYPE_NUMBER == $attributeFilterType) { if (is_array($exportFilter[$attributeCode]) && count($exportFilter[$attributeCode]) == 2) { $from = array_shift($exportFilter[$attributeCode]); $to = array_shift($exportFilter[$attributeCode]); if (is_numeric($from)) { $collection->addAttributeToFilter($attributeCode, array('from' => $from)); } if (is_numeric($to)) { $collection->addAttributeToFilter($attributeCode, array('to' => $to)); } } } } } return $collection; }
/** * Filter collection by website(s), customer group(s) and date. * Filter collection to only active rules. * Sorting is not involved * * @param int $websiteId * @param int $customerGroupId * @param string|null $now * @use $this->addWebsiteFilter() * @return $this */ public function addWebsiteGroupDateFilter($websiteId, $customerGroupId, $now = null) { if (!$this->getFlag('website_group_date_filter')) { if (is_null($now)) { $now = $this->_date->date()->format('Y-m-d'); } $this->addWebsiteFilter($websiteId); $entityInfo = $this->_getAssociatedEntityInfo('customer_group'); $connection = $this->getConnection(); $this->getSelect()->joinInner(['customer_group_ids' => $this->getTable($entityInfo['associations_table'])], $connection->quoteInto('main_table.' . $entityInfo['rule_id_field'] . ' = customer_group_ids.' . $entityInfo['rule_id_field'] . ' AND customer_group_ids.' . $entityInfo['entity_id_field'] . ' = ?', (int) $customerGroupId), [])->where('from_date is null or from_date <= ?', $now)->where('to_date is null or to_date >= ?', $now); $this->addIsActiveFilter(); $this->setFlag('website_group_date_filter', true); } return $this; }
/** * Converts input date into timestamp with timezone offset * Input date must be in GMT timezone * * @param int|string $input date in GMT timezone * @return int */ public function timestamp($input = null) { if (is_null($input)) { $result = $this->gmtTimestamp(); } else { if (is_numeric($input)) { $result = $input; } else { $result = strtotime($input); } } $date = $this->_localeDate->date($result); $timestamp = $date->get(\Zend_Date::TIMESTAMP) + $date->get(\Zend_Date::TIMEZONE_SECS); unset($date); return $timestamp; }
/** * Prepare date for save in DB * * string format used from input fields (all date input fields need apply locale settings) * int value can be declared in code (this meen whot we use valid date) * * @param string|int $date * @return string */ public function formatDate($date) { if (empty($date)) { return null; } // unix timestamp given - simply instantiate date object if (preg_match('/^[0-9]+$/', $date)) { $date = new \Magento\Framework\Stdlib\DateTime\Date((int) $date); // international format } elseif (preg_match('#^\\d{4}-\\d{2}-\\d{2}( \\d{2}:\\d{2}:\\d{2})?$#', $date)) { $zendDate = new \Magento\Framework\Stdlib\DateTime\Date(); $date = $zendDate->setIso($date); // parse this date in current locale, do not apply GMT offset } else { $date = $this->_localeDate->date($date, $this->_localeDate->getDateFormat(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::FORMAT_TYPE_SHORT), null, false); } return $date->toString(\Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT); }
/** * Convert given date to default (UTC) timezone * * @param int $date * @param LocaleInterface $locale * @return \Magento\Framework\Stdlib\DateTime\Date|null */ protected function convertDate($date, LocaleInterface $locale) { try { $dateObj = $this->localeDate->date(null, null, $locale, false); //set default timezone for store (admin) $dateObj->setTimezone($this->scopeConfig->getValue($this->localeDate->getDefaultTimezonePath(), \Magento\Framework\Store\ScopeInterface::SCOPE_STORE)); //set beginning of day $dateObj->setHour(00); $dateObj->setMinute(00); $dateObj->setSecond(00); //set date with applying timezone of store $dateObj->set($date, null, $locale); //convert store date to default date in UTC timezone without DST $dateObj->setTimezone(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::DEFAULT_TIMEZONE); return $dateObj; } catch (\Exception $e) { return null; } }
/** * Return formatted option value for quote option * * @param string $optionValue Prepared for cart option value * @return string */ public function getFormattedOptionValue($optionValue) { if ($this->_formattedOptionValue === null) { $option = $this->getOption(); if ($this->getOption()->getType() == \Magento\Catalog\Model\Product\Option::OPTION_TYPE_DATE) { $format = $this->_localeDate->getDateFormat(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::FORMAT_TYPE_MEDIUM); $result = $this->_localeDate->date($optionValue, \Zend_Date::ISO_8601, null, false)->toString($format); } elseif ($this->getOption()->getType() == \Magento\Catalog\Model\Product\Option::OPTION_TYPE_DATE_TIME) { $format = $this->_localeDate->getDateTimeFormat(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::FORMAT_TYPE_SHORT); $result = $this->_localeDate->date($optionValue, \Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT, null, false)->toString($format); } elseif ($this->getOption()->getType() == \Magento\Catalog\Model\Product\Option::OPTION_TYPE_TIME) { $date = new \Magento\Framework\Stdlib\DateTime\Date($optionValue); $result = date($this->is24hTimeFormat() ? 'H:i' : 'h:i a', $date->getTimestamp()); } else { $result = $optionValue; } $this->_formattedOptionValue = $result; } return $this->_formattedOptionValue; }
/** * Send email id payment was failed * * @param \Magento\Sales\Model\Quote $checkout * @param string $message * @param string $checkoutType * @return $this */ public function sendPaymentFailedEmail($checkout, $message, $checkoutType = 'onepage') { $this->inlineTranslation->suspend(); $template = $this->_scopeConfig->getValue('checkout/payment_failed/template', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $checkout->getStoreId()); $copyTo = $this->_getEmails('checkout/payment_failed/copy_to', $checkout->getStoreId()); $copyMethod = $this->_scopeConfig->getValue('checkout/payment_failed/copy_method', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $checkout->getStoreId()); $bcc = array(); if ($copyTo && $copyMethod == 'bcc') { $bcc = $copyTo; } $_receiver = $this->_scopeConfig->getValue('checkout/payment_failed/receiver', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $checkout->getStoreId()); $sendTo = array(array('email' => $this->_scopeConfig->getValue('trans_email/ident_' . $_receiver . '/email', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $checkout->getStoreId()), 'name' => $this->_scopeConfig->getValue('trans_email/ident_' . $_receiver . '/name', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $checkout->getStoreId()))); if ($copyTo && $copyMethod == 'copy') { foreach ($copyTo as $email) { $sendTo[] = array('email' => $email, 'name' => null); } } $shippingMethod = ''; if ($shippingInfo = $checkout->getShippingAddress()->getShippingMethod()) { $data = explode('_', $shippingInfo); $shippingMethod = $data[0]; } $paymentMethod = ''; if ($paymentInfo = $checkout->getPayment()) { $paymentMethod = $paymentInfo->getMethod(); } $items = ''; foreach ($checkout->getAllVisibleItems() as $_item) { /* @var $_item \Magento\Sales\Model\Quote\Item */ $items .= $_item->getProduct()->getName() . ' x ' . $_item->getQty() . ' ' . $checkout->getStoreCurrencyCode() . ' ' . $_item->getProduct()->getFinalPrice($_item->getQty()) . "\n"; } $total = $checkout->getStoreCurrencyCode() . ' ' . $checkout->getGrandTotal(); foreach ($sendTo as $recipient) { $transport = $this->_transportBuilder->setTemplateIdentifier($template)->setTemplateOptions(array('area' => \Magento\Framework\App\Area::AREA_FRONTEND, 'store' => $checkout->getStoreId()))->setTemplateVars(array('reason' => $message, 'checkoutType' => $checkoutType, 'dateAndTime' => $this->_localeDate->date(), 'customer' => $checkout->getCustomerFirstname() . ' ' . $checkout->getCustomerLastname(), 'customerEmail' => $checkout->getCustomerEmail(), 'billingAddress' => $checkout->getBillingAddress(), 'shippingAddress' => $checkout->getShippingAddress(), 'shippingMethod' => $this->_scopeConfig->getValue('carriers/' . $shippingMethod . '/title', \Magento\Store\Model\ScopeInterface::SCOPE_STORE), 'paymentMethod' => $this->_scopeConfig->getValue('payment/' . $paymentMethod . '/title', \Magento\Store\Model\ScopeInterface::SCOPE_STORE), 'items' => nl2br($items), 'total' => $total))->setFrom($this->_scopeConfig->getValue('checkout/payment_failed/identity', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $checkout->getStoreId()))->addTo($recipient['email'], $recipient['name'])->addBcc($bcc)->getTransport(); $transport->sendMessage(); } $this->inlineTranslation->resume(); return $this; }
/** * Stock item saving. * * @return $this */ protected function _saveStockItem() { $indexer = $this->indexerRegistry->get('catalog_product_category'); /** @var $stockResource \Magento\CatalogInventory\Model\ResourceModel\Stock\Item */ $stockResource = $this->_stockResItemFac->create(); $entityTable = $stockResource->getMainTable(); while ($bunch = $this->_dataSourceModel->getNextBunch()) { $stockData = []; $productIdsToReindex = []; // Format bunch to stock data rows foreach ($bunch as $rowNum => $rowData) { if (!$this->isRowAllowedToImport($rowData, $rowNum)) { continue; } $row = []; $row['product_id'] = $this->skuProcessor->getNewSku($rowData[self::COL_SKU])['entity_id']; $productIdsToReindex[] = $row['product_id']; $row['website_id'] = $this->stockConfiguration->getDefaultWebsiteId(); $row['stock_id'] = $this->stockRegistry->getStock($row['website_id'])->getStockId(); $stockItemDo = $this->stockRegistry->getStockItem($row['product_id'], $row['website_id']); $existStockData = $stockItemDo->getData(); $row = array_merge($this->defaultStockData, array_intersect_key($existStockData, $this->defaultStockData), array_intersect_key($rowData, $this->defaultStockData), $row); if ($this->stockConfiguration->isQty($this->skuProcessor->getNewSku($rowData[self::COL_SKU])['type_id'])) { $stockItemDo->setData($row); $row['is_in_stock'] = $this->stockStateProvider->verifyStock($stockItemDo); if ($this->stockStateProvider->verifyNotification($stockItemDo)) { $row['low_stock_date'] = $this->_localeDate->date(null, null, false)->format('Y-m-d H:i:s'); } $row['stock_status_changed_auto'] = (int) (!$this->stockStateProvider->verifyStock($stockItemDo)); } else { $row['qty'] = 0; } $stockData[] = $row; } // Insert rows if (!empty($stockData)) { $this->_connection->insertOnDuplicate($entityTable, $stockData); } if ($productIdsToReindex) { $indexer->reindexList($productIdsToReindex); } } return $this; }
/** * Gather and save information about product entities. * * @return $this * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @SuppressWarnings(PHPMD.UnusedLocalVariable) */ protected function _saveProducts() { $priceIsGlobal = $this->_catalogData->isPriceGlobal(); $productLimit = null; $productsQty = null; while ($bunch = $this->_dataSourceModel->getNextBunch()) { $entityRowsIn = []; $entityRowsUp = []; $attributes = []; $this->websitesCache = []; $this->categoriesCache = []; $tierPrices = []; $mediaGallery = []; $uploadedImages = []; $previousType = null; $prevAttributeSet = null; $bunchImages = $this->getBunchImages($bunch); $existingImages = $this->getExistingImages($bunchImages); foreach ($bunch as $rowNum => $rowData) { if (!$this->validateRow($rowData, $rowNum)) { continue; } if ($this->getErrorAggregator()->hasToBeTerminated()) { $this->getErrorAggregator()->addRowToSkip($rowNum); continue; } $rowScope = $this->getRowScope($rowData); $rowSku = $rowData[self::COL_SKU]; if (null === $rowSku) { $this->getErrorAggregator()->addRowToSkip($rowNum); continue; } elseif (self::SCOPE_STORE == $rowScope) { // set necessary data from SCOPE_DEFAULT row $rowData[self::COL_TYPE] = $this->skuProcessor->getNewSku($rowSku)['type_id']; $rowData['attribute_set_id'] = $this->skuProcessor->getNewSku($rowSku)['attr_set_id']; $rowData[self::COL_ATTR_SET] = $this->skuProcessor->getNewSku($rowSku)['attr_set_code']; } // 1. Entity phase if (isset($this->_oldSku[$rowSku])) { // existing row $entityRowsUp[] = ['updated_at' => (new \DateTime())->format(DateTime::DATETIME_PHP_FORMAT), 'entity_id' => $this->_oldSku[$rowSku]['entity_id']]; } else { if (!$productLimit || $productsQty < $productLimit) { $entityRowsIn[$rowSku] = ['attribute_set_id' => $this->skuProcessor->getNewSku($rowSku)['attr_set_id'], 'type_id' => $this->skuProcessor->getNewSku($rowSku)['type_id'], 'sku' => $rowSku, 'has_options' => isset($rowData['has_options']) ? $rowData['has_options'] : 0, 'created_at' => (new \DateTime())->format(DateTime::DATETIME_PHP_FORMAT), 'updated_at' => (new \DateTime())->format(DateTime::DATETIME_PHP_FORMAT)]; $productsQty++; } else { $rowSku = null; // sign for child rows to be skipped $this->getErrorAggregator()->addRowToSkip($rowNum); continue; } } if (!array_key_exists($rowSku, $this->websitesCache)) { $this->websitesCache[$rowSku] = []; } // 2. Product-to-Website phase if (!empty($rowData[self::COL_PRODUCT_WEBSITES])) { $websiteCodes = explode($this->getMultipleValueSeparator(), $rowData[self::COL_PRODUCT_WEBSITES]); foreach ($websiteCodes as $websiteCode) { $websiteId = $this->storeResolver->getWebsiteCodeToId($websiteCode); $this->websitesCache[$rowSku][$websiteId] = true; } } // 3. Categories phase if (!array_key_exists($rowSku, $this->categoriesCache)) { $this->categoriesCache[$rowSku] = []; } $categoryIds = $this->processRowCategories($rowData); foreach ($categoryIds as $id) { $this->categoriesCache[$rowSku][$id] = true; } // 4.1. Tier prices phase if (!empty($rowData['_tier_price_website'])) { $tierPrices[$rowSku][] = ['all_groups' => $rowData['_tier_price_customer_group'] == self::VALUE_ALL, 'customer_group_id' => $rowData['_tier_price_customer_group'] == self::VALUE_ALL ? 0 : $rowData['_tier_price_customer_group'], 'qty' => $rowData['_tier_price_qty'], 'value' => $rowData['_tier_price_price'], 'website_id' => self::VALUE_ALL == $rowData['_tier_price_website'] || $priceIsGlobal ? 0 : $this->storeResolver->getWebsiteCodeToId($rowData['_tier_price_website'])]; } if (!$this->validateRow($rowData, $rowNum)) { continue; } // 5. Media gallery phase $disabledImages = []; list($rowImages, $rowLabels) = $this->getImagesFromRow($rowData); if (isset($rowData['_media_is_disabled'])) { $disabledImages = array_flip(explode($this->getMultipleValueSeparator(), $rowData['_media_is_disabled'])); } $rowData[self::COL_MEDIA_IMAGE] = []; foreach ($rowImages as $column => $columnImages) { foreach ($columnImages as $position => $columnImage) { if (!isset($uploadedImages[$columnImage])) { $uploadedFile = $this->uploadMediaFiles(trim($columnImage), true); if ($uploadedFile) { $uploadedImages[$columnImage] = $uploadedFile; } else { $this->addRowError(ValidatorInterface::ERROR_MEDIA_URL_NOT_ACCESSIBLE, $rowNum, null, null, ProcessingError::ERROR_LEVEL_NOT_CRITICAL); } } else { $uploadedFile = $uploadedImages[$columnImage]; } if ($uploadedFile && $column !== self::COL_MEDIA_IMAGE) { $rowData[$column] = $uploadedFile; } $imageNotAssigned = !isset($existingImages[$uploadedFile]) || !in_array($rowSku, $existingImages[$uploadedFile]); if ($uploadedFile && $imageNotAssigned) { if ($column == self::COL_MEDIA_IMAGE) { $rowData[$column][] = $uploadedFile; } $mediaGallery[$rowSku][] = ['attribute_id' => $this->getMediaGalleryAttributeId(), 'label' => isset($rowLabels[$column][$position]) ? $rowLabels[$column][$position] : '', 'position' => $position + 1, 'disabled' => isset($disabledImages[$columnImage]) ? '1' : '0', 'value' => $uploadedFile]; $existingImages[$uploadedFile][] = $rowSku; } } } // 6. Attributes phase $rowStore = self::SCOPE_STORE == $rowScope ? $this->storeResolver->getStoreCodeToId($rowData[self::COL_STORE]) : 0; $productType = isset($rowData[self::COL_TYPE]) ? $rowData[self::COL_TYPE] : null; if (!is_null($productType)) { $previousType = $productType; } if (isset($rowData[self::COL_ATTR_SET])) { $prevAttributeSet = $rowData[self::COL_ATTR_SET]; } if (self::SCOPE_NULL == $rowScope) { // for multiselect attributes only if (!is_null($prevAttributeSet)) { $rowData[self::COL_ATTR_SET] = $prevAttributeSet; } if (is_null($productType) && !is_null($previousType)) { $productType = $previousType; } if (is_null($productType)) { continue; } } $productTypeModel = $this->_productTypeModels[$productType]; if (!empty($rowData['tax_class_name'])) { $rowData['tax_class_id'] = $this->taxClassProcessor->upsertTaxClass($rowData['tax_class_name'], $productTypeModel); } if ($this->getBehavior() == Import::BEHAVIOR_APPEND || empty($rowData[self::COL_SKU])) { $rowData = $productTypeModel->clearEmptyData($rowData); } $rowData = $productTypeModel->prepareAttributesWithDefaultValueForSave($rowData, !isset($this->_oldSku[$rowSku])); $product = $this->_proxyProdFactory->create(['data' => $rowData]); foreach ($rowData as $attrCode => $attrValue) { $attribute = $this->retrieveAttributeByCode($attrCode); if ('multiselect' != $attribute->getFrontendInput() && self::SCOPE_NULL == $rowScope) { // skip attribute processing for SCOPE_NULL rows continue; } $attrId = $attribute->getId(); $backModel = $attribute->getBackendModel(); $attrTable = $attribute->getBackend()->getTable(); $storeIds = [0]; if ('datetime' == $attribute->getBackendType() && strtotime($attrValue)) { $attrValue = $this->dateTime->gmDate('Y-m-d H:i:s', $this->_localeDate->date($attrValue)->getTimestamp()); } elseif ($backModel) { $attribute->getBackend()->beforeSave($product); $attrValue = $product->getData($attribute->getAttributeCode()); } if (self::SCOPE_STORE == $rowScope) { if (self::SCOPE_WEBSITE == $attribute->getIsGlobal()) { // check website defaults already set if (!isset($attributes[$attrTable][$rowSku][$attrId][$rowStore])) { $storeIds = $this->storeResolver->getStoreIdToWebsiteStoreIds($rowStore); } } elseif (self::SCOPE_STORE == $attribute->getIsGlobal()) { $storeIds = [$rowStore]; } if (!isset($this->_oldSku[$rowSku])) { $storeIds[] = 0; } } foreach ($storeIds as $storeId) { if (!isset($attributes[$attrTable][$rowSku][$attrId][$storeId])) { $attributes[$attrTable][$rowSku][$attrId][$storeId] = $attrValue; } } // restore 'backend_model' to avoid 'default' setting $attribute->setBackendModel($backModel); } } $this->_saveProductEntity($entityRowsIn, $entityRowsUp)->_saveProductWebsites($this->websitesCache)->_saveProductCategories($this->categoriesCache)->_saveProductTierPrices($tierPrices)->_saveMediaGallery($mediaGallery)->_saveProductAttributes($attributes); $this->_eventManager->dispatch('catalog_product_import_bunch_save_after', ['adapter' => $this, 'bunch' => $bunch]); } return $this; }
/** * Stock item saving. * * @return $this */ protected function _saveStockItem() { /** @var $stockResource \Magento\CatalogInventory\Model\Resource\Stock\Item */ $stockResource = $this->_stockResItemFac->create(); $entityTable = $stockResource->getMainTable(); while ($bunch = $this->_dataSourceModel->getNextBunch()) { $stockData = array(); $productIdsToReindex = array(); // Format bunch to stock data rows foreach ($bunch as $rowNum => $rowData) { if (!$this->isRowAllowedToImport($rowData, $rowNum)) { continue; } // only SCOPE_DEFAULT can contain stock data if (self::SCOPE_DEFAULT != $this->getRowScope($rowData)) { continue; } $row = array(); $row['product_id'] = $this->_newSku[$rowData[self::COL_SKU]]['entity_id']; $productIdsToReindex[] = $row['product_id']; $row['stock_id'] = \Magento\CatalogInventory\Model\Stock\Item::DEFAULT_STOCK_ID; $stockItemDo = $this->stockItemService->getStockItem($row['product_id']); $existStockData = $stockItemDo->__toArray(); $row = array_merge($this->defaultStockData, array_intersect_key($existStockData, $this->defaultStockData), array_intersect_key($rowData, $this->defaultStockData), $row); $row = $this->stockItemService->processIsInStock($row); if ($this->stockItemService->isQty($this->_newSku[$rowData[self::COL_SKU]]['type_id'])) { if ($this->stockItemService->verifyNotification($row['product_id'])) { $row['low_stock_date'] = $this->_localeDate->date(null, null, null, false)->toString(\Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT); } $row['stock_status_changed_auto'] = (int) (!$this->stockItemService->verifyStock($row['product_id'])); } else { $row['qty'] = 0; } $stockData[] = $row; } // Insert rows if (!empty($stockData)) { $this->_connection->insertOnDuplicate($entityTable, $stockData); } if ($productIdsToReindex) { $this->newIndexer->load('catalog_product_category')->reindexList($productIdsToReindex); } } return $this; }
/** * Returns unique string. Used to backup existing pages, blocks, etc * This method is not 100% bullet proof, but there is very low chance to * receive duplicate string. * * @param string $identifier * @return string */ protected function getBackupIdentifier($identifier) { return $identifier . '_backup_' . rand(10, 99) . '_' . $this->localeDate->date()->format('Y-m-d-H-i-s'); }