‪TYPO3CMS  ‪main
JavaScriptItems.php
Go to the documentation of this file.
1 <?php
2 
3 declare(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 
18 namespace ‪TYPO3\CMS\Core\Page;
19 
20 class JavaScriptItems implements \JsonSerializable
21 {
25  protected array $globalAssignments = [];
26 
30  protected array $javaScriptModuleInstructions = [];
31 
32  public function jsonSerialize(): array
33  {
34  return $this->toArray();
35  }
36 
37  public function addGlobalAssignment(array $payload): void
38  {
39  if (empty($payload)) {
40  return;
41  }
42  $this->globalAssignments[] = $payload;
43  }
44 
45  public function addJavaScriptModuleInstruction(JavaScriptModuleInstruction $instruction): void
46  {
47  $this->javaScriptModuleInstructions[] = $instruction;
48  }
49 
54  public function toArray(): array
55  {
56  if ($this->isEmpty()) {
57  return [];
58  }
59  $items = [];
60  foreach ($this->globalAssignments as $item) {
61  $items[] = [
62  'type' => 'globalAssignment',
63  'payload' => $item,
64  ];
65  }
66  foreach ($this->javaScriptModuleInstructions as $item) {
67  $items[] = [
68  'type' => 'javaScriptModuleInstruction',
69  'payload' => $item,
70  ];
71  }
72  return $items;
73  }
74 
75  public function isEmpty(): bool
76  {
77  return $this->globalAssignments === []
78  && empty($this->javaScriptModuleInstructions);
79  }
80 
84  public function updateState(array $state): void
85  {
86  $this->globalAssignments = $state['globalAssignments'] ?? [];
87  $this->javaScriptModuleInstructions = [];
88  foreach ($state['javaScriptModuleInstructions'] ?? [] as $instruction) {
89  $this->javaScriptModuleInstructions[] = ‪JavaScriptModuleInstruction::fromState($instruction);
90  }
91  }
92 
96  public function getState(): array
97  {
98  return [
99  'globalAssignments' => $this->globalAssignments,
100  'javaScriptModuleInstructions' => array_map(
101  static fn(JavaScriptModuleInstruction $instruction): array => $instruction->getState(),
102  $this->javaScriptModuleInstructions
103  ),
104  ];
105  }
106 }
‪TYPO3\CMS\Core\Page
Definition: AssetCollector.php:18
‪TYPO3\CMS\Core\Page\JavaScriptModuleInstruction\fromState
‪static self fromState(array $state)
Definition: JavaScriptModuleInstruction.php:58