1<?php
2
3declare(strict_types=1);
4
5/*
6 * This file is part of the TYPO3 CMS project.
7 *
8 * It is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, either version 2
10 * of the License, or any later version.
11 *
12 * For the full copyright and license information, please read the
13 * LICENSE.txt file that was distributed with this source code.
14 *
15 * The TYPO3 project - inspiring people to share!
16 */
17
18namespace TYPO3\CMS\Form\Hooks;
19
20use TYPO3\CMS\Filelist\ContextMenu\ItemProviders\FileProvider;
21use TYPO3\CMS\Form\Mvc\Persistence\FormPersistenceManager;
22
23/**
24 * Purges previously added form files from items for context menus.
25 * @internal
26 */
27class FormFileProvider extends FileProvider
28{
29    /**
30     * @var array
31     */
32    protected $itemsConfiguration = [];
33
34    /**
35     * Lowest priority, thus gets executed last.
36     *
37     * @return int
38     */
39    public function getPriority(): int
40    {
41        return 0;
42    }
43
44    /**
45     * @return bool
46     */
47    public function canHandle(): bool
48    {
49        return parent::canHandle()
50            && str_ends_with($this->identifier, FormPersistenceManager::FORM_DEFINITION_FILE_EXTENSION);
51    }
52
53    /**
54     * @param array $items
55     * @return array
56     */
57    public function addItems(array $items): array
58    {
59        $this->initialize();
60        return $this->purgeItems($items);
61    }
62
63    /**
64     * Purges items that are not allowed for according command.
65     * According canBeEdited, canBeRenamed, ... commands will always return
66     * false in order to remove those form file items.
67     *
68     * Using the canRender() approach avoid adding hardcoded index name
69     * lookup. Thus, it's streamlined with the rest of the provides, but
70     * actually purges items instead of adding them.
71     *
72     * @param array $items
73     * @return array
74     */
75    protected function purgeItems(array $items): array
76    {
77        foreach ($items as $name => $item) {
78            $type = $item['type'];
79
80            if ($type === 'submenu' && !empty($item['childItems'])) {
81                $item['childItems'] = $this->purgeItems($item['childItems']);
82            } elseif (!$this->canRender($name, $type)) {
83                unset($items[$name]);
84            }
85        }
86
87        return $items;
88    }
89
90    /**
91     * @return bool
92     */
93    protected function canBeEdited(): bool
94    {
95        return false;
96    }
97
98    /**
99     * @return bool
100     */
101    protected function canBeRenamed(): bool
102    {
103        return false;
104    }
105}
106