Merge.php 27.1 KB
Newer Older
Ketan's avatar
Ketan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Magento\Framework\View\Model\Layout;

use Magento\Framework\App\State;
use Magento\Framework\Config\Dom\ValidationException;
use Magento\Framework\Filesystem\DriverPool;
use Magento\Framework\Filesystem\File\ReadFactory;
use Magento\Framework\View\Layout\LayoutCacheKeyInterface;
use Magento\Framework\View\Model\Layout\Update\Validator;

/**
 * Layout merge model
 * @SuppressWarnings(PHPMD.TooManyFields)
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class Merge implements \Magento\Framework\View\Layout\ProcessorInterface
{
    /**
     * Layout abstraction based on designer prerogative.
     */
    const DESIGN_ABSTRACTION_CUSTOM = 'custom';

    /**
     * Layout generalization guaranteed to load into View
     */
    const DESIGN_ABSTRACTION_PAGE_LAYOUT = 'page_layout';

    /**
     * XPath of handles originally declared in layout updates
     */
    const XPATH_HANDLE_DECLARATION = '/layout[@design_abstraction]';

    /**
     * Name of an attribute that stands for data type of node values
     */
    const TYPE_ATTRIBUTE = 'xsi:type';

    /**
     * Cache id suffix for page layout
     */
    const PAGE_LAYOUT_CACHE_SUFFIX = 'page_layout';

    /**
     * @var \Magento\Framework\View\Design\ThemeInterface
     */
    private $theme;

    /**
     * @var \Magento\Framework\Url\ScopeInterface
     */
    private $scope;

    /**
     * In-memory cache for loaded layout updates
     *
     * @var \Magento\Framework\View\Layout\Element
     */
    protected $layoutUpdatesCache;

    /**
     * Cumulative array of update XML strings
     *
     * @var array
     */
    protected $updates = [];

    /**
     * Handles used in this update
     *
     * @var array
     */
    protected $handles = [];

    /**
     * Page handle names sorted by from parent to child
     *
     * @var array
     */
    protected $pageHandles = [];

    /**
     * Substitution values in structure array('from' => array(), 'to' => array())
     *
     * @var array|null
     */
    protected $subst = null;

    /**
     * @var \Magento\Framework\View\File\CollectorInterface
     */
    private $fileSource;

    /**
     * @var \Magento\Framework\View\File\CollectorInterface
     */
    private $pageLayoutFileSource;

    /**
     * @var \Magento\Framework\App\State
     */
    private $appState;

    /**
     * Cache keys to be able to generate different cache id for same handles
     *
     * @var LayoutCacheKeyInterface
     */
    private $layoutCacheKey;

    /**
     * @var \Magento\Framework\Cache\FrontendInterface
     */
    protected $cache;

    /**
     * @var \Magento\Framework\View\Model\Layout\Update\Validator
     */
    protected $layoutValidator;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    /**
     * @var string
     */
    protected $pageLayout;

    /**
     * @var string
     */
    protected $cacheSuffix;

    /**
     * All processed handles used in this update
     *
     * @var array
     */
    protected $allHandles = [];

    /**
     * Status for handle being processed
     *
     * @var int
     */
    protected $handleProcessing = 1;

    /**
     * Status for processed handle
     *
     * @var int
     */
    protected $handleProcessed = 2;

    /**
     * @var ReadFactory
     */
    private $readFactory;

    /**
     * Init merge model
     *
     * @param \Magento\Framework\View\DesignInterface $design
     * @param \Magento\Framework\Url\ScopeResolverInterface $scopeResolver
     * @param \Magento\Framework\View\File\CollectorInterface $fileSource
     * @param \Magento\Framework\View\File\CollectorInterface $pageLayoutFileSource
     * @param \Magento\Framework\App\State $appState
     * @param \Magento\Framework\Cache\FrontendInterface $cache
     * @param \Magento\Framework\View\Model\Layout\Update\Validator $validator
     * @param \Psr\Log\LoggerInterface $logger
     * @param ReadFactory $readFactory ,
     * @param \Magento\Framework\View\Design\ThemeInterface $theme Non-injectable theme instance
     * @param string $cacheSuffix
     * @param LayoutCacheKeyInterface $layoutCacheKey
     * @SuppressWarnings(PHPMD.ExcessiveParameterList)
     */
    public function __construct(
        \Magento\Framework\View\DesignInterface $design,
        \Magento\Framework\Url\ScopeResolverInterface $scopeResolver,
        \Magento\Framework\View\File\CollectorInterface $fileSource,
        \Magento\Framework\View\File\CollectorInterface $pageLayoutFileSource,
        \Magento\Framework\App\State $appState,
        \Magento\Framework\Cache\FrontendInterface $cache,
        \Magento\Framework\View\Model\Layout\Update\Validator $validator,
        \Psr\Log\LoggerInterface $logger,
        ReadFactory $readFactory,
        \Magento\Framework\View\Design\ThemeInterface $theme = null,
        $cacheSuffix = '',
        LayoutCacheKeyInterface $layoutCacheKey = null
    ) {
        $this->theme = $theme ?: $design->getDesignTheme();
        $this->scope = $scopeResolver->getScope();
        $this->fileSource = $fileSource;
        $this->pageLayoutFileSource = $pageLayoutFileSource;
        $this->appState = $appState;
        $this->cache = $cache;
        $this->layoutValidator = $validator;
        $this->logger = $logger;
        $this->readFactory = $readFactory;
        $this->cacheSuffix = $cacheSuffix;
        $this->layoutCacheKey = $layoutCacheKey
            ?: \Magento\Framework\App\ObjectManager::getInstance()->get(LayoutCacheKeyInterface::class);
    }

    /**
     * Add XML update instruction
     *
     * @param string $update
     * @return $this
     */
    public function addUpdate($update)
    {
        if (!in_array($update, $this->updates)) {
            $this->updates[] = $update;
        }
        return $this;
    }

    /**
     * Get all registered updates as array
     *
     * @return array
     */
    public function asArray()
    {
        return $this->updates;
    }

    /**
     * Get all registered updates as string
     *
     * @return string
     */
    public function asString()
    {
        return implode('', $this->updates);
    }

    /**
     * Add handle(s) to update
     *
     * @param array|string $handleName
     * @return $this
     */
    public function addHandle($handleName)
    {
        if (is_array($handleName)) {
            foreach ($handleName as $name) {
                $this->handles[$name] = 1;
            }
        } else {
            $this->handles[$handleName] = 1;
        }
        return $this;
    }

    /**
     * Remove handle from update
     *
     * @param string $handleName
     * @return $this
     */
    public function removeHandle($handleName)
    {
        unset($this->handles[$handleName]);
        return $this;
    }

    /**
     * Get handle names array
     *
     * @return array
     */
    public function getHandles()
    {
        return array_keys($this->handles);
    }

    /**
     * Add the first existing (declared in layout updates) page handle along with all parents to the update.
     * Return whether any page handles have been added or not.
     *
     * @param string[] $handlesToTry
     * @return bool
     */
    public function addPageHandles(array $handlesToTry)
    {
        $handlesAdded = false;
        foreach ($handlesToTry as $handleName) {
            if (!$this->pageHandleExists($handleName)) {
                continue;
            }
            $handles[] = $handleName;
            $this->pageHandles = $handles;
            $this->addHandle($handles);
            $handlesAdded = true;
        }
        return $handlesAdded;
    }

    /**
     * Whether a page handle is declared in the system or not
     *
     * @param string $handleName
     * @return bool
     */
    public function pageHandleExists($handleName)
    {
        return (bool)$this->_getPageHandleNode($handleName);
    }

    /**
     * @return string|null
     */
    public function getPageLayout()
    {
        return $this->pageLayout;
    }

    /**
     * Check current handles if layout was defined on it
     *
     * @return bool
     */
    public function isLayoutDefined()
    {
        $fullLayoutXml = $this->getFileLayoutUpdatesXml();
        foreach ($this->getHandles() as $handle) {
            if ($fullLayoutXml->xpath("layout[@id='{$handle}']")) {
                return true;
            }
        }
        return false;
    }

    /**
     * Get handle xml node by handle name
     *
     * @param string $handleName
     * @return \Magento\Framework\View\Layout\Element|null
     */
    protected function _getPageHandleNode($handleName)
    {
        /* quick validation for non-existing page types */
        if (!$handleName) {
            return null;
        }
        $handles = $this->getFileLayoutUpdatesXml()->xpath("handle[@id='{$handleName}']");
        if (empty($handles)) {
            return null;
        }
        $nodes = $this->getFileLayoutUpdatesXml()->xpath("/layouts/handle[@id=\"{$handleName}\"]");
        return $nodes ? reset($nodes) : null;
    }

    /**
     * Retrieve used page handle names sorted from parent to child
     *
     * @return array
     */
    public function getPageHandles()
    {
        return $this->pageHandles;
    }

    /**
     * Retrieve all design abstractions that exist in the system.
     *
     * Result format:
     * array(
     *     'handle_name_1' => array(
     *         'name'     => 'handle_name_1',
     *         'label'    => 'Handle Name 1',
     *         'design_abstraction' => self::DESIGN_ABSTRACTION_PAGE_LAYOUT or self::DESIGN_ABSTRACTION_CUSTOM
     *     ),
     *     // ...
     * )
     *
     * @return array
     */
    public function getAllDesignAbstractions()
    {
        $result = [];

        $conditions = [
            '(@design_abstraction="' . self::DESIGN_ABSTRACTION_PAGE_LAYOUT .
            '" or @design_abstraction="' . self::DESIGN_ABSTRACTION_CUSTOM . '")',
        ];
        $xpath = '/layouts/*[' . implode(' or ', $conditions) . ']';
        $nodes = $this->getFileLayoutUpdatesXml()->xpath($xpath) ?: [];
        /** @var $node \Magento\Framework\View\Layout\Element */
        foreach ($nodes as $node) {
            $name = $node->getAttribute('id');
            $info = [
                'name' => $name,
                'label' => (string)new \Magento\Framework\Phrase((string)$node->getAttribute('label')),
                'design_abstraction' => $node->getAttribute('design_abstraction'),
            ];
            $result[$name] = $info;
        }
        return $result;
    }

    /**
     * Retrieve the type of a page handle
     *
     * @param string $handleName
     * @return string|null
     */
    public function getPageHandleType($handleName)
    {
        $node = $this->_getPageHandleNode($handleName);
        return $node ? $node->getAttribute('type') : null;
    }

    /**
     * Load layout updates by handles
     *
     * @param array|string $handles
     * @throws \Magento\Framework\Exception\LocalizedException
     * @return $this
     */
    public function load($handles = [])
    {
        if (is_string($handles)) {
            $handles = [$handles];
        } elseif (!is_array($handles)) {
            throw new \Magento\Framework\Exception\LocalizedException(
                new \Magento\Framework\Phrase('Invalid layout update handle')
            );
        }

        $this->addHandle($handles);

        $cacheId = $this->getCacheId();
        $cacheIdPageLayout = $cacheId . '_' . self::PAGE_LAYOUT_CACHE_SUFFIX;
        $result = $this->_loadCache($cacheId);
        if ($result) {
            $this->addUpdate($result);
            $this->pageLayout = $this->_loadCache($cacheIdPageLayout);
            foreach ($this->getHandles() as $handle) {
                $this->allHandles[$handle] = $this->handleProcessed;
            }
            return $this;
        }

        foreach ($this->getHandles() as $handle) {
            $this->_merge($handle);
        }

        $layout = $this->asString();
        $this->_validateMergedLayout($cacheId, $layout);
        $this->_saveCache($layout, $cacheId, $this->getHandles());
        $this->_saveCache((string)$this->pageLayout, $cacheIdPageLayout, $this->getHandles());
        return $this;
    }

    /**
     * Validate merged layout
     *
     * @param string $cacheId
     * @param string $layout
     * @return $this
     * @throws \Exception
     */
    protected function _validateMergedLayout($cacheId, $layout)
    {
        $layoutStr = '<handle id="handle">' . $layout . '</handle>';

        try {
            $this->layoutValidator->isValid($layoutStr, Validator::LAYOUT_SCHEMA_MERGED, false);
        } catch (\Exception $e) {
            $messages = $this->layoutValidator->getMessages();
            //Add first message to exception
            $message = reset($messages);
            $this->logger->info(
                'Cache file with merged layout: ' . $cacheId
                . ' and handles ' . implode(', ', (array)$this->getHandles()) . ': ' . $message
            );
            if ($this->appState->getMode() === \Magento\Framework\App\State::MODE_DEVELOPER) {
                throw $e;
            }
        }

        return $this;
    }

    /**
     * Get layout updates as \Magento\Framework\View\Layout\Element object
     *
     * @return \SimpleXMLElement
     */
    public function asSimplexml()
    {
        $updates = trim($this->asString());
        $updates = '<?xml version="1.0"?>'
            . '<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
            . $updates
            . '</layout>';
        return $this->_loadXmlString($updates);
    }

    /**
     * Return object representation of XML string
     *
     * @param string $xmlString
     * @return \SimpleXMLElement
     */
    protected function _loadXmlString($xmlString)
    {
        return simplexml_load_string($xmlString, \Magento\Framework\View\Layout\Element::class);
    }

    /**
     * Merge layout update by handle
     *
     * @param string $handle
     * @return $this
     */
    protected function _merge($handle)
    {
        if (!isset($this->allHandles[$handle])) {
            $this->allHandles[$handle] = $this->handleProcessing;
            $this->_fetchPackageLayoutUpdates($handle);
            $this->_fetchDbLayoutUpdates($handle);
            $this->allHandles[$handle] = $this->handleProcessed;
        } elseif ($this->allHandles[$handle] == $this->handleProcessing
            && $this->appState->getMode() === \Magento\Framework\App\State::MODE_DEVELOPER
        ) {
            $this->logger->info('Cyclic dependency in merged layout for handle: ' . $handle);
        }
        return $this;
    }

    /**
     * Add updates for the specified handle
     *
     * @param string $handle
     * @return bool
     */
    protected function _fetchPackageLayoutUpdates($handle)
    {
        $_profilerKey = 'layout_package_update:' . $handle;
        \Magento\Framework\Profiler::start($_profilerKey);
        $layout = $this->getFileLayoutUpdatesXml();
        foreach ($layout->xpath("*[self::handle or self::layout][@id='{$handle}']") as $updateXml) {
            $this->_fetchRecursiveUpdates($updateXml);
            $updateInnerXml = $updateXml->innerXml();
            $this->validateUpdate($handle, $updateInnerXml);
            $this->addUpdate($updateInnerXml);
        }
        \Magento\Framework\Profiler::stop($_profilerKey);

        return true;
    }

    /**
     * Fetch & add layout updates for the specified handle from the database
     *
     * @param string $handle
     * @return bool
     */
    protected function _fetchDbLayoutUpdates($handle)
    {
        $_profilerKey = 'layout_db_update: ' . $handle;
        \Magento\Framework\Profiler::start($_profilerKey);
        $updateStr = $this->getDbUpdateString($handle);
        if (!$updateStr) {
            \Magento\Framework\Profiler::stop($_profilerKey);
            return false;
        }
        $updateStr = '<update_xml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' .
            $updateStr .
            '</update_xml>';
        $updateStr = $this->_substitutePlaceholders($updateStr);
        $updateXml = $this->_loadXmlString($updateStr);
        $this->_fetchRecursiveUpdates($updateXml);
        $updateInnerXml = $updateXml->innerXml();
        $this->validateUpdate($handle, $updateInnerXml);
        $this->addUpdate($updateInnerXml);

        \Magento\Framework\Profiler::stop($_profilerKey);
        return (bool)$updateStr;
    }

    /**
     * Validate layout update content, throw exception on failure.
     *
     * This method is used as a hook for plugins.
     *
     * @param string $handle
     * @param string $updateXml
     * @return void
     * @throws \Exception
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     * @codeCoverageIgnore
     */
    public function validateUpdate($handle, $updateXml)
    {
        return;
    }

    /**
     * Substitute placeholders {{placeholder_name}} with their values in XML string
     *
     * @param string $xmlString
     * @return string
     */
    protected function _substitutePlaceholders($xmlString)
    {
        if ($this->subst === null) {
            $placeholders = [
                'baseUrl' => $this->scope->getBaseUrl(),
                'baseSecureUrl' => $this->scope->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK, true),
            ];
            $this->subst = [];
            foreach ($placeholders as $key => $value) {
                $this->subst['from'][] = '{{' . $key . '}}';
                $this->subst['to'][] = $value;
            }
        }
        return str_replace($this->subst['from'], $this->subst['to'], $xmlString);
    }

    /**
     * Get update string
     *
     * @param string $handle
     * @return string
     *
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function getDbUpdateString($handle)
    {
        return null;
    }

    /**
     * Add handles declared as '<update handle="handle_name"/>' directives
     *
     * @param \SimpleXMLElement $updateXml
     * @return $this
     */
    protected function _fetchRecursiveUpdates($updateXml)
    {
        foreach ($updateXml->children() as $child) {
            if (strtolower($child->getName()) == 'update' && isset($child['handle'])) {
                $this->_merge((string)$child['handle']);
            }
        }
        if (isset($updateXml['layout'])) {
            $this->pageLayout = (string)$updateXml['layout'];
        }
        return $this;
    }

    /**
     * Retrieve already merged layout updates from files for specified area/theme/package/store
     *
     * @return \Magento\Framework\View\Layout\Element
     */
    public function getFileLayoutUpdatesXml()
    {
        if ($this->layoutUpdatesCache) {
            return $this->layoutUpdatesCache;
        }
        $cacheId = $this->generateCacheId($this->cacheSuffix);
        $result = $this->_loadCache($cacheId);
        if ($result) {
            $result = $this->_loadXmlString($result);
        } else {
            $result = $this->_loadFileLayoutUpdatesXml();
            $this->_saveCache($result->asXML(), $cacheId);
        }
        $this->layoutUpdatesCache = $result;
        return $result;
    }

    /**
     * Generate cache identifier taking into account current area/package/theme/store
     *
     * @param string $suffix
     * @return string
     */
    protected function generateCacheId($suffix = '')
    {
        return "LAYOUT_{$this->theme->getArea()}_STORE{$this->scope->getId()}_{$this->theme->getId()}{$suffix}";
    }

    /**
     * Retrieve data from the cache, if the layout caching is allowed, or FALSE otherwise
     *
     * @param string $cacheId
     * @return string|bool
     */
    protected function _loadCache($cacheId)
    {
        return $this->cache->load($cacheId);
    }

    /**
     * Save data to the cache, if the layout caching is allowed
     *
     * @param string $data
     * @param string $cacheId
     * @param array $cacheTags
     * @return void
     */
    protected function _saveCache($data, $cacheId, array $cacheTags = [])
    {
        $this->cache->save($data, $cacheId, $cacheTags, null);
    }

    /**
     * Collect and merge layout updates from files
     *
     * @return \Magento\Framework\View\Layout\Element
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    protected function _loadFileLayoutUpdatesXml()
    {
        $layoutStr = '';
        $theme = $this->_getPhysicalTheme($this->theme);
        $updateFiles = $this->fileSource->getFiles($theme, '*.xml');
        $updateFiles = array_merge($updateFiles, $this->pageLayoutFileSource->getFiles($theme, '*.xml'));
        $useErrors = libxml_use_internal_errors(true);
        foreach ($updateFiles as $file) {
            /** @var $fileReader \Magento\Framework\Filesystem\File\Read */
            $fileReader = $this->readFactory->create($file->getFilename(), DriverPool::FILE);
            $fileStr = $fileReader->readAll($file->getName());
            $fileStr = $this->_substitutePlaceholders($fileStr);
            /** @var $fileXml \Magento\Framework\View\Layout\Element */
            $fileXml = $this->_loadXmlString($fileStr);
            if (!$fileXml instanceof \Magento\Framework\View\Layout\Element) {
                $xmlErrors = $this->getXmlErrors(libxml_get_errors());
                $this->_logXmlErrors($file->getFilename(), $xmlErrors);
                if ($this->appState->getMode() === State::MODE_DEVELOPER) {
                    throw new ValidationException(
                        new \Magento\Framework\Phrase(
                            "Theme layout update file '%1' is not valid.\n%2",
                            [
                                $file->getFilename(),
                                implode("\n", $xmlErrors)
                            ]
                        )
                    );
                }
                libxml_clear_errors();
                continue;
            }
            if (!$file->isBase() && $fileXml->xpath(self::XPATH_HANDLE_DECLARATION)) {
                throw new \Magento\Framework\Exception\LocalizedException(
                    new \Magento\Framework\Phrase(
                        'Theme layout update file \'%1\' must not declare page types.',
                        [$file->getFileName()]
                    )
                );
            }
            $handleName = basename($file->getFilename(), '.xml');
            $tagName = $fileXml->getName() === 'layout' ? 'layout' : 'handle';
            $handleAttributes = ' id="' . $handleName . '"' . $this->_renderXmlAttributes($fileXml);
            $handleStr = '<' . $tagName . $handleAttributes . '>' . $fileXml->innerXml() . '</' . $tagName . '>';
            $layoutStr .= $handleStr;
        }
        libxml_use_internal_errors($useErrors);
        $layoutStr = '<layouts xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' . $layoutStr . '</layouts>';
        $layoutXml = $this->_loadXmlString($layoutStr);
        return $layoutXml;
    }

    /**
     * Log xml errors to system log
     *
     * @param string $fileName
     * @param array $xmlErrors
     * @return void
     */
    protected function _logXmlErrors($fileName, $xmlErrors)
    {
        $this->logger->info(
            sprintf("Theme layout update file '%s' is not valid.\n%s", $fileName, implode("\n", $xmlErrors))
        );
    }

    /**
     * Get formatted xml errors
     *
     * @param array $libXmlErrors
     * @return array
     */
    private function getXmlErrors($libXmlErrors)
    {
        $errors = [];
        if (count($libXmlErrors)) {
            foreach ($libXmlErrors as $error) {
                $errors[] = "{$error->message} Line: {$error->line}";
            }
        }
        return $errors;
    }

    /**
     * Find the closest physical theme among ancestors and a theme itself
     *
     * @param \Magento\Framework\View\Design\ThemeInterface $theme
     * @return \Magento\Theme\Model\Theme
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    protected function _getPhysicalTheme(\Magento\Framework\View\Design\ThemeInterface $theme)
    {
        $result = $theme;
        while ($result !== null && $result->getId() && !$result->isPhysical()) {
            $result = $result->getParentTheme();
        }
        if (!$result) {
            throw new \Magento\Framework\Exception\LocalizedException(
                new \Magento\Framework\Phrase(
                    'Unable to find a physical ancestor for a theme \'%1\'.',
                    [$theme->getThemeTitle()]
                )
            );
        }
        return $result;
    }

    /**
     * Return attributes of XML node rendered as a string
     *
     * @param \SimpleXMLElement $node
     * @return string
     */
    protected function _renderXmlAttributes(\SimpleXMLElement $node)
    {
        $result = '';
        foreach ($node->attributes() as $attributeName => $attributeValue) {
            $result .= ' ' . $attributeName . '="' . $attributeValue . '"';
        }
        return $result;
    }

    /**
     * Retrieve containers from the update handles that have been already loaded
     *
     * Result format:
     * array(
     *     'container_name' => 'Container Label',
     *     // ...
     * )
     *
     * @return array
     */
    public function getContainers()
    {
        $result = [];
        $containerNodes = $this->asSimplexml()->xpath('//container');
        /** @var $oneContainerNode \Magento\Framework\View\Layout\Element */
        foreach ($containerNodes as $oneContainerNode) {
            $label = $oneContainerNode->getAttribute('label');
            if ($label) {
                $result[$oneContainerNode->getAttribute('name')] = (string)new \Magento\Framework\Phrase($label);
            }
        }
        return $result;
    }

    /**
     * Cleanup circular references
     *
     * Destructor should be called explicitly in order to work around the PHP bug
     * https://bugs.php.net/bug.php?id=62468
     */
    public function __destruct()
    {
        $this->updates = [];
        $this->layoutUpdatesCache = null;
    }

    /**
     * @inheritdoc
     */
    public function isCustomerDesignAbstraction(array $abstraction)
    {
        if (!isset($abstraction['design_abstraction'])) {
            return false;
        }
        return $abstraction['design_abstraction'] === self::DESIGN_ABSTRACTION_CUSTOM;
    }

    /**
     * @inheritdoc
     */
    public function isPageLayoutDesignAbstraction(array $abstraction)
    {
        if (!isset($abstraction['design_abstraction'])) {
            return false;
        }
        return $abstraction['design_abstraction'] === self::DESIGN_ABSTRACTION_PAGE_LAYOUT;
    }

    /**
     * Retrieve theme
     *
     * @return \Magento\Framework\View\Design\ThemeInterface
     */
    public function getTheme()
    {
        return $this->theme;
    }

    /**
     * Retrieve current scope
     *
     * @return \Magento\Framework\Url\ScopeInterface
     */
    public function getScope()
    {
        return $this->scope;
    }

    /**
     * Return cache ID based current area/package/theme/store and handles
     *
     * @return string
     */
    public function getCacheId()
    {
        $layoutCacheKeys = $this->layoutCacheKey->getCacheKeys();
        return $this->generateCacheId(md5(implode('|', array_merge($this->getHandles(), $layoutCacheKeys))));
    }
}