1: <?php
2: /*
3: * SimpleID
4: *
5: * Copyright (C) Kelvin Mo 2021-2025
6: *
7: * This program is free software; you can redistribute it and/or
8: * modify it under the terms of the GNU General Public
9: * License as published by the Free Software Foundation; either
10: * version 2 of the License, or (at your option) any later version.
11: *
12: * This program is distributed in the hope that it will be useful,
13: * but WITHOUT ANY WARRANTY; without even the implied warranty of
14: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15: * General Public License for more details.
16: *
17: * You should have received a copy of the GNU General Public
18: * License along with this program; if not, write to the Free
19: * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20: *
21: */
22:
23: namespace SimpleID\Util\UI;
24:
25: /**
26: * A builder to build user interfaces.
27: *
28: * User interfaces built by adding "blocks" using the {@link addBlock()}
29: * method. A block is essentially a piece of HTML code that can be
30: * inserted in a particular order.
31: *
32: * In addition to blocks, attachments can also be added. Attachments
33: * can be things such as CSS style sheets, Javascript references or
34: * Javascript code. Each attachment is associated with a type.
35: *
36: */
37: class UIBuilder implements UIBuilderInterface {
38: use AttachmentManagerTrait;
39:
40: /** @var array<array<mixed>> */
41: protected $blocks = [];
42:
43: /**
44: * {@inheritdoc}
45: */
46: public function addBlock(string $id, string $content, int $weight = 0, array $additional = []): UIBuilder {
47: $block = [ 'id' => $id, 'content' => $content, 'weight' => $weight ];
48: $block = array_merge($block, $additional);
49:
50: $this->blocks[] = [
51: '#data' => $block,
52: '#weight' => $weight
53: ];
54:
55: return $this;
56: }
57:
58: /**
59: * {@inheritdoc}
60: */
61: public function merge(UIBuilderInterface $builder) {
62: $this->blocks = array_merge($this->blocks, $builder->getBlockData());
63: $this->mergeAttachments($builder);
64: return $this;
65: }
66:
67: /**
68: * {@inheritdoc}
69: */
70: public function getBlocks(): array {
71: uasort($this->blocks, function($a, $b) { if ($a['#weight'] == $b['#weight']) { return 0; } return ($a['#weight'] < $b['#weight']) ? -1 : 1; });
72: return array_map(function($a) { return $a['#data']; }, $this->blocks);
73: }
74:
75: /**
76: * {@inheritdoc}
77: */
78: public function getBlockData(): array {
79: return $this->blocks;
80: }
81:
82: /**
83: * {@inheritdoc}
84: */
85: public function reset() {
86: $this->blocks = [];
87: $this->resetAttachments();
88: }
89: }
90:
91: ?>