Menu.php 7.9 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
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Magento\Backend\Model;

use Magento\Backend\Model\Menu\Item;
use Magento\Backend\Model\Menu\Item\Factory;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Serialize\SerializerInterface;
use Psr\Log\LoggerInterface;

/**
 * Backend menu model
 *
 * @api
 * @since 100.0.2
 */
class Menu extends \ArrayObject
{
    /**
     * Path in tree structure
     *
     * @var string
     */
    protected $_path = '';

    /**
     * @var LoggerInterface
     */
    protected $_logger;

    /**
     * @var Factory
     */
    private $menuItemFactory;

    /**
     * @var SerializerInterface
     */
    private $serializer;

    /**
     * Menu constructor
     *
     * @param LoggerInterface $logger
     * @param string $pathInMenuStructure
     * @param Factory|null $menuItemFactory
     * @param SerializerInterface|null $serializer
     */
    public function __construct(
        LoggerInterface $logger,
        $pathInMenuStructure = '',
        Factory $menuItemFactory = null,
        SerializerInterface $serializer = null
    ) {
        if ($pathInMenuStructure) {
            $this->_path = $pathInMenuStructure . '/';
        }
        $this->_logger = $logger;
        $this->setIteratorClass(\Magento\Backend\Model\Menu\Iterator::class);
        $this->menuItemFactory = $menuItemFactory ?: ObjectManager::getInstance()
            ->create(Factory::class);
        $this->serializer = $serializer ?: ObjectManager::getInstance()->create(SerializerInterface::class);
    }

    /**
     * Add child to menu item
     *
     * @param Item $item
     * @param string $parentId
     * @param int $index
     * @return void
     * @throws \InvalidArgumentException
     */
    public function add(Item $item, $parentId = null, $index = null)
    {
        if ($parentId !== null) {
            $parentItem = $this->get($parentId);
            if ($parentItem === null) {
                throw new \InvalidArgumentException("Item with identifier {$parentId} does not exist");
            }
            $parentItem->getChildren()->add($item, null, $index);
        } else {
            $index = (int) $index;
            if (!isset($this[$index])) {
                $this->offsetSet($index, $item);
                $this->_logger->info(
                    sprintf('Add of item with id %s was processed', $item->getId())
                );
            } else {
                $this->add($item, $parentId, $index + 1);
            }
        }
    }

    /**
     * Retrieve menu item by id
     *
     * @param string $itemId
     * @return Item|null
     */
    public function get($itemId)
    {
        $result = null;
        /** @var Item $item */
        foreach ($this as $item) {
            if ($item->getId() == $itemId) {
                $result = $item;
                break;
            }

            if ($item->hasChildren() && ($result = $item->getChildren()->get($itemId))) {
                break;
            }
        }
        return $result;
    }

    /**
     * Move menu item
     *
     * @param string $itemId
     * @param string $toItemId
     * @param int $sortIndex
     * @return void
     * @throws \InvalidArgumentException
     */
    public function move($itemId, $toItemId, $sortIndex = null)
    {
        $item = $this->get($itemId);
        if ($item === null) {
            throw new \InvalidArgumentException("Item with identifier {$itemId} does not exist");
        }
        $this->remove($itemId);
        $this->add($item, $toItemId, $sortIndex);
    }

    /**
     * Remove menu item by id
     *
     * @param string $itemId
     * @return bool
     */
    public function remove($itemId)
    {
        $result = false;
        /** @var Item $item */
        foreach ($this as $key => $item) {
            if ($item->getId() == $itemId) {
                unset($this[$key]);
                $result = true;
                $this->_logger->info(
                    sprintf('Remove on item with id %s was processed', $item->getId())
                );
                break;
            }

            if ($item->hasChildren() && ($result = $item->getChildren()->remove($itemId))) {
                break;
            }
        }
        return $result;
    }

    /**
     * Change order of an item in its parent menu
     *
     * @param string $itemId
     * @param int $position
     * @return bool
     */
    public function reorder($itemId, $position)
    {
        $result = false;
        /** @var Item $item */
        foreach ($this as $key => $item) {
            if ($item->getId() == $itemId) {
                unset($this[$key]);
                $this->add($item, null, $position);
                $result = true;
                break;
            } elseif ($item->hasChildren() && $result = $item->getChildren()->reorder($itemId, $position)) {
                break;
            }
        }
        return $result;
    }

    /**
     * Check whether provided item is last in list
     *
     * @param Item $item
     * @return bool
     */
    public function isLast(Item $item)
    {
        return $this->offsetGet(max(array_keys($this->getArrayCopy())))->getId() == $item->getId();
    }

    /**
     * Find first menu item that user is able to access
     *
     * @return Item|null
     */
    public function getFirstAvailable()
    {
        $result = null;
        /** @var Item $item */
        foreach ($this as $item) {
            if ($item->isAllowed() && !$item->isDisabled()) {
                if ($item->hasChildren()) {
                    $result = $item->getChildren()->getFirstAvailable();
                    if (false == ($result === null)) {
                        break;
                    }
                } else {
                    $result = $item;
                    break;
                }
            }
        }
        return $result;
    }

    /**
     * Get parent items by item id
     *
     * @param string $itemId
     * @return Item[]
     */
    public function getParentItems($itemId)
    {
        $parents = [];
        $this->_findParentItems($this, $itemId, $parents);
        return array_reverse($parents);
    }

    /**
     * Find parent items
     *
     * @param \Magento\Backend\Model\Menu $menu
     * @param string $itemId
     * @param array &$parents
     * @return bool
     */
    protected function _findParentItems($menu, $itemId, &$parents)
    {
        /** @var Item $item */
        foreach ($menu as $item) {
            if ($item->getId() == $itemId) {
                return true;
            }
            if ($item->hasChildren()) {
                if ($this->_findParentItems($item->getChildren(), $itemId, $parents)) {
                    $parents[] = $item;
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Serialize menu
     *
     * @return string
     */
    public function serialize()
    {
        return $this->serializer->serialize($this->toArray());
    }

    /**
     * Get menu data represented as an array
     *
     * @return array
     * @since 100.2.0
     */
    public function toArray()
    {
        $data = [];
        foreach ($this as $item) {
            $data[] = $item->toArray();
        }
        return $data;
    }

    /**
     * Unserialize menu
     *
     * @param string $serialized
     * @return void
     * @since 100.2.0
     */
    public function unserialize($serialized)
    {
        $data = $this->serializer->unserialize($serialized);
        $this->populateFromArray($data);
    }

    /**
     * Populate the menu with data from array
     *
     * @param array $data
     * @return void
     * @since 100.2.0
     */
    public function populateFromArray(array $data)
    {
        $items = [];
        foreach ($data as $itemData) {
            $item = $this->menuItemFactory->create($itemData);
            $items[] = $item;
        }
        $this->exchangeArray($items);
    }
}