AbstractBlock.php 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\View\Element;
  7. use Magento\Framework\DataObject\IdentityInterface;
  8. /**
  9. * Base class for all blocks.
  10. *
  11. * Avoid inheriting from this class. Will be deprecated.
  12. *
  13. * Marked as public API because it is actively used now.
  14. *
  15. * @api
  16. * @SuppressWarnings(PHPMD.ExcessivePublicCount)
  17. * @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
  18. * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  19. * @SuppressWarnings(PHPMD.TooManyFields)
  20. * @SuppressWarnings(PHPMD.NumberOfChildren)
  21. * @since 100.0.2
  22. */
  23. abstract class AbstractBlock extends \Magento\Framework\DataObject implements BlockInterface
  24. {
  25. /**
  26. * Cache group Tag
  27. */
  28. const CACHE_GROUP = \Magento\Framework\App\Cache\Type\Block::TYPE_IDENTIFIER;
  29. /**
  30. * Prefix for cache key of block
  31. */
  32. const CACHE_KEY_PREFIX = 'BLOCK_';
  33. /**
  34. * Design
  35. *
  36. * @var \Magento\Framework\View\DesignInterface
  37. */
  38. protected $_design;
  39. /**
  40. * Session
  41. *
  42. * @var \Magento\Framework\Session\SessionManagerInterface
  43. */
  44. protected $_session;
  45. /**
  46. * SID Resolver
  47. *
  48. * @var \Magento\Framework\Session\SidResolverInterface
  49. */
  50. protected $_sidResolver;
  51. /**
  52. * Block name in layout
  53. *
  54. * @var string
  55. */
  56. protected $_nameInLayout;
  57. /**
  58. * Parent layout of the block
  59. *
  60. * @var \Magento\Framework\View\LayoutInterface
  61. */
  62. protected $_layout;
  63. /**
  64. * JS layout configuration
  65. *
  66. * @var array
  67. */
  68. protected $jsLayout = [];
  69. /**
  70. * Request
  71. *
  72. * @var \Magento\Framework\App\RequestInterface
  73. */
  74. protected $_request;
  75. /**
  76. * Url Builder
  77. *
  78. * @var \Magento\Framework\UrlInterface
  79. */
  80. protected $_urlBuilder;
  81. /**
  82. * System event manager
  83. *
  84. *
  85. * @var \Magento\Framework\Event\ManagerInterface
  86. */
  87. protected $_eventManager;
  88. /**
  89. * Application front controller
  90. *
  91. * @var \Magento\Framework\App\FrontController
  92. */
  93. protected $_frontController;
  94. /**
  95. * Asset service
  96. *
  97. * @var \Magento\Framework\View\Asset\Repository
  98. */
  99. protected $_assetRepo;
  100. /**
  101. * View config model
  102. *
  103. * @var \Magento\Framework\View\ConfigInterface
  104. */
  105. protected $_viewConfig;
  106. /**
  107. * Cache State
  108. *
  109. * @var \Magento\Framework\App\Cache\StateInterface
  110. */
  111. protected $_cacheState;
  112. /**
  113. * Logger
  114. *
  115. * @var \Psr\Log\LoggerInterface
  116. */
  117. protected $_logger;
  118. /**
  119. * Escaper
  120. *
  121. * @var \Magento\Framework\Escaper
  122. */
  123. protected $_escaper;
  124. /**
  125. * Filter manager
  126. *
  127. * @var \Magento\Framework\Filter\FilterManager
  128. */
  129. protected $filterManager;
  130. /**
  131. * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface
  132. */
  133. protected $_localeDate;
  134. /**
  135. * @var \Magento\Framework\Translate\Inline\StateInterface
  136. */
  137. protected $inlineTranslation;
  138. /**
  139. * The property is used to define content-scope of block. Can be private or public.
  140. * If it isn't defined then application considers it as false.
  141. *
  142. * @var bool
  143. */
  144. protected $_isScopePrivate = false;
  145. /**
  146. * @var \Magento\Framework\App\Config\ScopeConfigInterface
  147. */
  148. protected $_scopeConfig;
  149. /**
  150. * @var \Magento\Framework\App\CacheInterface
  151. * @since 101.0.0
  152. */
  153. protected $_cache;
  154. /**
  155. * Constructor
  156. *
  157. * @param \Magento\Framework\View\Element\Context $context
  158. * @param array $data
  159. */
  160. public function __construct(\Magento\Framework\View\Element\Context $context, array $data = [])
  161. {
  162. $this->_request = $context->getRequest();
  163. $this->_layout = $context->getLayout();
  164. $this->_eventManager = $context->getEventManager();
  165. $this->_urlBuilder = $context->getUrlBuilder();
  166. $this->_cache = $context->getCache();
  167. $this->_design = $context->getDesignPackage();
  168. $this->_session = $context->getSession();
  169. $this->_sidResolver = $context->getSidResolver();
  170. $this->_scopeConfig = $context->getScopeConfig();
  171. $this->_assetRepo = $context->getAssetRepository();
  172. $this->_viewConfig = $context->getViewConfig();
  173. $this->_cacheState = $context->getCacheState();
  174. $this->_logger = $context->getLogger();
  175. $this->_escaper = $context->getEscaper();
  176. $this->filterManager = $context->getFilterManager();
  177. $this->_localeDate = $context->getLocaleDate();
  178. $this->inlineTranslation = $context->getInlineTranslation();
  179. if (isset($data['jsLayout'])) {
  180. $this->jsLayout = $data['jsLayout'];
  181. unset($data['jsLayout']);
  182. }
  183. parent::__construct($data);
  184. $this->_construct();
  185. }
  186. /**
  187. * Retrieve serialized JS layout configuration ready to use in template
  188. *
  189. * @return string
  190. */
  191. public function getJsLayout()
  192. {
  193. return json_encode($this->jsLayout);
  194. }
  195. /**
  196. * Get request
  197. *
  198. * @return \Magento\Framework\App\RequestInterface
  199. */
  200. public function getRequest()
  201. {
  202. return $this->_request;
  203. }
  204. /**
  205. * Internal constructor, that is called from real constructor
  206. *
  207. * Please override this one instead of overriding real __construct constructor
  208. *
  209. * @return void
  210. */
  211. protected function _construct()
  212. {
  213. /**
  214. * Please override this one instead of overriding real __construct constructor
  215. */
  216. }
  217. /**
  218. * Retrieve parent block
  219. *
  220. * @return \Magento\Framework\View\Element\AbstractBlock|bool
  221. */
  222. public function getParentBlock()
  223. {
  224. $layout = $this->getLayout();
  225. if (!$layout) {
  226. return false;
  227. }
  228. $parentName = $layout->getParentName($this->getNameInLayout());
  229. if ($parentName) {
  230. return $layout->getBlock($parentName);
  231. }
  232. return false;
  233. }
  234. /**
  235. * Set layout object
  236. *
  237. * @param \Magento\Framework\View\LayoutInterface $layout
  238. * @return $this
  239. */
  240. public function setLayout(\Magento\Framework\View\LayoutInterface $layout)
  241. {
  242. $this->_layout = $layout;
  243. $this->_prepareLayout();
  244. return $this;
  245. }
  246. /**
  247. * Preparing global layout
  248. *
  249. * You can redefine this method in child classes for changing layout
  250. *
  251. * @return $this
  252. */
  253. protected function _prepareLayout()
  254. {
  255. return $this;
  256. }
  257. /**
  258. * Retrieve layout object
  259. *
  260. * @return \Magento\Framework\View\LayoutInterface
  261. * @throws \Magento\Framework\Exception\LocalizedException
  262. */
  263. public function getLayout()
  264. {
  265. if (!$this->_layout) {
  266. throw new \Magento\Framework\Exception\LocalizedException(
  267. new \Magento\Framework\Phrase('Layout must be initialized')
  268. );
  269. }
  270. return $this->_layout;
  271. }
  272. /**
  273. * Sets/changes name of a block in layout
  274. *
  275. * @param string $name
  276. * @return $this
  277. */
  278. public function setNameInLayout($name)
  279. {
  280. if (!empty($this->_nameInLayout) && $this->_layout) {
  281. if ($name === $this->_nameInLayout) {
  282. return $this;
  283. }
  284. $this->_layout->renameElement($this->_nameInLayout, $name);
  285. }
  286. $this->_nameInLayout = $name;
  287. return $this;
  288. }
  289. /**
  290. * Retrieves sorted list of child names
  291. *
  292. * @return array
  293. */
  294. public function getChildNames()
  295. {
  296. $layout = $this->getLayout();
  297. if (!$layout) {
  298. return [];
  299. }
  300. return $layout->getChildNames($this->getNameInLayout());
  301. }
  302. /**
  303. * Set block attribute value
  304. *
  305. * Wrapper for method "setData"
  306. *
  307. * @param string $name
  308. * @param mixed $value
  309. * @return $this
  310. */
  311. public function setAttribute($name, $value = null)
  312. {
  313. return $this->setData($name, $value);
  314. }
  315. /**
  316. * Set child block
  317. *
  318. * @param string $alias
  319. * @param \Magento\Framework\View\Element\AbstractBlock|string $block
  320. * @return $this
  321. */
  322. public function setChild($alias, $block)
  323. {
  324. $layout = $this->getLayout();
  325. if (!$layout) {
  326. return $this;
  327. }
  328. $thisName = $this->getNameInLayout();
  329. if ($layout->getChildName($thisName, $alias)) {
  330. $this->unsetChild($alias);
  331. }
  332. if ($block instanceof self) {
  333. $block = $block->getNameInLayout();
  334. }
  335. $layout->setChild($thisName, $block, $alias);
  336. return $this;
  337. }
  338. /**
  339. * Create block with name: {parent}.{alias} and set as child
  340. *
  341. * @param string $alias
  342. * @param string $block
  343. * @param array $data
  344. * @return $this new block
  345. */
  346. public function addChild($alias, $block, $data = [])
  347. {
  348. $block = $this->getLayout()->createBlock(
  349. $block,
  350. $this->getNameInLayout() . '.' . $alias,
  351. ['data' => $data]
  352. );
  353. $this->setChild($alias, $block);
  354. return $block;
  355. }
  356. /**
  357. * Unset child block
  358. *
  359. * @param string $alias
  360. * @return $this
  361. */
  362. public function unsetChild($alias)
  363. {
  364. $layout = $this->getLayout();
  365. if (!$layout) {
  366. return $this;
  367. }
  368. $layout->unsetChild($this->getNameInLayout(), $alias);
  369. return $this;
  370. }
  371. /**
  372. * Call a child and unset it, if callback matched result
  373. *
  374. * Variable $params will pass to child callback
  375. * $params may be array, if called from layout with elements with same name, for example:
  376. * ...<foo>value_1</foo><foo>value_2</foo><foo>value_3</foo>
  377. *
  378. * Or, if called like this:
  379. * ...<foo>value_1</foo><bar>value_2</bar><baz>value_3</baz>
  380. * - then it will be $params1, $params2, $params3
  381. *
  382. * It is no difference anyway, because they will be transformed in appropriate way.
  383. *
  384. * @param string $alias
  385. * @param string $callback
  386. * @param mixed $result
  387. * @param array $params
  388. * @return $this
  389. */
  390. public function unsetCallChild($alias, $callback, $result, $params)
  391. {
  392. $child = $this->getChildBlock($alias);
  393. if ($child) {
  394. $args = func_get_args();
  395. $alias = array_shift($args);
  396. $callback = array_shift($args);
  397. $result = (string)array_shift($args);
  398. if (!is_array($params)) {
  399. $params = $args;
  400. }
  401. // @codingStandardsIgnoreStart
  402. if ($result == call_user_func_array([&$child, $callback], $params)) {
  403. $this->unsetChild($alias);
  404. }
  405. // @codingStandardsIgnoreEnd
  406. }
  407. return $this;
  408. }
  409. /**
  410. * Unset all children blocks
  411. *
  412. * @return $this
  413. */
  414. public function unsetChildren()
  415. {
  416. $layout = $this->getLayout();
  417. if (!$layout) {
  418. return $this;
  419. }
  420. $name = $this->getNameInLayout();
  421. $children = $layout->getChildNames($name);
  422. foreach ($children as $childName) {
  423. $layout->unsetChild($name, $childName);
  424. }
  425. return $this;
  426. }
  427. /**
  428. * Retrieve child block by name
  429. *
  430. * @param string $alias
  431. * @return \Magento\Framework\View\Element\AbstractBlock|bool
  432. */
  433. public function getChildBlock($alias)
  434. {
  435. $layout = $this->getLayout();
  436. if (!$layout) {
  437. return false;
  438. }
  439. $name = $layout->getChildName($this->getNameInLayout(), $alias);
  440. if ($name) {
  441. return $layout->getBlock($name);
  442. }
  443. return false;
  444. }
  445. /**
  446. * Retrieve child block HTML
  447. *
  448. * @param string $alias
  449. * @param boolean $useCache
  450. * @return string
  451. */
  452. public function getChildHtml($alias = '', $useCache = true)
  453. {
  454. $layout = $this->getLayout();
  455. if (!$layout) {
  456. return '';
  457. }
  458. $name = $this->getNameInLayout();
  459. $out = '';
  460. if ($alias) {
  461. $childName = $layout->getChildName($name, $alias);
  462. if ($childName) {
  463. $out = $layout->renderElement($childName, $useCache);
  464. }
  465. } else {
  466. foreach ($layout->getChildNames($name) as $child) {
  467. $out .= $layout->renderElement($child, $useCache);
  468. }
  469. }
  470. return $out;
  471. }
  472. /**
  473. * Render output of child child element
  474. *
  475. * @param string $alias
  476. * @param string $childChildAlias
  477. * @param bool $useCache
  478. * @return string
  479. */
  480. public function getChildChildHtml($alias, $childChildAlias = '', $useCache = true)
  481. {
  482. $layout = $this->getLayout();
  483. if (!$layout) {
  484. return '';
  485. }
  486. $childName = $layout->getChildName($this->getNameInLayout(), $alias);
  487. if (!$childName) {
  488. return '';
  489. }
  490. $out = '';
  491. if ($childChildAlias) {
  492. $childChildName = $layout->getChildName($childName, $childChildAlias);
  493. $out = $layout->renderElement($childChildName, $useCache);
  494. } else {
  495. foreach ($layout->getChildNames($childName) as $childChild) {
  496. $out .= $layout->renderElement($childChild, $useCache);
  497. }
  498. }
  499. return $out;
  500. }
  501. /**
  502. * Retrieve block html
  503. *
  504. * @param string $name
  505. * @return string
  506. */
  507. public function getBlockHtml($name)
  508. {
  509. $block = $this->_layout->getBlock($name);
  510. if ($block) {
  511. return $block->toHtml();
  512. }
  513. return '';
  514. }
  515. /**
  516. * Insert child element into specified position
  517. *
  518. * By default inserts as first element into children list
  519. *
  520. * @param \Magento\Framework\View\Element\AbstractBlock|string $element
  521. * @param string|int|null $siblingName
  522. * @param bool $after
  523. * @param string $alias
  524. * @return $this|bool
  525. */
  526. public function insert($element, $siblingName = 0, $after = true, $alias = '')
  527. {
  528. $layout = $this->getLayout();
  529. if (!$layout) {
  530. return false;
  531. }
  532. if ($element instanceof \Magento\Framework\View\Element\AbstractBlock) {
  533. $elementName = $element->getNameInLayout();
  534. } else {
  535. $elementName = $element;
  536. }
  537. $layout->setChild($this->_nameInLayout, $elementName, $alias);
  538. $layout->reorderChild($this->_nameInLayout, $elementName, $siblingName, $after);
  539. return $this;
  540. }
  541. /**
  542. * Append element to the end of children list
  543. *
  544. * @param \Magento\Framework\View\Element\AbstractBlock|string $element
  545. * @param string $alias
  546. * @return $this
  547. */
  548. public function append($element, $alias = '')
  549. {
  550. return $this->insert($element, null, true, $alias);
  551. }
  552. /**
  553. * Get a group of child blocks
  554. *
  555. * Returns an array of <alias> => <block>
  556. * or an array of <alias> => <callback_result>
  557. * The callback currently supports only $this methods and passes the alias as parameter
  558. *
  559. * @param string $groupName
  560. * @return array
  561. */
  562. public function getGroupChildNames($groupName)
  563. {
  564. return $this->getLayout()->getGroupChildNames($this->getNameInLayout(), $groupName);
  565. }
  566. /**
  567. * Get a value from child block by specified key
  568. *
  569. * @param string $alias
  570. * @param string $key
  571. * @return mixed
  572. */
  573. public function getChildData($alias, $key = '')
  574. {
  575. $child = $this->getChildBlock($alias);
  576. if ($child) {
  577. return $child->getData($key);
  578. }
  579. return null;
  580. }
  581. /**
  582. * Before rendering html, but after trying to load cache
  583. *
  584. * @return $this
  585. */
  586. protected function _beforeToHtml()
  587. {
  588. return $this;
  589. }
  590. /**
  591. * Produce and return block's html output
  592. *
  593. * This method should not be overridden. You can override _toHtml() method in descendants if needed.
  594. *
  595. * @return string
  596. */
  597. public function toHtml()
  598. {
  599. $this->_eventManager->dispatch('view_block_abstract_to_html_before', ['block' => $this]);
  600. if ($this->_scopeConfig->getValue(
  601. 'advanced/modules_disable_output/' . $this->getModuleName(),
  602. \Magento\Store\Model\ScopeInterface::SCOPE_STORE
  603. )) {
  604. return '';
  605. }
  606. $html = $this->_loadCache();
  607. if ($html === false) {
  608. if ($this->hasData('translate_inline')) {
  609. $this->inlineTranslation->suspend($this->getData('translate_inline'));
  610. }
  611. $this->_beforeToHtml();
  612. $html = $this->_toHtml();
  613. $this->_saveCache($html);
  614. if ($this->hasData('translate_inline')) {
  615. $this->inlineTranslation->resume();
  616. }
  617. }
  618. $html = $this->_afterToHtml($html);
  619. /** @var \Magento\Framework\DataObject */
  620. $transportObject = new \Magento\Framework\DataObject(
  621. [
  622. 'html' => $html,
  623. ]
  624. );
  625. $this->_eventManager->dispatch('view_block_abstract_to_html_after', [
  626. 'block' => $this,
  627. 'transport' => $transportObject
  628. ]);
  629. $html = $transportObject->getHtml();
  630. return $html;
  631. }
  632. /**
  633. * Processing block html after rendering
  634. *
  635. * @param string $html
  636. * @return string
  637. */
  638. protected function _afterToHtml($html)
  639. {
  640. return $html;
  641. }
  642. /**
  643. * Override this method in descendants to produce html
  644. *
  645. * @return string
  646. */
  647. protected function _toHtml()
  648. {
  649. return '';
  650. }
  651. /**
  652. * Retrieve data-ui-id attribute
  653. *
  654. * Retrieve data-ui-id attribute which will distinguish
  655. * link/input/container/anything else in template among others.
  656. * Function takes an arbitrary amount of parameters.
  657. *
  658. * @param string|null $arg1
  659. * @param string|null $arg2
  660. * @param string|null $arg3
  661. * @param string|null $arg4
  662. * @param string|null $arg5
  663. * @return string
  664. */
  665. public function getUiId($arg1 = null, $arg2 = null, $arg3 = null, $arg4 = null, $arg5 = null)
  666. {
  667. return ' data-ui-id="' . $this->getJsId($arg1, $arg2, $arg3, $arg4, $arg5) . '" ';
  668. }
  669. /**
  670. * Generate id for using in JavaScript UI
  671. *
  672. * Function takes an arbitrary amount of parameters
  673. *
  674. * @param string|null $arg1
  675. * @param string|null $arg2
  676. * @param string|null $arg3
  677. * @param string|null $arg4
  678. * @param string|null $arg5
  679. * @return string
  680. */
  681. public function getJsId($arg1 = null, $arg2 = null, $arg3 = null, $arg4 = null, $arg5 = null)
  682. {
  683. $args = [];
  684. if ($arg1 !== null) {
  685. $args[] = $arg1;
  686. }
  687. if ($arg2 !== null) {
  688. $args[] = $arg2;
  689. }
  690. if ($arg3 !== null) {
  691. $args[] = $arg3;
  692. }
  693. if ($arg4 !== null) {
  694. $args[] = $arg4;
  695. }
  696. if ($arg5 !== null) {
  697. $args[] = $arg5;
  698. }
  699. $rawId = $this->_nameInLayout . '-' . implode('-', $args);
  700. return trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($rawId)), '-');
  701. }
  702. /**
  703. * Generate url by route and parameters
  704. *
  705. * @param string $route
  706. * @param array $params
  707. * @return string
  708. */
  709. public function getUrl($route = '', $params = [])
  710. {
  711. return $this->_urlBuilder->getUrl($route, $params);
  712. }
  713. /**
  714. * Retrieve url of a view file
  715. *
  716. * @param string $fileId
  717. * @param array $params
  718. * @return string
  719. */
  720. public function getViewFileUrl($fileId, array $params = [])
  721. {
  722. try {
  723. $params = array_merge(['_secure' => $this->getRequest()->isSecure()], $params);
  724. return $this->_assetRepo->getUrlWithParams($fileId, $params);
  725. } catch (\Magento\Framework\Exception\LocalizedException $e) {
  726. $this->_logger->critical($e);
  727. return $this->_getNotFoundUrl();
  728. }
  729. }
  730. /**
  731. * Get 404 file not found url
  732. *
  733. * @param string $route
  734. * @param array $params
  735. * @return string
  736. */
  737. protected function _getNotFoundUrl($route = '', $params = ['_direct' => 'core/index/notFound'])
  738. {
  739. return $this->getUrl($route, $params);
  740. }
  741. /**
  742. * Retrieve formatting date
  743. *
  744. * @param null|string|\DateTimeInterface $date
  745. * @param int $format
  746. * @param bool $showTime
  747. * @param null|string $timezone
  748. * @return string
  749. */
  750. public function formatDate(
  751. $date = null,
  752. $format = \IntlDateFormatter::SHORT,
  753. $showTime = false,
  754. $timezone = null
  755. ) {
  756. $date = $date instanceof \DateTimeInterface ? $date : new \DateTime($date);
  757. return $this->_localeDate->formatDateTime(
  758. $date,
  759. $format,
  760. $showTime ? $format : \IntlDateFormatter::NONE,
  761. null,
  762. $timezone
  763. );
  764. }
  765. /**
  766. * Retrieve formatting time
  767. *
  768. * @param \DateTime|string|null $time
  769. * @param int $format
  770. * @param bool $showDate
  771. * @return string
  772. */
  773. public function formatTime(
  774. $time = null,
  775. $format = \IntlDateFormatter::SHORT,
  776. $showDate = false
  777. ) {
  778. $time = $time instanceof \DateTimeInterface ? $time : new \DateTime($time);
  779. return $this->_localeDate->formatDateTime(
  780. $time,
  781. $showDate ? $format : \IntlDateFormatter::NONE,
  782. $format
  783. );
  784. }
  785. /**
  786. * Retrieve module name of block
  787. *
  788. * @return string
  789. */
  790. public function getModuleName()
  791. {
  792. if (!$this->_getData('module_name')) {
  793. $this->setData('module_name', self::extractModuleName(get_class($this)));
  794. }
  795. return $this->_getData('module_name');
  796. }
  797. /**
  798. * Extract module name from specified block class name
  799. *
  800. * @param string $className
  801. * @return string
  802. */
  803. public static function extractModuleName($className)
  804. {
  805. $namespace = substr(
  806. $className,
  807. 0,
  808. strpos($className, '\\' . 'Block')
  809. );
  810. return str_replace('\\', '_', $namespace);
  811. }
  812. /**
  813. * Escape HTML entities
  814. *
  815. * @param string|array $data
  816. * @param array|null $allowedTags
  817. * @return string
  818. */
  819. public function escapeHtml($data, $allowedTags = null)
  820. {
  821. return $this->_escaper->escapeHtml($data, $allowedTags);
  822. }
  823. /**
  824. * Escape string for the JavaScript context
  825. *
  826. * @param string $string
  827. * @return string
  828. * @since 101.0.0
  829. */
  830. public function escapeJs($string)
  831. {
  832. return $this->_escaper->escapeJs($string);
  833. }
  834. /**
  835. * Escape a string for the HTML attribute context
  836. *
  837. * @param string $string
  838. * @param boolean $escapeSingleQuote
  839. * @return string
  840. * @since 101.0.0
  841. */
  842. public function escapeHtmlAttr($string, $escapeSingleQuote = true)
  843. {
  844. return $this->_escaper->escapeHtmlAttr($string, $escapeSingleQuote);
  845. }
  846. /**
  847. * Escape string for the CSS context
  848. *
  849. * @param string $string
  850. * @return string
  851. * @since 101.0.0
  852. */
  853. public function escapeCss($string)
  854. {
  855. return $this->_escaper->escapeCss($string);
  856. }
  857. /**
  858. * Wrapper for standard strip_tags() function with extra functionality for html entities
  859. *
  860. * @param string $data
  861. * @param string|null $allowableTags
  862. * @param bool $allowHtmlEntities
  863. * @return string
  864. */
  865. public function stripTags($data, $allowableTags = null, $allowHtmlEntities = false)
  866. {
  867. return $this->filterManager->stripTags(
  868. $data,
  869. ['allowableTags' => $allowableTags, 'escape' => $allowHtmlEntities]
  870. );
  871. }
  872. /**
  873. * Escape URL
  874. *
  875. * @param string $string
  876. * @return string
  877. */
  878. public function escapeUrl($string)
  879. {
  880. return $this->_escaper->escapeUrl((string)$string);
  881. }
  882. /**
  883. * Escape xss in urls
  884. *
  885. * @param string $data
  886. * @return string
  887. * @deprecated 101.0.0
  888. */
  889. public function escapeXssInUrl($data)
  890. {
  891. return $this->_escaper->escapeXssInUrl($data);
  892. }
  893. /**
  894. * Escape quotes inside html attributes
  895. *
  896. * Use $addSlashes = false for escaping js that inside html attribute (onClick, onSubmit etc)
  897. *
  898. * @param string $data
  899. * @param bool $addSlashes
  900. * @return string
  901. * @deprecated 101.0.0
  902. */
  903. public function escapeQuote($data, $addSlashes = false)
  904. {
  905. return $this->_escaper->escapeQuote($data, $addSlashes);
  906. }
  907. /**
  908. * Escape quotes in java scripts
  909. *
  910. * @param string|array $data
  911. * @param string $quote
  912. * @return string|array
  913. * @deprecated 101.0.0
  914. */
  915. public function escapeJsQuote($data, $quote = '\'')
  916. {
  917. return $this->_escaper->escapeJsQuote($data, $quote);
  918. }
  919. /**
  920. * Get block name
  921. *
  922. * @return string
  923. */
  924. public function getNameInLayout()
  925. {
  926. return $this->_nameInLayout;
  927. }
  928. /**
  929. * Get cache key informative items
  930. *
  931. * Provide string array key to share specific info item with FPC placeholder
  932. *
  933. * @return string[]
  934. */
  935. public function getCacheKeyInfo()
  936. {
  937. return [$this->getNameInLayout()];
  938. }
  939. /**
  940. * Get Key for caching block content
  941. *
  942. * @return string
  943. */
  944. public function getCacheKey()
  945. {
  946. if ($this->hasData('cache_key')) {
  947. return static::CACHE_KEY_PREFIX . $this->getData('cache_key');
  948. }
  949. /**
  950. * don't prevent recalculation by saving generated cache key
  951. * because of ability to render single block instance with different data
  952. */
  953. $key = $this->getCacheKeyInfo();
  954. $key = array_values($key); // ignore array keys
  955. $key = implode('|', $key);
  956. $key = sha1($key); // use hashing to hide potentially private data
  957. return static::CACHE_KEY_PREFIX . $key;
  958. }
  959. /**
  960. * Get tags array for saving cache
  961. *
  962. * @return array
  963. */
  964. protected function getCacheTags()
  965. {
  966. if (!$this->hasData('cache_tags')) {
  967. $tags = [];
  968. } else {
  969. $tags = $this->getData('cache_tags');
  970. }
  971. $tags[] = self::CACHE_GROUP;
  972. if ($this instanceof IdentityInterface) {
  973. $tags = array_merge($tags, $this->getIdentities());
  974. }
  975. return $tags;
  976. }
  977. /**
  978. * Get block cache life time
  979. *
  980. * @return int|bool|null
  981. */
  982. protected function getCacheLifetime()
  983. {
  984. if (!$this->hasData('cache_lifetime')) {
  985. return null;
  986. }
  987. $cacheLifetime = $this->getData('cache_lifetime');
  988. if (false === $cacheLifetime || null === $cacheLifetime) {
  989. return null;
  990. }
  991. return (int)$cacheLifetime;
  992. }
  993. /**
  994. * Load block html from cache storage
  995. *
  996. * @return string|false
  997. */
  998. protected function _loadCache()
  999. {
  1000. if ($this->getCacheLifetime() === null || !$this->_cacheState->isEnabled(self::CACHE_GROUP)) {
  1001. return false;
  1002. }
  1003. $cacheKey = $this->getCacheKey();
  1004. $cacheData = $this->_cache->load($cacheKey);
  1005. if ($cacheData) {
  1006. $cacheData = str_replace(
  1007. $this->_getSidPlaceholder($cacheKey),
  1008. $this->_sidResolver->getSessionIdQueryParam($this->_session) . '=' . $this->_session->getSessionId(),
  1009. $cacheData
  1010. );
  1011. }
  1012. return $cacheData;
  1013. }
  1014. /**
  1015. * Save block content to cache storage
  1016. *
  1017. * @param string $data
  1018. * @return $this
  1019. */
  1020. protected function _saveCache($data)
  1021. {
  1022. if (!$this->getCacheLifetime() || !$this->_cacheState->isEnabled(self::CACHE_GROUP)) {
  1023. return false;
  1024. }
  1025. $cacheKey = $this->getCacheKey();
  1026. $data = str_replace(
  1027. $this->_sidResolver->getSessionIdQueryParam($this->_session) . '=' . $this->_session->getSessionId(),
  1028. $this->_getSidPlaceholder($cacheKey),
  1029. $data
  1030. );
  1031. $this->_cache->save($data, $cacheKey, array_unique($this->getCacheTags()), $this->getCacheLifetime());
  1032. return $this;
  1033. }
  1034. /**
  1035. * Get SID placeholder for cache
  1036. *
  1037. * @param null|string $cacheKey
  1038. * @return string
  1039. */
  1040. protected function _getSidPlaceholder($cacheKey = null)
  1041. {
  1042. if ($cacheKey === null) {
  1043. $cacheKey = $this->getCacheKey();
  1044. }
  1045. return '<!--SID=' . $cacheKey . '-->';
  1046. }
  1047. /**
  1048. * Get variable value from view configuration
  1049. *
  1050. * Module name can be omitted. If omitted, it will be determined automatically.
  1051. *
  1052. * @param string $name variable name
  1053. * @param string|null $module optional module name
  1054. * @return string|false
  1055. */
  1056. public function getVar($name, $module = null)
  1057. {
  1058. $module = $module ?: $this->getModuleName();
  1059. return $this->_viewConfig->getViewConfig()->getVarValue($module, $name);
  1060. }
  1061. /**
  1062. * Determine if the block scope is private or public.
  1063. *
  1064. * Returns true if scope is private, false otherwise
  1065. *
  1066. * @return bool
  1067. */
  1068. public function isScopePrivate()
  1069. {
  1070. return $this->_isScopePrivate;
  1071. }
  1072. }