3 declare(strict_types
=1);
7 use function array_key_exists
;
10 use function str_contains
;
13 * Collects information about which JavaScript
14 * files and objects are necessary to render
15 * the page and generates the relevant code.
20 * An array of SCRIPT tags
22 * @var array<string, array<string, int|string|array<string, string>>>
23 * @psalm-var array<string, array{has_onload: 0|1, filename: non-empty-string, params: array<string, string>}>
25 private array $files = [];
27 * A string of discrete javascript code snippets
29 private string $code = '';
32 * Generates new Scripts objects
34 public function __construct(private readonly Template
$template)
39 * Adds a new file to the list of scripts
41 * @param string $filename The name of the file to include
42 * @param array<string, string> $params Additional parameters to pass to the file
44 public function addFile(
48 $hash = md5($filename);
49 if (array_key_exists($hash, $this->files
) ||
$filename === '') {
53 $hasOnload = $this->hasOnloadEvent($filename);
54 $this->files
[$hash] = ['has_onload' => (int) $hasOnload, 'filename' => $filename, 'params' => $params];
58 * Add new files to the list of scripts
60 * @param string[] $filelist The array of file names
62 public function addFiles(array $filelist): void
64 foreach ($filelist as $filename) {
65 $this->addFile($filename);
70 * Determines whether to fire up an onload event for a file
72 * @param string $filename The name of the file to be checked against the exclude list.
74 * @return bool true to fire up the event, false not to
76 private function hasOnloadEvent(string $filename): bool
78 return ! str_contains($filename, 'vendor')
79 && ! str_contains($filename, 'runtime.js')
80 && ! str_contains($filename, 'name-conflict-fixes.js')
81 && ! str_contains($filename, 'index.php')
82 && ! str_contains($filename, 'shared.js')
83 && ! str_contains($filename, 'datetimepicker.js')
84 && ! str_contains($filename, 'validator-messages.js');
88 * Adds a new code snippet to the code to be executed
90 * @param string $code The JS code to be added
92 public function addCode(string $code): void
94 $this->code
.= $code . "\n";
98 * Returns a list with filenames and a flag to indicate
99 * whether to register onload events for this file
101 * @return array<int, array<string, int|string>>
102 * @psalm-return list<array{name: non-empty-string, fire: 0|1}>
104 public function getFiles(): array
107 foreach ($this->files
as $file) {
108 //If filename contains a "?", continue.
109 if (str_contains($file['filename'], '?')) {
113 $retval[] = ['name' => $file['filename'], 'fire' => $file['has_onload']];
120 * Renders all the JavaScript file inclusions, code and events
122 public function getDisplay(): string
124 $baseDir = defined('PMA_PATH_TO_BASEDIR') ? PMA_PATH_TO_BASEDIR
: '';
126 return $this->template
->render('scripts', [
127 'base_dir' => $baseDir,
128 'files' => $this->files
,
129 'version' => Version
::VERSION
,
130 'code' => $this->code
,