You need to sign in or sign up before continuing.
UiComponentGenerator.php 2.29 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
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Magento\Ui\Model;

use Magento\Framework\View\Element\UiComponent\ContextFactory;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Framework\View\Element\UiComponentInterface;

/**
 * Dynamically generate UI Component
 *
 * Sometimes we need to generate components dynamically (not from layout).
 * The basic example, is creating widget UI component, based on CMS page or CMS block
 * directive
 */
class UiComponentGenerator
{
    /**
     * @var ContextFactory
     */
    private $contextFactory;

    /**
     * @var UiComponentFactory
     */
    private $uiComponentFactory;

    /**
     * UiComponentGenerator constructor.
     * @param ContextFactory $contextFactory
     * @param UiComponentFactory $uiComponentFactory
     */
    public function __construct(
        ContextFactory $contextFactory,
        UiComponentFactory $uiComponentFactory
    ) {
        $this->contextFactory = $contextFactory;
        $this->uiComponentFactory = $uiComponentFactory;
    }

    /**
     * Allows to generate Ui component
     *
     * @param string $name
     * @param \Magento\Framework\View\LayoutInterface $layout
     * @return UiComponentInterface
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function generateUiComponent($name, \Magento\Framework\View\LayoutInterface $layout)
    {
        $context = $this->contextFactory->create([
            'namespace' => $name,
            'pageLayout' => $layout,
        ]);

        $component = $this->uiComponentFactory->create(
            $name,
            null,
            [
                'context' => $context
            ]
        );
        return $this->prepareComponent($component);
    }

    /**
     * Call prepare method in the component UI
     *
     * @param UiComponentInterface $component
     * @return UiComponentInterface
     */
    private function prepareComponent(UiComponentInterface $component)
    {
        $childComponents = $component->getChildComponents();
        if (!empty($childComponents)) {
            foreach ($childComponents as $child) {
                $this->prepareComponent($child);
            }
        }
        $component->prepare();

        return $component;
    }
}