/** * Returns block content depends on ajax request * * @return void */ public function execute() { if (!$this->getRequest()->isAjax()) { $this->_forward('noroute'); return; } // disable profiling during private content handling AJAX call \Magento\Framework\Profiler::reset(); $currentRoute = $this->getRequest()->getRouteName(); $currentControllerName = $this->getRequest()->getControllerName(); $currentActionName = $this->getRequest()->getActionName(); $currentRequestUri = $this->getRequest()->getRequestUri(); $origRequest = $this->getRequest()->getParam('originalRequest'); $origRequest = json_decode($origRequest, true); $this->getRequest()->setRouteName($origRequest['route']); $this->getRequest()->setControllerName($origRequest['controller']); $this->getRequest()->setActionName($origRequest['action']); $this->getRequest()->setRequestUri($origRequest['uri']); /** @var \Magento\Framework\View\Element\BlockInterface[] $blocks */ $blocks = $this->_getBlocks(); $data = []; foreach ($blocks as $blockName => $blockInstance) { $data[$blockName] = $blockInstance->toHtml(); } $this->getRequest()->setRouteName($currentRoute); $this->getRequest()->setControllerName($currentControllerName); $this->getRequest()->setActionName($currentActionName); $this->getRequest()->setRequestUri($currentRequestUri); $this->getResponse()->setPrivateHeaders(\Magento\PageCache\Helper\Data::PRIVATE_MAX_AGE_CACHE); $this->translateInline->processResponseBody($data); $this->getResponse()->appendBody(json_encode($data)); }
/** * * {@inheritdoc} */ public function logStats($type, $sql, $bind = [], $result = null) { $log = []; //Change approach to "around" and then break return string into MySQL columns // as right now we cannot get time of query execution //Problem remains how to pass the YES/NO on time and full backtrace // maybe its best to simply record all and then remove it from __destruct // as in __destruct we have access to helper // trace log and all log simply kill the database size, thus we need them as config self::$counter++; \Magento\Framework\Profiler::start('foggyline_sentinel_logStats_' . self::$counter); $log['type'] = $type; $log['time'] = sprintf('%.4f', microtime(true) - $this->timer); $log['sql'] = $sql; $log['bind'] = var_export($bind, true); if ($result instanceof \Zend_Db_Statement_Pdo) { $log['row_count'] = $result->rowCount(); } /** * When backtrace is assigned, it consumes roughly: * - 0.3 seconds on homepage, * - 0.5 seconds on admin product page * * Problem here is that we cannot control Debug::backtrace via Magento admin config, so we have to leave it * either running or comment it out. If we leave it running, we can add some minor tome to overhead but we * can then use $this->helper->getQueryLogCallStack(); to either save it in database or not. * * Backtrace adds enormous amount of data to database. We are talking MB of data just in 3-4 page requests. * Thus it is highly important be very careful with full log stack (backtrace) loging to dataabse. */ $log['backtrace'] = \Magento\Framework\Debug::backtrace(true, false); $this->queryLogs[] = $log; \Magento\Framework\Profiler::stop('foggyline_sentinel_logStats_' . self::$counter); }
/** * Run application * * @param string $applicationName * @param array $arguments * @return void */ public function run($applicationName, array $arguments = array()) { try { \Magento\Framework\Profiler::start('magento'); if (!$this->_locator) { $locatorFactory = new \Magento\Framework\App\ObjectManagerFactory(); $this->_locator = $locatorFactory->create($this->_rootDir, $this->_parameters); } $application = $this->_locator->create($applicationName, $arguments); $response = $application->launch(); \Magento\Framework\Profiler::stop('magento'); $response->sendResponse(); } catch (\Exception $exception) { if (isset($this->_parameters[State::PARAM_MODE]) && $this->_parameters[State::PARAM_MODE] == State::MODE_DEVELOPER) { echo $exception->getMessage() . "\n\n"; echo $exception->getTraceAsString(); } else { $message = "Error happened during application run.\n"; try { if (!$this->_locator) { throw new \DomainException(); } $this->_locator->get('Magento\\Framework\\Logger')->logException($exception); } catch (\Exception $e) { $message .= "Could not write error message to log. Please use developer mode to see the message.\n"; } echo $message; } } }
public function execute() { $resultPage = $this->resultPageFactory->create(); \Magento\Framework\Profiler::start('foggyline:office'); $this->logger->log(\Monolog\Logger::DEBUG, 'debug msg'); $this->logger->log(\Monolog\Logger::INFO, 'info msg'); $this->logger->log(\Monolog\Logger::NOTICE, 'notice msg'); $this->logger->log(\Monolog\Logger::WARNING, 'warning msg'); $this->logger->log(\Monolog\Logger::ERROR, 'error msg'); $this->logger->log(\Monolog\Logger::CRITICAL, 'critical msg'); $this->logger->log(\Monolog\Logger::ALERT, 'alert msg'); $this->logger->log(\Monolog\Logger::EMERGENCY, 'emergency msg'); $this->logger->debug('debug msg'); $this->logger->info('info msg'); $this->logger->notice('notice msg'); $this->logger->warning('warning msg'); $this->logger->error('error msg'); $this->logger->critical('critical msg'); $this->logger->alert('alert msg'); $this->logger->emergency('emergency msg'); sleep(2); /* code block or single expression here */ \Magento\Framework\Profiler::stop('foggyline:office'); return $resultPage; }
/** * Register profiler driver to involve it into the results processing */ protected function _registerDriver() { if (!$this->_isDriverRegistered) { $this->_isDriverRegistered = true; \Magento\Framework\Profiler::add($this->_driver); } }
/** * Get html code * * @return string */ protected function _toHtml() { /* @var $template \Magento\Newsletter\Model\Template */ $template = $this->_templateFactory->create(); if ($id = (int) $this->getRequest()->getParam('id')) { $template->load($id); } else { $template->setTemplateType($this->getRequest()->getParam('type')); $template->setTemplateText($this->getRequest()->getParam('text')); $template->setTemplateStyles($this->getRequest()->getParam('styles')); } $storeId = (int) $this->getRequest()->getParam('store_id'); if (!$storeId) { $storeId = $this->_storeManager->getDefaultStoreView()->getId(); } \Magento\Framework\Profiler::start("newsletter_template_proccessing"); $vars = array(); $vars['subscriber'] = $this->_subscriberFactory->create(); if ($this->getRequest()->getParam('subscriber')) { $vars['subscriber']->load($this->getRequest()->getParam('subscriber')); } $template->emulateDesign($storeId); $templateProcessed = $this->_appState->emulateAreaCode(\Magento\Newsletter\Model\Template::DEFAULT_DESIGN_AREA, array($template, 'getProcessedTemplate'), array($vars, true)); $template->revertDesign(); if ($template->isPlain()) { $templateProcessed = "<pre>" . htmlspecialchars($templateProcessed) . "</pre>"; } \Magento\Framework\Profiler::stop("newsletter_template_proccessing"); return $templateProcessed; }
/** * Prepare html output * * @return string */ protected function _toHtml() { /** @var $template \Magento\Email\Model\Template */ $template = $this->_emailFactory->create(['data' => ['area' => \Magento\Framework\App\Area::AREA_FRONTEND]]); $id = (int) $this->getRequest()->getParam('id'); if ($id) { $template->load($id); } else { $template->setTemplateType($this->getRequest()->getParam('type')); $template->setTemplateText($this->getRequest()->getParam('text')); $template->setTemplateStyles($this->getRequest()->getParam('styles')); } $template->setTemplateText($this->_maliciousCode->filter($template->getTemplateText())); \Magento\Framework\Profiler::start("email_template_proccessing"); $vars = []; $store = $this->getAnyStoreView(); $storeId = $store ? $store->getId() : null; $template->setDesignConfig(['area' => $this->_design->getArea(), 'store' => $storeId]); $templateProcessed = $template->getProcessedTemplate($vars, true); if ($template->isPlain()) { $templateProcessed = "<pre>" . htmlspecialchars($templateProcessed) . "</pre>"; } \Magento\Framework\Profiler::stop("email_template_proccessing"); return $templateProcessed; }
/** * Perform action and generate response * * @param RequestInterface $request * @return ResponseInterface|\Magento\Framework\Controller\ResultInterface * @throws \LogicException */ public function dispatch(RequestInterface $request) { \Magento\Framework\Profiler::start('routers_match'); $routingCycleCounter = 0; $result = null; while (!$request->isDispatched() && $routingCycleCounter++ < 100) { /** @var \Magento\Framework\App\RouterInterface $router */ foreach ($this->_routerList as $router) { try { $actionInstance = $router->match($request); if ($actionInstance) { $request->setDispatched(true); $this->response->setNoCacheHeaders(); if ($actionInstance instanceof \Magento\Framework\App\Action\AbstractAction) { $result = $actionInstance->dispatch($request); } else { $result = $actionInstance->execute(); } break; } } catch (\Magento\Framework\Exception\NotFoundException $e) { $request->initForward(); $request->setActionName('noroute'); $request->setDispatched(false); break; } } } \Magento\Framework\Profiler::stop('routers_match'); if ($routingCycleCounter > 100) { throw new \LogicException('Front controller reached 100 router match iterations'); } return $result; }
/** * Get html code * * @return string */ protected function _toHtml() { /* @var $template \Magento\Newsletter\Model\Template */ $template = $this->_templateFactory->create(); if ($id = (int) $this->getRequest()->getParam('id')) { $this->loadTemplate($template, $id); } else { $previewData = $this->getPreviewData(); $template->setTemplateType($previewData['type']); $template->setTemplateText($previewData['text']); $template->setTemplateStyles($previewData['styles']); } \Magento\Framework\Profiler::start($this->profilerName); $vars = []; $vars['subscriber'] = $this->_subscriberFactory->create(); if ($this->getRequest()->getParam('subscriber')) { $vars['subscriber']->load($this->getRequest()->getParam('subscriber')); } $template->emulateDesign($this->getStoreId()); $templateProcessed = $this->_appState->emulateAreaCode(\Magento\Newsletter\Model\Template::DEFAULT_DESIGN_AREA, [$template, 'getProcessedTemplate'], [$vars]); $template->revertDesign(); if ($template->isPlain()) { $templateProcessed = "<pre>" . htmlspecialchars($templateProcessed) . "</pre>"; } \Magento\Framework\Profiler::stop($this->profilerName); return $templateProcessed; }
/** * Apply rewrites to current request * * @param \Magento\Framework\App\RequestInterface $request * @return void */ public function applyRewrites(\Magento\Framework\App\RequestInterface $request) { // URL rewrite if (!$request->isStraight()) { \Magento\Framework\Profiler::start('db_url_rewrite'); /** @var $urlRewrite \Magento\UrlRewrite\Model\UrlRewrite */ $urlRewrite = $this->_rewriteFactory->create(); $urlRewrite->rewrite($request); \Magento\Framework\Profiler::stop('db_url_rewrite'); } }
protected function setUp() { $this->_eventManagerMock = $this->getMock('Magento\\Framework\\Event\\ManagerInterface', [], [], '', false); $this->_actionFlagMock = $this->getMock('Magento\\Framework\\App\\ActionFlag', [], [], '', false); $this->_redirectMock = $this->getMock('Magento\\Framework\\App\\Response\\RedirectInterface', [], [], '', false); $this->_requestMock = $this->getMock('Magento\\Framework\\App\\RequestInterface', ['getFullActionName', 'getRouteName', 'isDispatched', 'initForward', 'setParams', 'setControllerName', 'setDispatched', 'getModuleName', 'setModuleName', 'getActionName', 'setActionName', 'getParam', 'getCookie'], [], '', false); $this->_responseMock = $this->getMock('Magento\\Framework\\App\\ResponseInterface', [], [], '', false); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->action = $this->objectManagerHelper->getObject('Magento\\Framework\\App\\Action\\ActionFake', ['request' => $this->_requestMock, 'response' => $this->_responseMock, 'eventManager' => $this->_eventManagerMock, 'redirect' => $this->_redirectMock, 'actionFlag' => $this->_actionFlagMock]); \Magento\Framework\Profiler::disable(); }
/** * @SuppressWarnings(PHPMD.StaticAccess) * * {@inheritdoc} */ public function query(RequestInterface $request) { \Magento\Framework\Profiler::start('ES:Execute Search Query'); try { $searchResponse = $this->doSearch($request); } catch (\Exception $e) { $searchResponse = []; $this->logger->error($e->getMessage()); } \Magento\Framework\Profiler::stop('ES:Execute Search Query'); return $this->responseFactory->create(['searchResponse' => $searchResponse]); }
/** * Perform action and generate response * * @param RequestInterface $request * @return ResponseInterface|\Magento\Framework\Controller\ResultInterface * @throws \LogicException */ public function dispatch(RequestInterface $request) { \Magento\Framework\Profiler::start('routers_match'); $routingCycleCounter = 0; $result = null; while (!$request->isDispatched() && $routingCycleCounter++ < 100) { $result = $this->processRequest($request); } \Magento\Framework\Profiler::stop('routers_match'); if ($routingCycleCounter > 100) { throw new \LogicException('Front controller reached 100 router match iterations'); } return $result; }
/** * Dispatch event * * Calls all observer callbacks registered for this event * and multiple observers matching event name pattern * * @param string $eventName * @param array $data * @return void */ public function dispatch($eventName, array $data = array()) { \Magento\Framework\Profiler::start('EVENT:' . $eventName, array('group' => 'EVENT', 'name' => $eventName)); foreach ($this->_eventConfig->getObservers($eventName) as $observerConfig) { $event = new \Magento\Framework\Event($data); $event->setName($eventName); $wrapper = new Observer(); $wrapper->setData(array_merge(array('event' => $event), $data)); \Magento\Framework\Profiler::start('OBSERVER:' . $observerConfig['name']); $this->_invoker->dispatch($observerConfig, $wrapper); \Magento\Framework\Profiler::stop('OBSERVER:' . $observerConfig['name']); } \Magento\Framework\Profiler::stop('EVENT:' . $eventName); }
protected function setUp() { $this->_eventManagerMock = $this->getMock('Magento\\Framework\\Event\\ManagerInterface', [], [], '', false); $this->_actionFlagMock = $this->getMock('Magento\\Framework\\App\\ActionFlag', [], [], '', false); $this->_redirectMock = $this->getMock('Magento\\Framework\\App\\Response\\RedirectInterface', [], [], '', false); $this->_requestMock = $this->getMock('Magento\\Framework\\App\\RequestInterface', ['getFullActionName', 'getRouteName', 'isDispatched', 'initForward', 'setParams', 'setControllerName', 'setDispatched', 'getModuleName', 'setModuleName', 'getActionName', 'setActionName', 'getParam', 'getCookie'], [], '', false); $this->_responseMock = $this->getMock('Magento\\Framework\\App\\ResponseInterface', [], [], '', false); $this->pageConfigMock = $this->getMock('Magento\\Framework\\View\\Page\\Config', ['getConfig'], [], '', false); $this->viewMock = $this->getMock('Magento\\Framework\\App\\ViewInterface'); $this->viewMock->expects($this->any())->method('getPage')->will($this->returnValue($this->pageConfigMock)); $this->pageConfigMock->expects($this->any())->method('getConfig')->will($this->returnValue(1)); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->action = $this->objectManagerHelper->getObject('Magento\\Framework\\App\\Action\\ActionFake', ['request' => $this->_requestMock, 'response' => $this->_responseMock, 'eventManager' => $this->_eventManagerMock, 'redirect' => $this->_redirectMock, 'actionFlag' => $this->_actionFlagMock, 'view' => $this->viewMock]); \Magento\Framework\Profiler::disable(); }
protected function setUp() { $this->_eventManagerMock = $this->getMock('Magento\\Framework\\Event\\ManagerInterface', [], [], '', false); $this->_actionFlagMock = $this->getMock('Magento\\Framework\\App\\ActionFlag', [], [], '', false); $this->_redirectMock = $this->getMock('Magento\\Framework\\App\\Response\\RedirectInterface', [], [], '', false); $this->_requestMock = $this->getMockBuilder('Magento\\Framework\\App\\Request\\Http')->disableOriginalConstructor()->getMock(); $this->_responseMock = $this->getMock('Magento\\Framework\\App\\ResponseInterface', [], [], '', false); $this->pageConfigMock = $this->getMock('Magento\\Framework\\View\\Page\\Config', ['getConfig'], [], '', false); $this->viewMock = $this->getMock('Magento\\Framework\\App\\ViewInterface'); $this->viewMock->expects($this->any())->method('getPage')->will($this->returnValue($this->pageConfigMock)); $this->pageConfigMock->expects($this->any())->method('getConfig')->will($this->returnValue(1)); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->action = $this->objectManagerHelper->getObject('Magento\\Framework\\App\\Test\\Unit\\Action\\ActionFake', ['request' => $this->_requestMock, 'response' => $this->_responseMock, 'eventManager' => $this->_eventManagerMock, 'redirect' => $this->_redirectMock, 'actionFlag' => $this->_actionFlagMock, 'view' => $this->viewMock]); \Magento\Framework\Profiler::disable(); }
public function dispatch($eventName, array $data = []) { \Magento\Framework\Profiler::start('EVENT:' . $eventName, ['group' => 'EVENT', 'name' => $eventName]); foreach ($this->_eventConfig->getObservers($eventName) as $observerConfig) { $event = new \Magento\Framework\Event($data); $event->setName($eventName); $wrapper = new \Magento\Framework\Event\Observer(); $wrapper->setData(array_merge(['event' => $event], $data)); \Magento\Framework\Profiler::start('OBSERVER:' . $observerConfig['name']); $this->_invoker->dispatch($observerConfig, $wrapper); $observerConfig['method'] = 'execute'; $this->_devHelper->setObserverDetails($observerConfig, $eventName); \Magento\Framework\Profiler::stop('OBSERVER:' . $observerConfig['name']); } \Magento\Framework\Profiler::stop('EVENT:' . $eventName); }
/** * @param string $method * @param array $params * @param \Zend_Cache_Backend $cacheBackend * @param \Zend_Cache_Core $cacheFrontend * @param string $expectedProfileId * @param array $expectedProfilerTags * @param mixed $expectedResult * @dataProvider proxyMethodDataProvider */ public function testProxyMethod($method, $params, $cacheBackend, $cacheFrontend, $expectedProfileId, $expectedProfilerTags, $expectedResult) { // Cache frontend setup $frontendMock = $this->getMock('Magento\\Framework\\Cache\\FrontendInterface'); $frontendMock->expects($this->any())->method('getBackend')->will($this->returnValue($cacheBackend)); $frontendMock->expects($this->any())->method('getLowLevelFrontend')->will($this->returnValue($cacheFrontend)); // Profiler setup $driver = $this->getMock('Magento\\Framework\\Profiler\\DriverInterface'); $driver->expects($this->once())->method('start')->with($expectedProfileId, $expectedProfilerTags); $driver->expects($this->once())->method('stop')->with($expectedProfileId); \Magento\Framework\Profiler::add($driver); // Test $object = new \Magento\Framework\Cache\Frontend\Decorator\Profiler($frontendMock, ['Zend_Cache_Backend_']); $helper = new \Magento\TestFramework\Helper\ProxyTesting(); $result = $helper->invokeWithExpectations($object, $frontendMock, $method, $params, $expectedResult); $this->assertSame($expectedResult, $result); }
/** * Dispatches an event to observer's callback * * @param Event $event * @return $this */ public function dispatch(Event $event) { if (!$this->isValidFor($event)) { return $this; } $callback = $this->getCallback(); $this->setEvent($event); $_profilerKey = 'OBSERVER: '; if (is_object($callback[0])) { $_profilerKey .= get_class($callback[0]); } else { $_profilerKey .= (string) $callback[0]; } $_profilerKey .= ' -> ' . $callback[1]; \Magento\Framework\Profiler::start($_profilerKey); call_user_func($callback, $this); \Magento\Framework\Profiler::stop($_profilerKey); return $this; }
/** * Reindex all data what process is responsible * * @return void */ public function execute() { /** @var $process \Magento\Index\Model\Process */ $process = $this->_initProcess(); if ($process) { try { \Magento\Framework\Profiler::start('__INDEX_PROCESS_REINDEX_ALL__'); $process->reindexEverything(); \Magento\Framework\Profiler::stop('__INDEX_PROCESS_REINDEX_ALL__'); $this->messageManager->addSuccess(__('%1 index was rebuilt.', $process->getIndexer()->getName())); } catch (\Magento\Framework\Model\Exception $e) { $this->messageManager->addError($e->getMessage()); } catch (\Exception $e) { $this->messageManager->addException($e, __('There was a problem with reindexing process.')); } } else { $this->messageManager->addError(__('Cannot initialize the indexer process.')); } $this->_redirect('adminhtml/*/list'); }
/** * Finds requested resource and provides it to the client * * @return \Magento\Framework\App\ResponseInterface * @throws \Exception */ public function launch() { // disabling profiling when retrieving static resource \Magento\Framework\Profiler::reset(); $appMode = $this->state->getMode(); if ($appMode == \Magento\Framework\App\State::MODE_PRODUCTION) { $this->response->setHttpResponseCode(404); } else { $path = $this->request->get('resource'); $params = $this->parsePath($path); $this->state->setAreaCode($params['area']); $this->objectManager->configure($this->configLoader->load($params['area'])); $file = $params['file']; unset($params['file']); $asset = $this->assetRepo->createAsset($file, $params); $this->response->setFilePath($asset->getSourceFile()); $this->publisher->publish($asset); } return $this->response; }
/** * @inheritdoc */ public function getCurrency($currency) { \Magento\Framework\Profiler::start('locale/currency'); if (!isset(self::$_currencyCache[$this->_localeResolver->getLocale()][$currency])) { $options = []; try { $currencyObject = $this->_currencyFactory->create(['options' => $currency, 'locale' => $this->_localeResolver->getLocale()]); } catch (\Exception $e) { $currencyObject = $this->_currencyFactory->create(['options' => $this->getDefaultCurrency(), 'locale' => $this->_localeResolver->getLocale()]); $options[self::CURRENCY_OPTION_NAME] = $currency; $options[self::CURRENCY_OPTION_CURRENCY] = $currency; $options[self::CURRENCY_OPTION_SYMBOL] = $currency; } $options = new \Magento\Framework\Object($options); $this->_eventManager->dispatch('currency_display_options_forming', ['currency_options' => $options, 'base_code' => $currency]); $currencyObject->setFormat($options->toArray()); self::$_currencyCache[$this->_localeResolver->getLocale()][$currency] = $currencyObject; } \Magento\Framework\Profiler::stop('locale/currency'); return self::$_currencyCache[$this->_localeResolver->getLocale()][$currency]; }
/** * Prepare html output * * @return string */ protected function _toHtml() { $storeId = $this->getAnyStoreView()->getId(); /** @var $template \Magento\Email\Model\Template */ $template = $this->_emailFactory->create(); if ($id = (int) $this->getRequest()->getParam('id')) { $template->load($id); } else { $template->setTemplateType($this->getRequest()->getParam('type')); $template->setTemplateText($this->getRequest()->getParam('text')); $template->setTemplateStyles($this->getRequest()->getParam('styles')); } $template->setTemplateText($this->_maliciousCode->filter($template->getTemplateText())); \Magento\Framework\Profiler::start($this->profilerName); $template->emulateDesign($storeId); $templateProcessed = $this->_appState->emulateAreaCode(\Magento\Email\Model\AbstractTemplate::DEFAULT_DESIGN_AREA, [$template, 'getProcessedTemplate']); $template->revertDesign(); if ($template->isPlain()) { $templateProcessed = "<pre>" . htmlspecialchars($templateProcessed) . "</pre>"; } \Magento\Framework\Profiler::stop($this->profilerName); return $templateProcessed; }
/** * Shopping cart display action * * @return void */ public function execute() { if ($this->cart->getQuote()->getItemsCount()) { $this->cart->init(); $this->cart->save(); if (!$this->cart->getQuote()->validateMinimumAmount()) { $currencyCode = $this->_objectManager->get('Magento\\Framework\\StoreManagerInterface')->getStore()->getCurrentCurrencyCode(); $minimumAmount = $this->_objectManager->get('Magento\\Framework\\Locale\\CurrencyInterface')->getCurrency($currencyCode)->toCurrency($this->_scopeConfig->getValue('sales/minimum_order/amount', \Magento\Store\Model\ScopeInterface::SCOPE_STORE)); $warning = $this->_scopeConfig->getValue('sales/minimum_order/description', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) ? $this->_scopeConfig->getValue('sales/minimum_order/description', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) : __('Minimum order amount is %1', $minimumAmount); $this->messageManager->addNotice($warning); } } // Compose array of messages to add $messages = array(); /** @var \Magento\Framework\Message\MessageInterface $message */ foreach ($this->cart->getQuote()->getMessages() as $message) { if ($message) { // Escape HTML entities in quote message to prevent XSS $message->setText($this->_objectManager->get('Magento\\Framework\\Escaper')->escapeHtml($message->getText())); $messages[] = $message; } } $this->messageManager->addUniqueMessages($messages); /** * if customer enteres shopping cart we should mark quote * as modified bc he can has checkout page in another window. */ $this->_checkoutSession->setCartWasUpdated(true); \Magento\Framework\Profiler::start(__METHOD__ . 'cart_display'); $this->_view->loadLayout(); $layout = $this->_view->getLayout(); $layout->initMessages(); $layout->getBlock('head')->setTitle(__('Shopping Cart')); $this->_view->renderLayout(); \Magento\Framework\Profiler::stop(__METHOD__ . 'cart_display'); }
/** * Add products to items and item options * * @return $this * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ protected function _assignProducts() { \Magento\Framework\Profiler::start('QUOTE:' . __METHOD__, ['group' => 'QUOTE', 'method' => __METHOD__]); $productIds = []; foreach ($this as $item) { $productIds[] = (int) $item->getProductId(); } $this->_productIds = array_merge($this->_productIds, $productIds); $productCollection = $this->_productCollectionFactory->create()->setStoreId($this->getStoreId())->addIdFilter($this->_productIds)->addAttributeToSelect($this->_quoteConfig->getProductAttributes())->addOptionsToResult()->addStoreFilter()->addUrlRewrite()->addTierPriceData(); $this->_eventManager->dispatch('prepare_catalog_product_collection_prices', ['collection' => $productCollection, 'store_id' => $this->getStoreId()]); $this->_eventManager->dispatch('sales_quote_item_collection_products_after_load', ['collection' => $productCollection]); $recollectQuote = false; foreach ($this as $item) { $product = $productCollection->getItemById($item->getProductId()); if ($product) { $product->setCustomOptions([]); $qtyOptions = []; $optionProductIds = []; foreach ($item->getOptions() as $option) { /** * Call type-specific logic for product associated with quote item */ $product->getTypeInstance()->assignProductToOption($productCollection->getItemById($option->getProductId()), $option, $product); if (is_object($option->getProduct()) && $option->getProduct()->getId() != $product->getId()) { $optionProductIds[$option->getProduct()->getId()] = $option->getProduct()->getId(); } } if ($optionProductIds) { foreach ($optionProductIds as $optionProductId) { $qtyOption = $item->getOptionByCode('product_qty_' . $optionProductId); if ($qtyOption) { $qtyOptions[$optionProductId] = $qtyOption; } } } $item->setQtyOptions($qtyOptions)->setProduct($product); } else { $item->isDeleted(true); $recollectQuote = true; } $item->checkData(); } if ($recollectQuote && $this->_quote) { $this->_quote->collectTotals(); } \Magento\Framework\Profiler::stop('QUOTE:' . __METHOD__); return $this; }
/** * Retrieve category id URL * * @return string */ public function getCategoryIdUrl() { Profiler::start('REGULAR: ' . __METHOD__, ['group' => 'REGULAR', 'method' => __METHOD__]); $urlKey = $this->getUrlKey() ? $this->getUrlKey() : $this->formatUrlKey($this->getName()); $url = $this->getUrlInstance()->getUrl('catalog/category/view', ['s' => $urlKey, 'id' => $this->getId()]); Profiler::stop('REGULAR: ' . __METHOD__); return $url; }
/** * Preload entity type attributes for performance optimization * * @param mixed $entityType * @param mixed $attributes * @return $this */ public function preloadAttributes($entityType, $attributes) { if (is_string($attributes)) { $attributes = array($attributes); } $entityType = $this->getEntityType($entityType); $entityTypeCode = $entityType->getEntityTypeCode(); if (!isset($this->_preloadedAttributes[$entityTypeCode])) { $this->_preloadedAttributes[$entityTypeCode] = $attributes; } else { $attributes = array_diff($attributes, $this->_preloadedAttributes[$entityTypeCode]); $this->_preloadedAttributes[$entityTypeCode] = array_merge($this->_preloadedAttributes[$entityTypeCode], $attributes); } if (empty($attributes)) { return $this; } \Magento\Framework\Profiler::start('EAV: ' . __METHOD__ . ':' . $entityTypeCode, array('group' => 'EAV', 'method' => __METHOD__, 'entity_type_code' => $entityTypeCode)); $attributesInfo = $this->_universalFactory->create($entityType->getEntityAttributeCollection())->setEntityTypeFilter($entityType)->setCodeFilter($attributes)->getData(); if (!$attributesInfo) { \Magento\Framework\Profiler::stop('EAV: ' . __METHOD__ . ':' . $entityTypeCode); return $this; } $attributesData = $codes = array(); foreach ($attributesInfo as $attribute) { if (empty($attribute['attribute_model'])) { $attribute['attribute_model'] = $entityType->getAttributeModel(); } $attributeCode = $attribute['attribute_code']; $attributeId = $attribute['attribute_id']; $this->_addAttributeReference($attributeId, $attributeCode, $entityTypeCode); $attributesData[$attributeCode] = $attribute; $codes[] = $attributeCode; } $this->_attributeData[$entityTypeCode] = $attributesData; \Magento\Framework\Profiler::stop('EAV: ' . __METHOD__ . ':' . $entityTypeCode); return $this; }
/** * Create structure of elements from the loaded XML configuration * * @return void */ public function generateElements() { \Magento\Framework\Profiler::start(__CLASS__ . '::' . __METHOD__); $cacheId = 'structure_' . $this->getUpdate()->getCacheId(); $result = $this->cache->load($cacheId); if ($result) { $this->readerContext = unserialize($result); } else { \Magento\Framework\Profiler::start('build_structure'); $this->readerPool->interpret($this->getReaderContext(), $this->getNode()); \Magento\Framework\Profiler::stop('build_structure'); $this->cache->save(serialize($this->getReaderContext()), $cacheId, $this->getUpdate()->getHandles()); } $generatorContext = $this->generatorContextFactory->create(['structure' => $this->structure, 'layout' => $this]); \Magento\Framework\Profiler::start('generate_elements'); $this->generatorPool->process($this->getReaderContext(), $generatorContext); \Magento\Framework\Profiler::stop('generate_elements'); $this->addToOutputRootContainers(); \Magento\Framework\Profiler::stop(__CLASS__ . '::' . __METHOD__); }
/** * Retrieve Selected Attributes info * * @param \Magento\Catalog\Model\Product $product * @return array */ public function getSelectedAttributesInfo($product) { $attributes = []; \Magento\Framework\Profiler::start('CONFIGURABLE:' . __METHOD__, ['group' => 'CONFIGURABLE', 'method' => __METHOD__]); if ($attributesOption = $product->getCustomOption('attributes')) { $data = unserialize($attributesOption->getValue()); $this->getUsedProductAttributeIds($product); $usedAttributes = $product->getData($this->_usedAttributes); foreach ($data as $attributeId => $attributeValue) { if (isset($usedAttributes[$attributeId])) { /** @var \Magento\Catalog\Model\Resource\Eav\Attribute $attribute */ $attribute = $usedAttributes[$attributeId]->getProductAttribute(); $label = $attribute->getStoreLabel(); $value = $attribute; if ($value->getSourceModel()) { $value = $value->getSource()->getOptionText($attributeValue); } else { $value = ''; } $attributes[] = ['label' => $label, 'value' => $value]; } } } \Magento\Framework\Profiler::stop('CONFIGURABLE:' . __METHOD__); return $attributes; }
public static function tearDownAfterClass() { \Magento\Framework\Profiler::disable(); }