/** * @return array */ public function formatDateDataProvider() { // Take care when calling date here as it can be called much earlier than when testFormatDate // executes thus causing a discrepancy in the actual vs expected time. See MAGETWO-10296 $date = new \Magento\Framework\Stdlib\DateTime\Date(); return ['null' => [null, false, ''], 'null including Time' => [null, true, ''], 'Bool true' => [true, false, 'Y-m-d'], 'Bool true including Time' => [true, true, 'Y-m-d H:i:s'], 'Bool false' => [false, false, ''], 'Bool false including Time' => [false, true, ''], 'Zend Date' => [$date, false, date('Y-m-d', $date->getTimestamp())], 'Zend Date including Time' => [$date, true, date('Y-m-d H:i:s', $date->getTimestamp())]]; }
/** * Set current attribute to entry (for specified product) * * @param \Magento\Catalog\Model\Product $product * @param \Magento\Framework\Gdata\Gshopping\Entry $entry * @return \Magento\Framework\Gdata\Gshopping\Entry */ public function convertAttribute($product, $entry) { $effectiveDateFrom = $this->getGroupAttributeSalePriceEffectiveDateFrom(); $fromValue = $effectiveDateFrom->getProductAttributeValue($product); $effectiveDateTo = $this->getGroupAttributeSalePriceEffectiveDateTo(); $toValue = $effectiveDateTo->getProductAttributeValue($product); $from = $to = null; if (!empty($fromValue) && \Zend_Date::isDate($fromValue, \Zend_Date::ATOM)) { $from = new \Magento\Framework\Stdlib\DateTime\Date($fromValue, \Zend_Date::ATOM); } if (!empty($toValue) && \Zend_Date::isDate($toValue, \Zend_Date::ATOM)) { $to = new \Magento\Framework\Stdlib\DateTime\Date($toValue, \Zend_Date::ATOM); } $dateString = null; // if we have from an to dates, and if these dates are correct if (!is_null($from) && !is_null($to) && $from->isEarlier($to)) { $dateString = $from->toString(\Zend_Date::ATOM) . '/' . $to->toString(\Zend_Date::ATOM); } // if we have only "from" date, send "from" day if (!is_null($from) && is_null($to)) { $dateString = $from->toString('YYYY-MM-dd'); } // if we have only "to" date, use "now" date for "from" if (is_null($from) && !is_null($to)) { $from = new \Magento\Framework\Stdlib\DateTime\Date(); // if "now" date is earlier than "to" date if ($from->isEarlier($to)) { $dateString = $from->toString(\Zend_Date::ATOM) . '/' . $to->toString(\Zend_Date::ATOM); } } if (!is_null($dateString)) { $this->_setAttribute($entry, 'sale_price_effective_date', self::ATTRIBUTE_TYPE_TEXT, $dateString); } return $entry; }
/** * Get current attribute value for specified product * * @param \Magento\Catalog\Model\Product $product * @return null|string */ public function getProductAttributeValue($product) { if (is_null($this->getAttributeId())) { return null; } $productAttribute = $this->_gsProduct->getProductAttribute($product, $this->getAttributeId()); if (is_null($productAttribute)) { return null; } if ($productAttribute->getFrontendInput() == 'date' || $productAttribute->getBackendType() == 'date') { $value = $product->getData($productAttribute->getAttributeCode()); if (empty($value) || !\Zend_Date::isDate($value, \Zend_Date::ISO_8601)) { return null; } $date = new \Magento\Framework\Stdlib\DateTime\Date($value, \Zend_Date::ISO_8601); $value = $date->toString(\Zend_Date::ATOM); } else { $value = $productAttribute->getFrontend()->getValue($product); } return $value; }
/** * Save report rows collected in settlement model * * @param \Magento\Framework\Model\AbstractModel|\Magento\Paypal\Model\Report\Settlement $object * @return $this */ protected function _afterSave(\Magento\Framework\Model\AbstractModel $object) { $rows = $object->getRows(); if (is_array($rows)) { $adapter = $this->_getWriteAdapter(); $reportId = (int) $object->getId(); try { $adapter->beginTransaction(); if ($reportId) { $adapter->delete($this->_rowsTable, array('report_id = ?' => $reportId)); } foreach (array_keys($rows) as $key) { /** * Converting dates */ $completionDate = new \Magento\Framework\Stdlib\DateTime\Date($rows[$key]['transaction_completion_date']); $rows[$key]['transaction_completion_date'] = $this->_coreDate->date(null, $completionDate->getTimestamp()); $initiationDate = new \Magento\Framework\Stdlib\DateTime\Date($rows[$key]['transaction_initiation_date']); $rows[$key]['transaction_initiation_date'] = $this->_coreDate->date(null, $initiationDate->getTimestamp()); /* * Converting numeric */ $rows[$key]['fee_amount'] = (double) $rows[$key]['fee_amount']; /* * Setting reportId */ $rows[$key]['report_id'] = $reportId; } if (!empty($rows)) { $adapter->insertMultiple($this->_rowsTable, $rows); } $adapter->commit(); } catch (\Exception $e) { $adapter->rollback(); } } return $this; }
/** * Retrieve array of intervals * * @param string $from * @param string $to * @param string $period * @return array */ public function getIntervals($from, $to, $period = self::REPORT_PERIOD_TYPE_DAY) { $intervals = array(); if (!$from && !$to) { return $intervals; } $start = new \Magento\Framework\Stdlib\DateTime\Date($from, \Magento\Framework\Stdlib\DateTime::DATE_INTERNAL_FORMAT); if ($period == self::REPORT_PERIOD_TYPE_DAY) { $dateStart = $start; } if ($period == self::REPORT_PERIOD_TYPE_MONTH) { $dateStart = new \Magento\Framework\Stdlib\DateTime\Date(date("Y-m", $start->getTimestamp()), DateTime::DATE_INTERNAL_FORMAT); } if ($period == self::REPORT_PERIOD_TYPE_YEAR) { $dateStart = new \Magento\Framework\Stdlib\DateTime\Date(date("Y", $start->getTimestamp()), DateTime::DATE_INTERNAL_FORMAT); } $dateEnd = new \Magento\Framework\Stdlib\DateTime\Date($to, DateTime::DATE_INTERNAL_FORMAT); while ($dateStart->compare($dateEnd) <= 0) { switch ($period) { case self::REPORT_PERIOD_TYPE_DAY: $t = $dateStart->toString('yyyy-MM-dd'); $dateStart->addDay(1); break; case self::REPORT_PERIOD_TYPE_MONTH: $t = $dateStart->toString('yyyy-MM'); $dateStart->addMonth(1); break; case self::REPORT_PERIOD_TYPE_YEAR: $t = $dateStart->toString('yyyy'); $dateStart->addYear(1); break; } $intervals[] = $t; } return $intervals; }
/** * Apply sorting and filtering to collection * * @return $this */ protected function _prepareCollection() { $filter = $this->getParam($this->getVarNameFilter(), null); if (is_null($filter)) { $filter = $this->_defaultFilter; } if (is_string($filter)) { $data = array(); $filter = base64_decode($filter); parse_str(urldecode($filter), $data); if (!isset($data['report_from'])) { // getting all reports from 2001 year $date = new \Magento\Framework\Stdlib\DateTime\Date(mktime(0, 0, 0, 1, 1, 2001)); $data['report_from'] = $date->toString($this->_localeDate->getDateFormat('short')); } if (!isset($data['report_to'])) { // getting all reports from 2001 year $date = new \Magento\Framework\Stdlib\DateTime\Date(); $data['report_to'] = $date->toString($this->_localeDate->getDateFormat('short')); } $this->_setFilterValues($data); } elseif ($filter && is_array($filter)) { $this->_setFilterValues($filter); } elseif (0 !== sizeof($this->_defaultFilter)) { $this->_setFilterValues($this->_defaultFilter); } /** @var $collection \Magento\Reports\Model\Resource\Report\Collection */ $collection = $this->getCollection(); if ($collection) { $collection->setPeriod($this->getFilter('report_period')); if ($this->getFilter('report_from') && $this->getFilter('report_to')) { /** * Validate from and to date */ try { $from = $this->_localeDate->date($this->getFilter('report_from'), \Zend_Date::DATE_SHORT, null, false); $to = $this->_localeDate->date($this->getFilter('report_to'), \Zend_Date::DATE_SHORT, null, false); $collection->setInterval($from, $to); } catch (\Exception $e) { $this->_errors[] = __('Invalid date specified'); } } $collection->setStoreIds($this->_getAllowedStoreIds()); if ($this->getSubReportSize() !== null) { $collection->setPageSize($this->getSubReportSize()); } $this->_eventManager->dispatch('adminhtml_widget_grid_filter_collection', array('collection' => $this->getCollection(), 'filter_values' => $this->_filterValues)); } return $this; }
/** * Adds filter on days in wishlist * * The $constraints may contain 'from' and 'to' indexes with number of days to look for items * * @param array $constraints * @return $this */ public function addDaysFilter($constraints) { if (!is_array($constraints)) { return $this; } $filter = array(); $now = $this->_date->date(); $gmtOffset = (int) $this->_date->getGmtOffset(); if (isset($constraints['from'])) { $lastDay = new \Magento\Framework\Stdlib\DateTime\Date($now, \Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT); $lastDay->subSecond($gmtOffset)->subDay(intval($constraints['from'])); $filter['to'] = $lastDay; } if (isset($constraints['to'])) { $firstDay = new \Magento\Framework\Stdlib\DateTime\Date($now, \Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT); $firstDay->subSecond($gmtOffset)->subDay(intval($constraints['to']) + 1); $filter['from'] = $firstDay; } if ($filter) { $filter['datetime'] = true; $this->addFieldToFilter('added_at', $filter); } return $this; }
/** * Parse CSV file and collect report rows * * @param string $localCsv Path to CSV file * @param string $format CSV format(column names) * @return $this */ public function parseCsv($localCsv, $format = 'new') { $this->_rows = array(); $sectionColumns = $this->_csvColumns[$format]['section_columns']; $rowMap = $this->_csvColumns[$format]['rowmap']; $flippedSectionColumns = array_flip($sectionColumns); $stream = $this->_tmpDirectory->openFile($localCsv); while ($line = $stream->readCsv()) { if (empty($line)) { // The line was empty, so skip it. continue; } $lineType = $line[0]; switch ($lineType) { case 'RH': // Report header. $lastModified = new \Magento\Framework\Stdlib\DateTime\Date($line[1]); $this->setReportLastModified($lastModified->toString(\Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT)); //$this->setAccountId($columns[2]); -- probably we'll just take that from the section header... break; case 'FH': // File header. // Nothing interesting here, move along break; case 'SH': // Section header. $this->setAccountId($line[3]); $this->loadByAccountAndDate(); break; case 'CH': // Section columns. // In case ever the column order is changed, we will have the items recorded properly // anyway. We have named, not numbered columns. for ($i = 1; $i < count($line); $i++) { $sectionColumns[$line[$i]] = $i; } $flippedSectionColumns = array_flip($sectionColumns); break; case 'SB': // Section body. $bodyItem = array(); for ($i = 1; $i < count($line); $i++) { $bodyItem[$rowMap[$flippedSectionColumns[$i]]] = $line[$i]; } $this->_rows[] = $bodyItem; break; case 'SC': // Section records count. // Section records count. case 'RC': // Report records count. // Report records count. case 'SF': // Section footer. // Section footer. case 'FF': // File footer. // File footer. case 'RF': // Report footer. // Nothing to see here, move along break; default: break; } } return $this; }
/** * Parse user input value and return cart prepared value * * @param string $optionValue * @param array $productOptionValues Values for product option * @return string|null */ public function parseOptionValue($optionValue, $productOptionValues) { $timestamp = strtotime($optionValue); if ($timestamp === false || $timestamp == -1) { return null; } $date = new \Magento\Framework\Stdlib\DateTime\Date($timestamp); return $date->toString(\Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT); }
/** * 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); }
/** * Determine nearest possible payment start date * * @param \Magento\Framework\Stdlib\DateTime\DateInterface $minAllowed * @return $this */ protected function setNearestStartDatetime(\Magento\Framework\Stdlib\DateTime\DateInterface $minAllowed = null) { // TODO: implement proper logic with invoking payment method instance $date = $minAllowed; if (!$date || $date->getTimestamp() < time()) { $date = new \Magento\Framework\Stdlib\DateTime\Date(time()); } $this->setStartDatetime($date->toString(\Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT)); return $this; }
/** * Return indexer or mview latest updated time * * @return string */ public function getLatestUpdated() { if ($this->getView()->isEnabled() && $this->getView()->getUpdated()) { if (!$this->getState()->getUpdated()) { return $this->getView()->getUpdated(); } $indexerUpdatedDate = new \Magento\Framework\Stdlib\DateTime\Date($this->getState()->getUpdated()); $viewUpdatedDate = new \Magento\Framework\Stdlib\DateTime\Date($this->getView()->getUpdated()); if ($viewUpdatedDate->compare($indexerUpdatedDate) == 1) { return $this->getView()->getUpdated(); } } return $this->getState()->getUpdated(); }
/** * 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 = array(); if ($rule->dataHasChangedFor('uses_per_coupon')) { $updateArray['usage_limit'] = $rule->getUsesPerCoupon(); } if ($rule->dataHasChangedFor('uses_per_customer')) { $updateArray['usage_per_customer'] = $rule->getUsesPerCustomer(); } $ruleNewDate = new \Magento\Framework\Stdlib\DateTime\Date($rule->getToDate()); $ruleOldDate = new \Magento\Framework\Stdlib\DateTime\Date($rule->getOrigData('to_date')); if ($ruleNewDate->compare($ruleOldDate)) { $updateArray['expiration_date'] = $rule->getToDate(); } if (!empty($updateArray)) { $this->_getWriteAdapter()->update($this->getTable('salesrule_coupon'), $updateArray, array('rule_id = ?' => $rule->getId())); } return $this; }
/** * Validate rule data * * @param \Magento\Framework\Object $object * @return bool|string[] - return true if validation passed successfully. Array with errors description otherwise */ public function validateData(\Magento\Framework\Object $object) { $result = array(); $fromDate = $toDate = null; if ($object->hasFromDate() && $object->hasToDate()) { $fromDate = $object->getFromDate(); $toDate = $object->getToDate(); } if ($fromDate && $toDate) { $fromDate = new \Magento\Framework\Stdlib\DateTime\Date($fromDate, \Magento\Framework\Stdlib\DateTime::DATE_INTERNAL_FORMAT); $toDate = new \Magento\Framework\Stdlib\DateTime\Date($toDate, \Magento\Framework\Stdlib\DateTime::DATE_INTERNAL_FORMAT); if ($fromDate->compare($toDate) === 1) { $result[] = __('End Date must follow Start Date.'); } } if ($object->hasWebsiteIds()) { $websiteIds = $object->getWebsiteIds(); if (empty($websiteIds)) { $result[] = __('Websites must be specified.'); } } if ($object->hasCustomerGroupIds()) { $customerGroupIds = $object->getCustomerGroupIds(); if (empty($customerGroupIds)) { $result[] = __('Customer Groups must be specified.'); } } return !empty($result) ? $result : true; }
/** * Retrieve Date value for store * * @param int $storeId * @param string $date * @return string|null */ protected function getStoreDate($storeId, $date = null) { if (!isset($this->dates[$storeId])) { $timezone = $this->scopeConfig->getValue($this->localeDate->getDefaultTimezonePath(), \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId); $locale = $this->scopeConfig->getValue($this->localeResolver->getDefaultLocalePath(), \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId); $locale = new \Zend_Locale($locale); $dateObj = new \Magento\Framework\Stdlib\DateTime\Date(null, null, $locale); $dateObj->setTimezone($timezone); $this->dates[$storeId] = [$dateObj, $locale->getTranslation(null, 'date', $locale)]; } if (!$this->dateTime->isEmptyDate($date)) { list($dateObj, $format) = $this->dates[$storeId]; $dateObj->setDate($date, \Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT); return $dateObj->toString($format); } return null; }
/** * Check attribute unique value * * @param AbstractAttribute $attribute * @param \Magento\Framework\Object $object * @return bool */ public function checkAttributeUniqueValue(AbstractAttribute $attribute, $object) { $adapter = $this->_getReadAdapter(); $select = $adapter->select(); if ($attribute->getBackend()->getType() === 'static') { $value = $object->getData($attribute->getAttributeCode()); $bind = array('entity_type_id' => $this->getTypeId(), 'attribute_code' => trim($value)); $select->from($this->getEntityTable(), $this->getEntityIdField())->where('entity_type_id = :entity_type_id')->where($attribute->getAttributeCode() . ' = :attribute_code'); } else { $value = $object->getData($attribute->getAttributeCode()); if ($attribute->getBackend()->getType() == 'datetime') { $date = new \Magento\Framework\Stdlib\DateTime\Date($value, \Magento\Framework\Stdlib\DateTime::DATE_INTERNAL_FORMAT); $value = $date->toString(\Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT); } $bind = array('entity_type_id' => $this->getTypeId(), 'attribute_id' => $attribute->getId(), 'value' => trim($value)); $select->from($attribute->getBackend()->getTable(), $attribute->getBackend()->getEntityIdField())->where('entity_type_id = :entity_type_id')->where('attribute_id = :attribute_id')->where('value = :value'); } $data = $adapter->fetchCol($select, $bind); if ($object->getId()) { if (isset($data[0])) { return $data[0] == $object->getId(); } return true; } return !count($data); }
/** * Retrieve date in UTC timezone * * @param mixed $date * @return null|\Magento\Framework\Stdlib\DateTime\DateInterface */ protected function _dateToUtc($date) { if ($date === null) { return null; } $dateUtc = new \Magento\Framework\Stdlib\DateTime\Date($date); $dateUtc->setTimezone('Etc/UTC'); return $dateUtc; }