16e5df2dfb15e6f7673c632c75936b57fbe1c0f8
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / DataHandling / SlugEnricher.php
1 <?php
2 declare(strict_types = 1);
3
4 namespace TYPO3\CMS\Core\DataHandling;
5
6 /*
7 * This file is part of the TYPO3 CMS project.
8 *
9 * It is free software; you can redistribute it and/or modify it under
10 * the terms of the GNU General Public License, either version 2
11 * of the License, or any later version.
12 *
13 * For the full copyright and license information, please read the
14 * LICENSE.txt file that was distributed with this source code.
15 *
16 * The TYPO3 project - inspiring people to share!
17 */
18
19 use TYPO3\CMS\Core\Utility\MathUtility;
20
21 /**
22 * New records that are capable of handling slugs (TCA type 'slug'), always
23 * require the field value to be set in order to run through the validation
24 * process to create a new slug. Fields having `null` as value are ignored
25 * and can be used to by-pass implicit slug initialization.
26 *
27 * @see DataHandler::fillInFieldArray(), DataHandler::checkValueForSlug()
28 */
29 class SlugEnricher
30 {
31 /**
32 * @var array
33 */
34 protected $slugFieldNamesPerTable = [];
35
36 /**
37 * @param array $dataMap
38 * @return array
39 */
40 public function enrichDataMap(array $dataMap): array
41 {
42 foreach ($dataMap as $tableName => &$tableDataMap) {
43 $slugFieldNames = $this->resolveSlugFieldNames($tableName);
44 if (empty($slugFieldNames)) {
45 continue;
46 }
47 foreach ($tableDataMap as $identifier => &$fieldValues) {
48 if (MathUtility::canBeInterpretedAsInteger($identifier)) {
49 continue;
50 }
51 $fieldValues = $this->enrichUndefinedSlugFieldNames(
52 $slugFieldNames,
53 $fieldValues
54 );
55 }
56 }
57 return $dataMap;
58 }
59
60 /**
61 * @param array $slugFieldNames
62 * @param array $fieldValues
63 * @return array
64 */
65 protected function enrichUndefinedSlugFieldNames(array $slugFieldNames, array $fieldValues): array
66 {
67 if (empty($slugFieldNames)) {
68 return [];
69 }
70 $undefinedSlugFieldNames = array_diff(
71 $slugFieldNames,
72 array_keys($fieldValues)
73 );
74 if (empty($undefinedSlugFieldNames)) {
75 return $fieldValues;
76 }
77 return array_merge(
78 $fieldValues,
79 array_fill_keys(
80 $undefinedSlugFieldNames,
81 ''
82 )
83 );
84 }
85
86 /**
87 * @param string $tableName
88 * @return string[]
89 */
90 protected function resolveSlugFieldNames(string $tableName): array
91 {
92 if (isset($this->slugFieldNamesPerTable[$tableName])) {
93 return $this->slugFieldNamesPerTable[$tableName];
94 }
95
96 return $this->slugFieldNamesPerTable[$tableName] = array_keys(
97 array_filter(
98 $GLOBALS['TCA'][$tableName]['columns'] ?? [],
99 function (array $settings) {
100 return ($settings['config']['type'] ?? null) === 'slug';
101 }
102 )
103 );
104 }
105 }