1: <?php
2:
3: namespace LaravelUi5\Core\Contracts;
4:
5: use LaravelUi5\Core\Exceptions\UndefinedBagKeyException;
6:
7: /**
8: * Immutable key-value bag with typed accessors.
9: *
10: * This base class is used for both Ui5Args (runtime parameters)
11: * and Ui5Config (resolved settings). It assumes that all values
12: * have already been validated and cast by the respective Resolver.
13: *
14: * Responsibilities:
15: * - Provide read-only access to the underlying data array.
16: * - Offer typed getter methods with default values.
17: * - Keep logic minimal: no additional casting or validation.
18: *
19: * Example:
20: * ```php
21: * $args = new Ui5Args(['year' => 2025, 'active' => true]);
22: * $year = $args->int('year'); // 2025
23: * $active = $args->bool('active'); // true
24: * $missing = $args->string('foo', 'x'); // "x"
25: * ```
26: */
27: abstract readonly class Ui5Bag
28: {
29: /** @param array<string,mixed> $data */
30: public function __construct(protected array $data) {}
31:
32: /**
33: * Return the raw underlying array.
34: */
35: public function all(): array
36: {
37: return $this->data;
38: }
39:
40: /**
41: * Return a raw value by key, with optional default.
42: */
43: public function get(string $key): mixed
44: {
45: if (array_key_exists($key, $this->data)) {
46: return $this->data[$key];
47:
48: }
49: throw new UndefinedBagKeyException($key);
50: }
51:
52: /**
53: * Return a string value or default.
54: */
55: public function string(string $key): ?string
56: {
57: if (array_key_exists($key, $this->data)) {
58: return $this->data[$key];
59:
60: }
61: throw new UndefinedBagKeyException($key);
62: }
63:
64: /**
65: * Return an integer value or default.
66: */
67: public function int(string $key): ?int
68: {
69: if (array_key_exists($key, $this->data)) {
70: return $this->data[$key];
71:
72: }
73: throw new UndefinedBagKeyException($key);
74: }
75:
76: /**
77: * Return a float value or default.
78: */
79: public function float(string $key): ?float
80: {
81: if (array_key_exists($key, $this->data)) {
82: return $this->data[$key];
83:
84: }
85: throw new UndefinedBagKeyException($key);
86: }
87:
88: /**
89: * Return a boolean value or default.
90: */
91: public function bool(string $key): ?bool
92: {
93: if (array_key_exists($key, $this->data)) {
94: return $this->data[$key];
95:
96: }
97: throw new UndefinedBagKeyException($key);
98: }
99:
100: /**
101: * Return an array value or default.
102: */
103: public function array(string $key): ?array
104: {
105: if (array_key_exists($key, $this->data)) {
106: return $this->data[$key];
107:
108: }
109: throw new UndefinedBagKeyException($key);
110: }
111: }
112: