InheritancesResolverService.php 12.3 KB
Newer Older
1
<?php
2
declare(strict_types = 1);
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
namespace TYPO3\CMS\Form\Mvc\Configuration;

/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

18
use TYPO3\CMS\Core\Utility\ArrayUtility;
19
use TYPO3\CMS\Core\Utility\Exception\MissingArrayPathException;
20
21
22
23
24
25
26
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\ObjectManager;
use TYPO3\CMS\Form\Mvc\Configuration\Exception\CycleInheritancesException;

/**
 * Resolve declared inheritances within an configuration array
 *
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
 * Basic concept:
 * - Take a large YAML config and replace the key '__inheritance' by the referenced YAML partial (of the same config file)
 * - Maybe also override some keys of the referenced partial
 * - Avoid endless loop by reference cycles
 *
 * e.g.
 * ---------------------
 *
 * Form:
 *  part1:
 *    key1: value1
 *    key2: value2
 *    key3: value3
 *  part2:
 *    __inheritance:
 *      10: Form.part1
 *    key2: another_value
 *
 * will result in:
 * ---------------------
 *
 * Form:
 *  part1:
 *    key1: value1
 *    key2: value2
 *    key3: value3
 *  part2:
 *    key1: value1
 *    key2: another_value
 *    key3: value3
 *
 * ---------------------
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
 * Scope: frontend / backend
 * @internal
 */
class InheritancesResolverService
{

    /**
     * The operator which is used to declare inheritances
     */
    const INHERITANCE_OPERATOR = '__inheritances';

    /**
     * The reference configuration is used to get untouched values which
     * can be merged into the touched configuration.
     *
     * @var array
     */
    protected $referenceConfiguration = [];

    /**
     * This stack is needed to find cyclically inheritances which are on
     * the same nesting level but which do not follow each other directly.
     *
     * @var array
     */
    protected $inheritanceStack = [];

    /**
87
     * Needed to buffer a configuration path for cyclically inheritances
88
89
90
91
     * detection while inheritances for this path is ongoing.
     *
     * @var string
     */
92
    protected $inheritancePathToCheck = '';
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

    /**
     * Returns an instance of this service. Additionally the configuration
     * which should be resolved can be passed.
     *
     * @param array $configuration
     * @return InheritancesResolverService
     * @internal
     */
    public static function create(array $configuration = []): InheritancesResolverService
    {
        /** @var InheritancesResolverService $inheritancesResolverService */
        $inheritancesResolverService = GeneralUtility::makeInstance(ObjectManager::class)
            ->get(self::class);
        $inheritancesResolverService->setReferenceConfiguration($configuration);
        return $inheritancesResolverService;
    }

    /**
     * Reset the state of this service.
     * Mainly introduced for unit tests.
     *
     * @return InheritancesResolverService
     * @internal
     */
    public function reset()
    {
        $this->referenceConfiguration = [];
        $this->inheritanceStack = [];
122
        $this->inheritancePathToCheck = '';
123
124
125
126
127
128
129
        return $this;
    }

    /**
     * Set the reference configuration which is used to get untouched
     * values which can be merged into the touched configuration.
     *
130
     * @param array $referenceConfiguration
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
     * @return InheritancesResolverService
     */
    public function setReferenceConfiguration(array $referenceConfiguration)
    {
        $this->referenceConfiguration = $referenceConfiguration;
        return $this;
    }

    /**
     * Resolve all inheritances within a configuration.
     * After that the configuration array is cleaned from the
     * inheritance operator.
     *
     * @return array
     * @internal
     */
    public function getResolvedConfiguration(): array
    {
        $configuration = $this->resolve($this->referenceConfiguration);
        $configuration = $this->removeInheritanceOperatorRecursive($configuration);
        return $configuration;
    }

    /**
     * Resolve all inheritances within a configuration.
     *
157
158
159
160
161
162
163
164
     * Takes a YAML config mapped to associative array $configuration
     * - replace all findings of key '__inheritance' recursively
     * - perform a deep search in config by iteration, thus check for endless loop by reference cycle
     *
     * Return the completed configuration.
     *
     * @param array $configuration - a mapped YAML configuration (full or partial)
     * @param array $pathStack - an identifier for YAML key as array (Form.part1.key => {Form, part1, key})
165
     * @param bool $setInheritancePathToCheck
166
167
168
169
170
     * @return array
     */
    protected function resolve(
        array $configuration,
        array $pathStack = [],
171
        bool $setInheritancePathToCheck = true
172
173
    ): array {
        foreach ($configuration as $key => $values) {
174
            //add current key to pathStack
175
176
177
            $pathStack[] = $key;
            $path = implode('.', $pathStack);

178
            //check endless loop for current path
179
            $this->throwExceptionIfCycleInheritances($path, $path);
180
181

            //overwrite service property 'inheritancePathToCheck' with current path
182
183
            if ($setInheritancePathToCheck) {
                $this->inheritancePathToCheck = $path;
184
185
            }

186
            //if value of subnode is an array, perform a deep search iteration step
187
188
            if (is_array($configuration[$key])) {
                if (isset($configuration[$key][self::INHERITANCE_OPERATOR])) {
189
                    $inheritances = $this->getValueByPath($this->referenceConfiguration, $path . '.' . self::INHERITANCE_OPERATOR);
190

191
                    //and replace the __inheritance operator by the respective partial
192
193
                    if (is_array($inheritances)) {
                        $inheritedConfigurations = $this->resolveInheritancesRecursive($inheritances);
194
                        $configuration[$key] = array_replace_recursive($inheritedConfigurations, $configuration[$key]);
195
196
                    }

197
                    //remove the inheritance operator from configuration
198
199
200
201
                    unset($configuration[$key][self::INHERITANCE_OPERATOR]);
                }

                if (!empty($configuration[$key])) {
202
203
                    // resolve subnode of YAML config
                    $configuration[$key] = $this->resolve($configuration[$key], $pathStack);
204
205
206
207
208
209
210
211
212
213
214
                }
            }
            array_pop($pathStack);
        }

        return $configuration;
    }

    /**
     * Additional helper for the resolve method.
     *
215
216
     * Takes all inheritances (an array of YAML paths), and check them for endless loops
     *
217
218
219
220
221
222
223
224
225
226
     * @param array $inheritances
     * @return array
     * @throws CycleInheritancesException
     */
    protected function resolveInheritancesRecursive(array $inheritances): array
    {
        ksort($inheritances);
        $inheritedConfigurations = [];
        foreach ($inheritances as $inheritancePath) {
            $this->throwExceptionIfCycleInheritances($inheritancePath, $inheritancePath);
227
            $inheritedConfiguration = $this->getValueByPath($this->referenceConfiguration, $inheritancePath);
228
229
230
231
232

            if (
                isset($inheritedConfiguration[self::INHERITANCE_OPERATOR])
                && count($inheritedConfiguration) === 1
            ) {
233
                if ($this->inheritancePathToCheck === $inheritancePath) {
234
                    throw new CycleInheritancesException(
235
                        $this->inheritancePathToCheck . ' has cycle inheritances',
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
                        1474900796
                    );
                }

                $inheritedConfiguration = $this->resolveInheritancesRecursive(
                    $inheritedConfiguration[self::INHERITANCE_OPERATOR]
                );
            } else {
                $pathStack = explode('.', $inheritancePath);
                $key = array_pop($pathStack);
                $newConfiguration = [
                    $key => $inheritedConfiguration
                ];
                $inheritedConfiguration = $this->resolve(
                    $newConfiguration,
                    $pathStack,
                    false
                );
                $inheritedConfiguration = $inheritedConfiguration[$key];
            }

257
258
259
260
261
262
263
            if ($inheritedConfiguration === null) {
                throw new CycleInheritancesException(
                    $inheritancePath . ' does not exist within the configuration',
                    1489260796
                );
            }

264
            $inheritedConfigurations = array_replace_recursive(
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
                $inheritedConfigurations,
                $inheritedConfiguration
            );
        }

        return $inheritedConfigurations;
    }

    /**
     * Throw an exception if a cycle is detected.
     *
     * @param string $path
     * @param string $pathToCheck
     * @throws CycleInheritancesException
     */
    protected function throwExceptionIfCycleInheritances(string $path, string $pathToCheck)
    {
282
        $configuration = $this->getValueByPath($this->referenceConfiguration, $path);
283
284

        if (isset($configuration[self::INHERITANCE_OPERATOR])) {
285
            $inheritances = $this->getValueByPath($this->referenceConfiguration, $path . '.' . self::INHERITANCE_OPERATOR);
286

287
288
            if (is_array($inheritances)) {
                foreach ($inheritances as $inheritancePath) {
289
                    $configuration = $this->getValueByPath($this->referenceConfiguration, $inheritancePath);
290
291

                    if (isset($configuration[self::INHERITANCE_OPERATOR])) {
292
                        $_inheritances = $this->getValueByPath($this->referenceConfiguration, $inheritancePath . '.' . self::INHERITANCE_OPERATOR);
293

294
295
296
297
298
299
300
301
302
303
304
                        foreach ($_inheritances as $_inheritancePath) {
                            if (strpos($pathToCheck, $_inheritancePath) === 0) {
                                throw new CycleInheritancesException(
                                    $pathToCheck . ' has cycle inheritances',
                                    1474900797
                                );
                            }
                        }
                    }

                    if (
Ralf Zimmermann's avatar
Ralf Zimmermann committed
305
306
                        isset($this->inheritanceStack[$pathToCheck])
                        && is_array($this->inheritanceStack[$pathToCheck])
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
                        && in_array($inheritancePath, $this->inheritanceStack[$pathToCheck])
                    ) {
                        $this->inheritanceStack[$pathToCheck][] = $inheritancePath;
                        throw new CycleInheritancesException(
                            $pathToCheck . ' has cycle inheritances',
                            1474900799
                        );
                    }
                    $this->inheritanceStack[$pathToCheck][] = $inheritancePath;
                    $this->throwExceptionIfCycleInheritances($inheritancePath, $pathToCheck);
                }
                $this->inheritanceStack[$pathToCheck] = null;
            }
        }
    }

    /**
     * Recursively remove self::INHERITANCE_OPERATOR keys
     *
     * @param array $array
     * @return array the modified array
     */
    protected function removeInheritanceOperatorRecursive(array $array): array
    {
        $result = $array;
        foreach ($result as $key => $value) {
            if ($key === self::INHERITANCE_OPERATOR) {
                unset($result[$key]);
                continue;
            }

            if (is_array($value)) {
                $result[$key] = $this->removeInheritanceOperatorRecursive($value);
            }
        }
        return $result;
    }
344
345
346
347
348
349
350
351
352
353
354
355
356
357

    /**
     * Check the given array representation of a YAML config for the given path and return it's value / sub-array.
     * If path is not found, return null;
     *
     * @param array $config
     * @param string $path
     * @param string $delimiter
     * @return string|array|null
     */
    protected function getValueByPath(array $config, string $path, string $delimiter = '.')
    {
        try {
            return ArrayUtility::getValueByPath($config, $path, $delimiter);
358
        } catch (MissingArrayPathException $exception) {
359
360
361
            return null;
        }
    }
362
}