/** * Build product based on user request * * @param RequestInterface $request * @return \Magento\Catalog\Model\Product */ public function build(RequestInterface $request) { $productId = (int) $request->getParam('id'); /** @var $product \Magento\Catalog\Model\Product */ $product = $this->productFactory->create(); $product->setStoreId($request->getParam('store', 0)); $typeId = $request->getParam('type'); if (!$productId && $typeId) { $product->setTypeId($typeId); } $product->setData('_edit_mode', true); if ($productId) { try { $product->load($productId); } catch (\Exception $e) { $product->setTypeId(\Magento\Catalog\Model\Product\Type::DEFAULT_TYPE); $this->logger->logException($e); } } $setId = (int) $request->getParam('set'); if ($setId) { $product->setAttributeSetId($setId); } $this->registry->register('product', $product); $this->registry->register('current_product', $product); $this->wysiwygConfig->setStoreId($request->getParam('store')); return $product; }
/** * Get associated grouped products grid popup * * @return void */ public function execute() { $productId = (int) $this->getRequest()->getParam('id'); /** @var $product \Magento\Catalog\Model\Product */ $product = $this->factory->create(); $product->setStoreId($this->getRequest()->getParam('store', 0)); $typeId = $this->getRequest()->getParam('type'); if (!$productId && $typeId) { $product->setTypeId($typeId); } $product->setData('_edit_mode', true); if ($productId) { try { $product->load($productId); } catch (\Exception $e) { $product->setTypeId(\Magento\Catalog\Model\Product\Type::DEFAULT_TYPE); $this->logger->logException($e); } } $setId = (int) $this->getRequest()->getParam('set'); if ($setId) { $product->setAttributeSetId($setId); } $this->registry->register('current_product', $product); $this->_view->loadLayout(false); $this->_view->renderLayout(); }
/** * Get command object * * @param array $data command params * @param \Magento\Framework\Logger $logger * @return \Magento\Backend\Model\Menu\Builder\AbstractCommand */ protected function _getCommand($data, $logger) { $command = $this->_commandFactory->create($data['type'], array('data' => $data)); if (isset($this->_messagePatterns[$data['type']])) { $logger->logDebug(sprintf($this->_messagePatterns[$data['type']], $command->getId()), \Magento\Backend\Model\Menu::LOGGER_KEY); } return $command; }
public function testIndexActionException() { $this->request->expects($this->once())->method('isPost')->will($this->returnValue(true)); $exception = new \Exception(); $this->request->expects($this->once())->method('getPost')->will($this->throwException($exception)); $this->logger->expects($this->once())->method('logException')->with($this->identicalTo($exception)); $this->response->expects($this->once())->method('setHttpResponseCode')->with(500); $this->model->execute(); }
/** * Create order * * @param \Magento\Sales\Service\V1\Data\Order $orderDataObject * @return bool * @throws \Exception */ public function invoke(\Magento\Sales\Service\V1\Data\Order $orderDataObject) { try { $order = $this->orderConverter->getModel($orderDataObject); return (bool) $order->save(); } catch (\Exception $e) { $this->logger->logException($e); throw new \Exception(__('An error has occurred during order creation')); } }
/** * Send email about new order. * Process mail exception * * @param Order $order * @return bool */ public function send(Order $order) { try { $this->orderSender->send($order); } catch (\Magento\Framework\Mail\Exception $exception) { $this->logger->logException($exception); $this->messageManager->addWarning(__('You did not email your customer. Please check your email settings.')); return false; } return true; }
/** * Instantiate IPN model and pass IPN request to it * * @return void */ public function execute() { if (!$this->getRequest()->isPost()) { return; } try { $data = $this->getRequest()->getPost(); $this->_ipnFactory->create(array('data' => $data))->processIpnRequest(); } catch (\Exception $e) { $this->_logger->logException($e); } }
/** * Clear temporary directories * * @param \Magento\Install\Controller\Index\Index $subject * @param \Magento\Framework\App\RequestInterface $request * * @return void * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function beforeDispatch(\Magento\Install\Controller\Index\Index $subject, \Magento\Framework\App\RequestInterface $request) { if (!$this->appState->isInstalled()) { foreach ($this->varDirectory->read() as $dir) { if ($this->varDirectory->isDirectory($dir)) { try { $this->varDirectory->delete($dir); } catch (FilesystemException $exception) { $this->logger->log($exception->getMessage()); } } } } }
/** * Perform forced log data to file * * @param mixed $data * @return $this */ public function log($data = null) { if ($data === null) { $data = $this->_data; } else { if (!is_array($data)) { $data = array($data); } } $data = $this->_filterDebugData($data); $data['__pid'] = getmypid(); $this->_logger->logFile($data, \Zend_Log::DEBUG, $this->_logFileName); return $this; }
/** * Get storage instance * * @param array $arguments * @return \Magento\Store\Model\StoreManagerInterface * @throws \InvalidArgumentException */ public function get(array $arguments = array()) { $className = $this->_appState->isInstalled() ? $this->_installedStorageClassName : $this->_defaultStorageClassName; if (false == isset($this->_cache[$className])) { /** @var $storage \Magento\Store\Model\StoreManagerInterface */ $storage = $this->_objectManager->create($className, $arguments); if (false === $storage instanceof \Magento\Store\Model\StoreManagerInterface) { throw new \InvalidArgumentException($className . ' doesn\'t implement \\Magento\\Store\\Model\\StoreManagerInterface'); } $this->_cache[$className] = $storage; if ($className === $this->_installedStorageClassName) { $this->_reinitStores($storage, $arguments); $useSid = $this->_scopeConfig->isSetFlag(\Magento\Framework\Session\SidResolver::XML_PATH_USE_FRONTEND_SID, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storage->getStore()); $this->_sidResolver->setUseSessionInUrl($useSid); $this->_eventManager->dispatch('core_app_init_current_store_after'); $store = $storage->getStore(true); $logActive = $this->_scopeConfig->isSetFlag('dev/log/active', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $store); if ($logActive || $this->_appState->getMode() === \Magento\Framework\App\State::MODE_DEVELOPER) { $logFile = $this->_scopeConfig->getValue('dev/log/file', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $store); $logExceptionFile = $this->_scopeConfig->getValue('dev/log/exception_file', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $store); $this->_log->unsetLoggers(); $this->_log->addStreamLog(\Magento\Framework\Logger::LOGGER_SYSTEM, $logFile, $this->_writerModel); $this->_log->addStreamLog(\Magento\Framework\Logger::LOGGER_EXCEPTION, $logExceptionFile, $this->_writerModel); } } } return $this->_cache[$className]; }
/** * Retrieve transitions for offsets of given timezone * * @param string $timezone * @param mixed $from * @param mixed $to * @return array */ protected function _getTZOffsetTransitions($timezone, $from = null, $to = null) { $tzTransitions = array(); try { if (!empty($from)) { $from = new \Magento\Framework\Stdlib\DateTime\Date($from, \Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT); $from = $from->getTimestamp(); } $to = new \Magento\Framework\Stdlib\DateTime\Date($to, \Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT); $nextPeriod = $this->_getWriteAdapter()->formatDate($to->toString(\Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT)); $to = $to->getTimestamp(); $dtz = new \DateTimeZone($timezone); $transitions = $dtz->getTransitions(); $dateTimeObject = new \Magento\Framework\Stdlib\DateTime\Date('c'); for ($i = count($transitions) - 1; $i >= 0; $i--) { $tr = $transitions[$i]; try { $this->timezoneValidator->validate($tr['ts'], $to); } catch (\Magento\Framework\Stdlib\DateTime\Timezone\ValidationException $e) { continue; } $dateTimeObject->set($tr['time']); $tr['time'] = $this->_getWriteAdapter()->formatDate($dateTimeObject->toString(\Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT)); $tzTransitions[$tr['offset']][] = array('from' => $tr['time'], 'to' => $nextPeriod); if (!empty($from) && $tr['ts'] < $from) { break; } $nextPeriod = $tr['time']; } } catch (\Exception $e) { $this->_logger->logException($e); } return $tzTransitions; }
/** * Create Backup * * @return $this */ public function scheduledBackup() { if (!$this->_scopeConfig->isSetFlag(self::XML_PATH_BACKUP_ENABLED, ScopeInterface::SCOPE_STORE)) { return $this; } if ($this->_scopeConfig->isSetFlag(self::XML_PATH_BACKUP_MAINTENANCE_MODE, ScopeInterface::SCOPE_STORE)) { $this->maintenanceMode->set(true); } $type = $this->_scopeConfig->getValue(self::XML_PATH_BACKUP_TYPE, ScopeInterface::SCOPE_STORE); $this->_errors = array(); try { $backupManager = $this->_backupFactory->create($type)->setBackupExtension($this->_backupData->getExtensionByType($type))->setTime(time())->setBackupsDir($this->_backupData->getBackupsDir()); $this->_coreRegistry->register('backup_manager', $backupManager); if ($type != \Magento\Framework\Backup\Factory::TYPE_DB) { $backupManager->setRootDir($this->_filesystem->getPath(\Magento\Framework\App\Filesystem::ROOT_DIR))->addIgnorePaths($this->_backupData->getBackupIgnorePaths()); } $backupManager->create(); $message = $this->_backupData->getCreateSuccessMessageByType($type); $this->_logger->log($message); } catch (\Exception $e) { $this->_errors[] = $e->getMessage(); $this->_errors[] = $e->getTrace(); $this->_logger->log($e->getMessage(), \Zend_Log::ERR); $this->_logger->logException($e); } if ($this->_scopeConfig->isSetFlag(self::XML_PATH_BACKUP_MAINTENANCE_MODE, ScopeInterface::SCOPE_STORE)) { $this->maintenanceMode->set(false); } return $this; }
/** * {@inheritdoc} */ public function setAddress($cartId, $addressData) { /** @var \Magento\Sales\Model\Quote $quote */ $quote = $this->quoteLoader->load($cartId, $this->storeManager->getStore()->getId()); if ($quote->isVirtual()) { throw new NoSuchEntityException('Cart contains virtual product(s) only. Shipping address is not applicable'); } /** @var \Magento\Sales\Model\Quote\Address $address */ $address = $this->quoteAddressFactory->create(); $this->addressValidator->validate($addressData); if ($addressData->getId()) { $address->load($addressData->getId()); } $address = $this->addressConverter->convertDataObjectToModel($addressData, $address); $address->setSameAsBilling(0); $quote->setShippingAddress($address); $quote->setDataChanges(true); try { $quote->save(); } catch (\Exception $e) { $this->logger->logException($e); throw new InputException('Unable to save address. Please, check input data.'); } return $quote->getShippingAddress()->getId(); }
/** * {@inheritdoc} */ public function postToConsumer($consumerId, $endpointUrl) { try { $consumer = $this->_consumerFactory->create()->load($consumerId); if (!$consumer->getId()) { throw new \Magento\Framework\Oauth\Exception(__('A consumer with ID %1 does not exist', $consumerId), OauthInterface::ERR_PARAMETER_REJECTED); } $consumerData = $consumer->getData(); $verifier = $this->_tokenFactory->create()->createVerifierToken($consumerId); $storeBaseUrl = $this->_storeManager->getStore()->getBaseUrl(); $this->_httpClient->setUri($endpointUrl); $this->_httpClient->setParameterPost(array('oauth_consumer_key' => $consumerData['key'], 'oauth_consumer_secret' => $consumerData['secret'], 'store_base_url' => $storeBaseUrl, 'oauth_verifier' => $verifier->getVerifier())); $maxredirects = $this->_dataHelper->getConsumerPostMaxRedirects(); $timeout = $this->_dataHelper->getConsumerPostTimeout(); $this->_httpClient->setConfig(array('maxredirects' => $maxredirects, 'timeout' => $timeout)); $this->_httpClient->request(\Magento\Framework\HTTP\ZendClient::POST); return $verifier->getVerifier(); } catch (\Magento\Framework\Model\Exception $exception) { throw $exception; } catch (\Magento\Framework\Oauth\Exception $exception) { throw $exception; } catch (\Exception $exception) { $this->_logger->logException($exception); throw new \Magento\Framework\Oauth\Exception('Unable to post data to consumer due to an unexpected error'); } }
/** * Not Magento exception handling * * @param \Exception $exception * @param string $alternativeText * @param string $group * @return $this */ public function addException(\Exception $exception, $alternativeText, $group = null) { $message = sprintf('Exception message: %s%sTrace: %s', $exception->getMessage(), "\n", $exception->getTraceAsString()); $this->logger->logFile($message, \Zend_Log::DEBUG, Logger::LOGGER_EXCEPTION); $this->addMessage($this->messageFactory->create(MessageInterface::TYPE_ERROR, $alternativeText), $group); return $this; }
/** * @param \Magento\Sales\Service\V1\Data\Invoice $invoiceDataObject * @return bool * @throws \Exception */ public function invoke(\Magento\Sales\Service\V1\Data\Invoice $invoiceDataObject) { try { /** @var \Magento\Sales\Model\Order\Invoice $invoice */ $invoice = $this->invoiceConverter->getModel($invoiceDataObject); if (!$invoice) { return false; } $invoice->register(); $invoice->save(); return true; } catch (\Exception $e) { $this->logger->logException($e); throw new \Exception(__('An error has occurred during creating Invoice')); } }
/** * Invoke CreateShipment service * * @param \Magento\Sales\Service\V1\Data\Shipment $shipmentDataObject * @return bool * @throws \Exception */ public function invoke(\Magento\Sales\Service\V1\Data\Shipment $shipmentDataObject) { try { /** @var \Magento\Sales\Model\Order\Shipment $shipment */ $shipment = $this->shipmentConverter->getModel($shipmentDataObject); if (!$shipment) { return false; } $shipment->getOrder()->setIsInProcess(true); $shipment->register(); $shipment->save(); return true; } catch (\Exception $e) { $this->logger->logException($e); throw new \Exception(__('An error has occurred during creating Shipment')); } }
public function testLogFile() { $message = ['Wrong file name', 'Avoid using special chars']; $filename = 'custom_file.log'; $this->model->logFile($message, \Zend_Log::DEBUG); $this->model->logFile($message, \Zend_Log::DEBUG, $filename); $this->assertTrue($this->model->hasLog($filename)); }
/** * Log information about exception to exception log. * * @param \Exception $exception * @return string $reportId */ protected function _logException(\Exception $exception) { $exceptionClass = get_class($exception); $reportId = uniqid("webapi-"); $exceptionForLog = new $exceptionClass("Report ID: {$reportId}; Message: {$exception->getMessage()}", $exception->getCode()); $this->_logger->logException($exceptionForLog); return $reportId; }
/** * Instantiate IPN model and pass IPN request to it * * @return void */ public function execute() { if (!$this->getRequest()->isPost()) { return; } try { $data = $this->getRequest()->getPost(); $this->_ipnFactory->create(array('data' => $data))->processIpnRequest(); } catch (UnavailableException $e) { $this->_logger->logException($e); $this->getResponse()->setHeader('HTTP/1.1', '503 Service Unavailable')->sendResponse(); /** @todo eliminate usage of exit statement */ exit; } catch (\Exception $e) { $this->_logger->logException($e); $this->getResponse()->setHttpResponseCode(500); } }
/** * {@inheritdoc} */ public function removePermissions($integrationId) { try { $this->_deleteRole($integrationId); } catch (\Exception $e) { $this->_logger->logException($e); throw new LocalizedException('Error happened while deleting role and permissions. Check exception log for details.'); } }
/** * Notify user * * @param AbstractModel $model * @return bool * @throws \Magento\Framework\Mail\Exception */ public function notify(\Magento\Sales\Model\AbstractModel $model) { try { $this->sender->send($model); if (!$model->getEmailSent()) { return false; } $historyItem = $this->historyCollectionFactory->create()->getUnnotifiedForInstance($model); if ($historyItem) { $historyItem->setIsCustomerNotified(1); $historyItem->save(); } } catch (Exception $e) { $this->logger->logException($e); return false; } return true; }
public function testRenderMsrpNotRegisteredException() { $this->logger->expects($this->once())->method('logException'); $this->priceInfo->expects($this->once())->method('getPrice')->with($this->equalTo('msrp_price'))->will($this->throwException(new \InvalidArgumentException())); $result = $this->object->toHtml(); //assert price wrapper $this->assertStringStartsWith('<div', $result); //assert css_selector $this->assertRegExp('/[final_price]/', $result); }
/** * Check whether integration is inactive and don't allow using this integration in this case. * * It's ok that we break invocation chain since we're dealing with ACL here - if something is not allowed at any * point it couldn't be made allowed at some other point. * * @param \Magento\Authz\Service\AuthorizationV1 $subject * @param callable $proceed * @param mixed $resources * @param UserIdentifier $userIdentifier * * @return bool * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function aroundIsAllowed(\Magento\Authz\Service\AuthorizationV1 $subject, \Closure $proceed, $resources, \Magento\Authz\Model\UserIdentifier $userIdentifier = null) { /** @var UserIdentifier $userIdentifierObject */ $userIdentifierObject = $userIdentifier ?: $this->_userIdentifier; if ($userIdentifierObject->getUserType() !== UserIdentifier::USER_TYPE_INTEGRATION) { return $proceed($resources, $userIdentifier); } try { $integration = $this->_integrationService->get($userIdentifierObject->getUserId()); } catch (\Exception $e) { // Wrong integration ID or DB not reachable or whatever - give up and don't allow just in case $this->_logger->logException($e); return false; } if ($integration->getStatus() !== Integration::STATUS_ACTIVE) { return false; } return $proceed($resources, $userIdentifier); }
/** * @param \Magento\Sales\Service\V1\Data\Creditmemo $creditmemoDataObject * @throws \Exception * @return bool */ public function invoke(\Magento\Sales\Service\V1\Data\Creditmemo $creditmemoDataObject) { try { /** @var \Magento\Sales\Model\Order\Creditmemo $creditmemo */ $creditmemo = $this->creditmemoConverter->getModel($creditmemoDataObject); if (!$creditmemo) { return false; } if (!$creditmemo->isValidGrandTotal()) { return false; } $creditmemo->register(); $creditmemo->save(); return true; } catch (\Exception $e) { $this->logger->logException($e); throw new \Exception(__('An error has occurred during creating Creditmemo')); } }
/** * Filter the string as template. * Rewrited for logging exceptions * * @param string $value * @return string * @SuppressWarnings(PHPMD.ConstructorWithNameAsEnclosingClass) */ public function filter($value) { try { $value = parent::filter($value); } catch (\Exception $e) { $value = ''; $this->_logger->logException($e); } return $value; }
/** * Show error as exception or log it * * @param string $errorMessage * @throws \Exception * @return void */ protected function _processError($errorMessage) { if ($this->_appState->getMode() == \Magento\Framework\App\State::MODE_DEVELOPER) { parent::_processError($errorMessage); } else { $exception = new \Exception($errorMessage); $errorMessage .= $exception->getTraceAsString(); $this->_logger->log($errorMessage, \Zend_Log::ERR); } }
/** * Run module modification files. Return version of last applied upgrade (false if no upgrades applied) * @param string $actionType * @param string $fromVersion * @param string $toVersion * @return false|string * @throws \Magento\Framework\Exception */ protected function _modifyResourceDb($actionType, $fromVersion, $toVersion) { switch ($actionType) { case self::TYPE_DB_INSTALL: case self::TYPE_DB_UPGRADE: $files = $this->_getAvailableDbFiles($actionType, $fromVersion, $toVersion); break; case self::TYPE_DATA_INSTALL: case self::TYPE_DATA_UPGRADE: $files = $this->_getAvailableDataFiles($actionType, $fromVersion, $toVersion); break; default: $files = array(); break; } if (empty($files) || !$this->getConnection()) { return false; } $version = false; foreach ($files as $file) { $fileName = $file['fileName']; $fileType = pathinfo($fileName, PATHINFO_EXTENSION); $this->getConnection()->disallowDdlCache(); try { switch ($fileType) { case 'php': $result = $this->_includeFile($fileName); break; case 'sql': $sql = $this->modulesDir->readFile($this->modulesDir->getRelativePath($fileName)); if (!empty($sql)) { $result = $this->run($sql); } else { $result = true; } break; default: $result = false; break; } if ($result) { $this->_setResourceVersion($actionType, $file['toVersion']); $this->_logger->log($fileName); } else { $this->_logger->log("Failed resource setup: {$fileName}"); } } catch (\Exception $e) { throw new \Magento\Framework\Exception(sprintf('Error in file: "%s" - %s', $fileName, $e->getMessage()), 0, $e); } $version = $file['toVersion']; $this->getConnection()->allowDdlCache(); } return $version; }
/** * Get store model * * @param null|string|bool|int|\\Magento\Store\Model\Store $store * @return \\Magento\Store\Model\Store */ protected function getStore($store = null) { try { if (!$store instanceof \Magento\Store\Model\Store) { $store = $this->storeManager->getStore($store); } } catch (\Exception $e) { $this->logger->logException($e); $store = $this->storeManager->getStore(); } return $store; }
/** * Attempt to merge assets, falling back to original non-merged ones, if merging fails * * @return void */ protected function initialize() { if (!$this->isInitialized) { $this->isInitialized = true; try { $mergedAsset = $this->createMergedAsset($this->assets); $this->mergeStrategy->merge($this->assets, $mergedAsset); $this->assets = array($mergedAsset); } catch (\Exception $e) { $this->logger->logException($e); } } }