[TASK] Introduce abstract class AbstractAjaxController
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Controller / AbstractFormEngineAjaxController.php
1 <?php
2 declare(strict_types=1);
3 namespace TYPO3\CMS\Backend\Controller;
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
18 /**
19 * Abstract class for a couple of FormEngine controllers triggered by
20 * ajax calls. The class containers some helpers to for instance prepare
21 * the form render result for json output.
22 *
23 * @internal Marked as internal for now, methods in this class may change any time.
24 */
25 abstract class AbstractFormEngineAjaxController
26 {
27 /**
28 * Gets result array from FormEngine and returns string with js modules
29 * that need to be loaded and evaluated by JavaScript.
30 *
31 * @param array $result
32 * @return array
33 */
34 public function createExecutableStringRepresentationOfRegisteredRequireJsModules(array $result): array
35 {
36 if (empty($result['requireJsModules'])) {
37 return [];
38 }
39 $requireJs = [];
40 foreach ($result['requireJsModules'] as $module) {
41 $moduleName = null;
42 $callback = null;
43 if (is_string($module)) {
44 // if $module is a string, no callback
45 $moduleName = $module;
46 $callback = null;
47 } elseif (is_array($module)) {
48 // if $module is an array, callback is possible
49 foreach ($module as $key => $value) {
50 $moduleName = $key;
51 $callback = $value;
52 break;
53 }
54 }
55 if ($moduleName !== null) {
56 $inlineCodeKey = $moduleName;
57 $javaScriptCode = 'require(["' . $moduleName . '"]';
58 if ($callback !== null) {
59 $inlineCodeKey .= sha1($callback);
60 $javaScriptCode .= ', ' . $callback;
61 }
62 $javaScriptCode .= ');';
63 $requireJs[] = '/*RequireJS-Module-' . $inlineCodeKey . '*/' . LF . $javaScriptCode;
64 }
65 }
66 return $requireJs;
67 }
68 }