1: <?php
2:
3: declare(strict_types=1);
4:
5: namespace Atk4\Ui\Js;
6:
7: use Atk4\Core\WarnDynamicPropertyTrait;
8:
9: /**
10: * @phpstan-consistent-constructor
11: */
12: class JsBlock implements JsExpressionable
13: {
14: use WarnDynamicPropertyTrait;
15:
16: /** @var list<JsExpressionable> */
17: private array $statements;
18:
19: /**
20: * @param list<JsExpressionable|null> $statements
21: */
22: public function __construct(array $statements = [])
23: {
24: $this->statements = [];
25: foreach ($statements as $value) {
26: if ($value === null) { // TODO this should be not needed
27: continue;
28: }
29:
30: $this->addStatement($value);
31: }
32: }
33:
34: /**
35: * @return list<JsExpressionable>
36: */
37: public function getStatements(): array
38: {
39: return $this->statements;
40: }
41:
42: public function addStatement(JsExpressionable $statement): void
43: {
44: $this->statements[] = $statement;
45: }
46:
47: /**
48: * @param list<JsExpressionable|null>|JsExpressionable $statements
49: *
50: * @return static
51: */
52: public static function fromHookResult($statements)
53: {
54: return new static(is_array($statements) ? $statements : [$statements]);
55: }
56:
57: #[\Override]
58: public function jsRender(): string
59: {
60: $output = '';
61: foreach ($this->statements as $statement) {
62: $js = $statement->jsRender();
63: if ($js === '') {
64: continue;
65: } elseif (!$statement instanceof self && !preg_match('~;\s*$~', $js)) {
66: $js .= ';';
67: }
68:
69: $output .= ($output !== '' ? "\n" : '') . $js;
70: }
71:
72: return $output;
73: }
74: }
75: