Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
AbstractBlock.php
Go to the documentation of this file.
1 <?php
7 
9 
26 {
31 
35  const CACHE_KEY_PREFIX = 'BLOCK_';
36 
42  protected $_design;
43 
49  protected $_session;
50 
56  protected $_sidResolver;
57 
63  protected $_nameInLayout;
64 
70  protected $_layout;
71 
77  protected $jsLayout = [];
78 
84  protected $_request;
85 
91  protected $_urlBuilder;
92 
99  protected $_eventManager;
100 
106  protected $_frontController;
107 
113  protected $_assetRepo;
114 
120  protected $_viewConfig;
121 
127  protected $_cacheState;
128 
134  protected $_logger;
135 
141  protected $_escaper;
142 
148  protected $filterManager;
149 
153  protected $_localeDate;
154 
159 
166  protected $_isScopePrivate = false;
167 
171  protected $_scopeConfig;
172 
177  protected $_cache;
178 
185  public function __construct(\Magento\Framework\View\Element\Context $context, array $data = [])
186  {
187  $this->_request = $context->getRequest();
188  $this->_layout = $context->getLayout();
189  $this->_eventManager = $context->getEventManager();
190  $this->_urlBuilder = $context->getUrlBuilder();
191  $this->_cache = $context->getCache();
192  $this->_design = $context->getDesignPackage();
193  $this->_session = $context->getSession();
194  $this->_sidResolver = $context->getSidResolver();
195  $this->_scopeConfig = $context->getScopeConfig();
196  $this->_assetRepo = $context->getAssetRepository();
197  $this->_viewConfig = $context->getViewConfig();
198  $this->_cacheState = $context->getCacheState();
199  $this->_logger = $context->getLogger();
200  $this->_escaper = $context->getEscaper();
201  $this->filterManager = $context->getFilterManager();
202  $this->_localeDate = $context->getLocaleDate();
203  $this->inlineTranslation = $context->getInlineTranslation();
204  if (isset($data['jsLayout'])) {
205  $this->jsLayout = $data['jsLayout'];
206  unset($data['jsLayout']);
207  }
208  parent::__construct($data);
209  $this->_construct();
210  }
211 
217  public function getJsLayout()
218  {
219  return json_encode($this->jsLayout);
220  }
221 
227  public function getRequest()
228  {
229  return $this->_request;
230  }
231 
239  protected function _construct()
240  {
244  }
245 
251  public function getParentBlock()
252  {
253  $layout = $this->getLayout();
254  if (!$layout) {
255  return false;
256  }
257  $parentName = $layout->getParentName($this->getNameInLayout());
258  if ($parentName) {
259  return $layout->getBlock($parentName);
260  }
261  return false;
262  }
263 
270  public function setLayout(\Magento\Framework\View\LayoutInterface $layout)
271  {
272  $this->_layout = $layout;
273  $this->_prepareLayout();
274  return $this;
275  }
276 
284  protected function _prepareLayout()
285  {
286  return $this;
287  }
288 
295  public function getLayout()
296  {
297  if (!$this->_layout) {
298  throw new \Magento\Framework\Exception\LocalizedException(
299  new \Magento\Framework\Phrase('Layout must be initialized')
300  );
301  }
302  return $this->_layout;
303  }
304 
311  public function setNameInLayout($name)
312  {
313  if (!empty($this->_nameInLayout) && $this->_layout) {
314  if ($name === $this->_nameInLayout) {
315  return $this;
316  }
317  $this->_layout->renameElement($this->_nameInLayout, $name);
318  }
319  $this->_nameInLayout = $name;
320  return $this;
321  }
322 
328  public function getChildNames()
329  {
330  $layout = $this->getLayout();
331  if (!$layout) {
332  return [];
333  }
334  return $layout->getChildNames($this->getNameInLayout());
335  }
336 
346  public function setAttribute($name, $value = null)
347  {
348  return $this->setData($name, $value);
349  }
350 
358  public function setChild($alias, $block)
359  {
360  $layout = $this->getLayout();
361  if (!$layout) {
362  return $this;
363  }
364  $thisName = $this->getNameInLayout();
365  if ($layout->getChildName($thisName, $alias)) {
366  $this->unsetChild($alias);
367  }
368  if ($block instanceof self) {
369  $block = $block->getNameInLayout();
370  }
371 
372  $layout->setChild($thisName, $block, $alias);
373 
374  return $this;
375  }
376 
385  public function addChild($alias, $block, $data = [])
386  {
387  $block = $this->getLayout()->createBlock(
388  $block,
389  $this->getNameInLayout() . '.' . $alias,
390  ['data' => $data]
391  );
392  $this->setChild($alias, $block);
393  return $block;
394  }
395 
402  public function unsetChild($alias)
403  {
404  $layout = $this->getLayout();
405  if (!$layout) {
406  return $this;
407  }
408  $layout->unsetChild($this->getNameInLayout(), $alias);
409  return $this;
410  }
411 
431  public function unsetCallChild($alias, $callback, $result, $params)
432  {
433  $child = $this->getChildBlock($alias);
434  if ($child) {
435  $args = func_get_args();
436  $alias = array_shift($args);
437  $callback = array_shift($args);
438  $result = (string)array_shift($args);
439  if (!is_array($params)) {
440  $params = $args;
441  }
442 
443  // @codingStandardsIgnoreStart
444  if ($result == call_user_func_array([&$child, $callback], $params)) {
445  $this->unsetChild($alias);
446  }
447  // @codingStandardsIgnoreEnd
448  }
449  return $this;
450  }
451 
457  public function unsetChildren()
458  {
459  $layout = $this->getLayout();
460  if (!$layout) {
461  return $this;
462  }
463  $name = $this->getNameInLayout();
464  $children = $layout->getChildNames($name);
465  foreach ($children as $childName) {
466  $layout->unsetChild($name, $childName);
467  }
468  return $this;
469  }
470 
477  public function getChildBlock($alias)
478  {
479  $layout = $this->getLayout();
480  if (!$layout) {
481  return false;
482  }
483  $name = $layout->getChildName($this->getNameInLayout(), $alias);
484  if ($name) {
485  return $layout->getBlock($name);
486  }
487  return false;
488  }
489 
497  public function getChildHtml($alias = '', $useCache = true)
498  {
499  $layout = $this->getLayout();
500  if (!$layout) {
501  return '';
502  }
503  $name = $this->getNameInLayout();
504  $out = '';
505  if ($alias) {
506  $childName = $layout->getChildName($name, $alias);
507  if ($childName) {
508  $out = $layout->renderElement($childName, $useCache);
509  }
510  } else {
511  foreach ($layout->getChildNames($name) as $child) {
512  $out .= $layout->renderElement($child, $useCache);
513  }
514  }
515 
516  return $out;
517  }
518 
527  public function getChildChildHtml($alias, $childChildAlias = '', $useCache = true)
528  {
529  $layout = $this->getLayout();
530  if (!$layout) {
531  return '';
532  }
533  $childName = $layout->getChildName($this->getNameInLayout(), $alias);
534  if (!$childName) {
535  return '';
536  }
537  $out = '';
538  if ($childChildAlias) {
539  $childChildName = $layout->getChildName($childName, $childChildAlias);
540  $out = $layout->renderElement($childChildName, $useCache);
541  } else {
542  foreach ($layout->getChildNames($childName) as $childChild) {
543  $out .= $layout->renderElement($childChild, $useCache);
544  }
545  }
546  return $out;
547  }
548 
555  public function getBlockHtml($name)
556  {
557  $block = $this->_layout->getBlock($name);
558  if ($block) {
559  return $block->toHtml();
560  }
561  return '';
562  }
563 
575  public function insert($element, $siblingName = 0, $after = true, $alias = '')
576  {
577  $layout = $this->getLayout();
578  if (!$layout) {
579  return false;
580  }
581  if ($element instanceof \Magento\Framework\View\Element\AbstractBlock) {
582  $elementName = $element->getNameInLayout();
583  } else {
585  }
586  $layout->setChild($this->_nameInLayout, $elementName, $alias);
587  $layout->reorderChild($this->_nameInLayout, $elementName, $siblingName, $after);
588  return $this;
589  }
590 
598  public function append($element, $alias = '')
599  {
600  return $this->insert($element, null, true, $alias);
601  }
602 
613  public function getGroupChildNames($groupName)
614  {
615  return $this->getLayout()->getGroupChildNames($this->getNameInLayout(), $groupName);
616  }
617 
625  public function getChildData($alias, $key = '')
626  {
627  $child = $this->getChildBlock($alias);
628  if ($child) {
629  return $child->getData($key);
630  }
631  return null;
632  }
633 
639  protected function _beforeToHtml()
640  {
641  return $this;
642  }
643 
651  public function toHtml()
652  {
653  $this->_eventManager->dispatch('view_block_abstract_to_html_before', ['block' => $this]);
654  if ($this->_scopeConfig->getValue(
655  'advanced/modules_disable_output/' . $this->getModuleName(),
657  )) {
658  return '';
659  }
660 
661  $html = $this->_loadCache();
662  if ($html === false) {
663  if ($this->hasData('translate_inline')) {
664  $this->inlineTranslation->suspend($this->getData('translate_inline'));
665  }
666 
667  $this->_beforeToHtml();
668  $html = $this->_toHtml();
669  $this->_saveCache($html);
670 
671  if ($this->hasData('translate_inline')) {
672  $this->inlineTranslation->resume();
673  }
674  }
675  $html = $this->_afterToHtml($html);
676 
678  $transportObject = new \Magento\Framework\DataObject(
679  [
680  'html' => $html,
681  ]
682  );
683  $this->_eventManager->dispatch('view_block_abstract_to_html_after', [
684  'block' => $this,
685  'transport' => $transportObject
686  ]);
687  $html = $transportObject->getHtml();
688 
689  return $html;
690  }
691 
698  protected function _afterToHtml($html)
699  {
700  return $html;
701  }
702 
708  protected function _toHtml()
709  {
710  return '';
711  }
712 
727  public function getUiId($arg1 = null, $arg2 = null, $arg3 = null, $arg4 = null, $arg5 = null)
728  {
729  return ' data-ui-id="' . $this->getJsId($arg1, $arg2, $arg3, $arg4, $arg5) . '" ';
730  }
731 
744  public function getJsId($arg1 = null, $arg2 = null, $arg3 = null, $arg4 = null, $arg5 = null)
745  {
746  $args = [];
747  if ($arg1 !== null) {
748  $args[] = $arg1;
749  }
750  if ($arg2 !== null) {
751  $args[] = $arg2;
752  }
753  if ($arg3 !== null) {
754  $args[] = $arg3;
755  }
756  if ($arg4 !== null) {
757  $args[] = $arg4;
758  }
759  if ($arg5 !== null) {
760  $args[] = $arg5;
761  }
762  $rawId = $this->_nameInLayout . '-' . implode('-', $args);
763  return trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($rawId)), '-');
764  }
765 
773  public function getUrl($route = '', $params = [])
774  {
775  return $this->_urlBuilder->getUrl($route, $params);
776  }
777 
785  public function getViewFileUrl($fileId, array $params = [])
786  {
787  try {
788  $params = array_merge(['_secure' => $this->getRequest()->isSecure()], $params);
789  return $this->_assetRepo->getUrlWithParams($fileId, $params);
790  } catch (\Magento\Framework\Exception\LocalizedException $e) {
791  $this->_logger->critical($e);
792  return $this->_getNotFoundUrl();
793  }
794  }
795 
803  protected function _getNotFoundUrl($route = '', $params = ['_direct' => 'core/index/notFound'])
804  {
805  return $this->getUrl($route, $params);
806  }
807 
817  public function formatDate(
818  $date = null,
819  $format = \IntlDateFormatter::SHORT,
820  $showTime = false,
821  $timezone = null
822  ) {
823  $date = $date instanceof \DateTimeInterface ? $date : new \DateTime($date);
824  return $this->_localeDate->formatDateTime(
825  $date,
826  $format,
827  $showTime ? $format : \IntlDateFormatter::NONE,
828  null,
829  $timezone
830  );
831  }
832 
841  public function formatTime(
842  $time = null,
843  $format = \IntlDateFormatter::SHORT,
844  $showDate = false
845  ) {
846  $time = $time instanceof \DateTimeInterface ? $time : new \DateTime($time);
847  return $this->_localeDate->formatDateTime(
848  $time,
849  $showDate ? $format : \IntlDateFormatter::NONE,
850  $format
851  );
852  }
853 
859  public function getModuleName()
860  {
861  if (!$this->_getData('module_name')) {
862  $this->setData('module_name', self::extractModuleName(get_class($this)));
863  }
864  return $this->_getData('module_name');
865  }
866 
873  public static function extractModuleName($className)
874  {
875  $namespace = substr(
876  $className,
877  0,
878  strpos($className, '\\' . 'Block')
879  );
880  return str_replace('\\', '_', $namespace);
881  }
882 
890  public function escapeHtml($data, $allowedTags = null)
891  {
892  return $this->_escaper->escapeHtml($data, $allowedTags);
893  }
894 
902  public function escapeJs($string)
903  {
904  return $this->_escaper->escapeJs($string);
905  }
906 
915  public function escapeHtmlAttr($string, $escapeSingleQuote = true)
916  {
917  return $this->_escaper->escapeHtmlAttr($string, $escapeSingleQuote);
918  }
919 
927  public function escapeCss($string)
928  {
929  return $this->_escaper->escapeCss($string);
930  }
931 
940  public function stripTags($data, $allowableTags = null, $allowHtmlEntities = false)
941  {
942  return $this->filterManager->stripTags(
943  $data,
944  ['allowableTags' => $allowableTags, 'escape' => $allowHtmlEntities]
945  );
946  }
947 
954  public function escapeUrl($string)
955  {
956  return $this->_escaper->escapeUrl((string)$string);
957  }
958 
966  public function escapeXssInUrl($data)
967  {
968  return $this->_escaper->escapeXssInUrl($data);
969  }
970 
981  public function escapeQuote($data, $addSlashes = false)
982  {
983  return $this->_escaper->escapeQuote($data, $addSlashes);
984  }
985 
994  public function escapeJsQuote($data, $quote = '\'')
995  {
996  return $this->_escaper->escapeJsQuote($data, $quote);
997  }
998 
1004  public function getNameInLayout()
1005  {
1006  return $this->_nameInLayout;
1007  }
1008 
1016  public function getCacheKeyInfo()
1017  {
1018  return [$this->getNameInLayout()];
1019  }
1020 
1026  public function getCacheKey()
1027  {
1028  if ($this->hasData('cache_key')) {
1029  return static::CACHE_KEY_PREFIX . $this->getData('cache_key');
1030  }
1031 
1036  $key = $this->getCacheKeyInfo();
1037 
1038  $key = array_values($key); // ignore array keys
1039 
1040  $key = implode('|', $key);
1041  $key = sha1($key); // use hashing to hide potentially private data
1042  return static::CACHE_KEY_PREFIX . $key;
1043  }
1044 
1050  protected function getCacheTags()
1051  {
1052  if (!$this->hasData('cache_tags')) {
1053  $tags = [];
1054  } else {
1055  $tags = $this->getData('cache_tags');
1056  }
1057  $tags[] = self::CACHE_GROUP;
1058 
1059  if ($this instanceof IdentityInterface) {
1060  $tags = array_merge($tags, $this->getIdentities());
1061  }
1062  return $tags;
1063  }
1064 
1070  protected function getCacheLifetime()
1071  {
1072  if (!$this->hasData('cache_lifetime')) {
1073  return null;
1074  }
1075 
1076  $cacheLifetime = $this->getData('cache_lifetime');
1077  if (false === $cacheLifetime || null === $cacheLifetime) {
1078  return null;
1079  }
1080 
1081  return (int)$cacheLifetime;
1082  }
1083 
1089  protected function _loadCache()
1090  {
1091  if ($this->getCacheLifetime() === null || !$this->_cacheState->isEnabled(self::CACHE_GROUP)) {
1092  return false;
1093  }
1094  $cacheKey = $this->getCacheKey();
1095  $cacheData = $this->_cache->load($cacheKey);
1096  if ($cacheData) {
1097  $cacheData = str_replace(
1098  $this->_getSidPlaceholder($cacheKey),
1099  $this->_sidResolver->getSessionIdQueryParam($this->_session) . '=' . $this->_session->getSessionId(),
1100  $cacheData
1101  );
1102  }
1103  return $cacheData;
1104  }
1105 
1112  protected function _saveCache($data)
1113  {
1114  if (!$this->getCacheLifetime() || !$this->_cacheState->isEnabled(self::CACHE_GROUP)) {
1115  return false;
1116  }
1117  $cacheKey = $this->getCacheKey();
1118  $data = str_replace(
1119  $this->_sidResolver->getSessionIdQueryParam($this->_session) . '=' . $this->_session->getSessionId(),
1120  $this->_getSidPlaceholder($cacheKey),
1121  $data
1122  );
1123 
1124  $this->_cache->save($data, $cacheKey, array_unique($this->getCacheTags()), $this->getCacheLifetime());
1125  return $this;
1126  }
1127 
1134  protected function _getSidPlaceholder($cacheKey = null)
1135  {
1136  if ($cacheKey === null) {
1137  $cacheKey = $this->getCacheKey();
1138  }
1139 
1140  return '<!--SID=' . $cacheKey . '-->';
1141  }
1142 
1152  public function getVar($name, $module = null)
1153  {
1154  $module = $module ?: $this->getModuleName();
1155  return $this->_viewConfig->getViewConfig()->getVarValue($module, $name);
1156  }
1157 
1165  public function isScopePrivate()
1166  {
1167  return $this->_isScopePrivate;
1168  }
1169 }
getJsId($arg1=null, $arg2=null, $arg3=null, $arg4=null, $arg5=null)
__construct(\Magento\Framework\View\Element\Context $context, array $data=[])
getData($key='', $index=null)
Definition: DataObject.php:119
getUiId($arg1=null, $arg2=null, $arg3=null, $arg4=null, $arg5=null)
formatDate( $date=null, $format=\IntlDateFormatter::SHORT, $showTime=false, $timezone=null)
formatTime( $time=null, $format=\IntlDateFormatter::SHORT, $showDate=false)
setLayout(\Magento\Framework\View\LayoutInterface $layout)
$quote
stripTags($data, $allowableTags=null, $allowHtmlEntities=false)
_getNotFoundUrl($route='', $params=['_direct'=> 'core/index/notFound'])
$block
Definition: block.php:8
$value
Definition: gender.phtml:16
$format
Definition: list.phtml:12
getChildChildHtml($alias, $childChildAlias='', $useCache=true)
setData($key, $value=null)
Definition: DataObject.php:72
$children
Definition: actions.phtml:11
escapeHtmlAttr($string, $escapeSingleQuote=true)
if(!trim($html)) $alias
Definition: details.phtml:20
insert($element, $siblingName=0, $after=true, $alias='')
$params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE]
Definition: website.php:18
$elementName
Definition: gallery.phtml:10
if($currentSelectedMethod==$_code) $className
Definition: form.phtml:31
unsetCallChild($alias, $callback, $result, $params)
if(!isset($_GET['name'])) $name
Definition: log.php:14
$element
Definition: element.phtml:12