-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathBlock.php
More file actions
361 lines (304 loc) · 10.6 KB
/
Block.php
File metadata and controls
361 lines (304 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
<?php
declare(strict_types=1);
namespace HiFolks\DataType;
use ArrayAccess;
use Countable;
use HiFolks\DataType\Traits\EditableBlock;
use HiFolks\DataType\Traits\QueryableBlock;
use HiFolks\DataType\Traits\ExportableBlock;
use HiFolks\DataType\Traits\FormattableBlock;
use HiFolks\DataType\Traits\IteratableBlock;
use HiFolks\DataType\Traits\LoadableBlock;
use HiFolks\DataType\Traits\TypeableBlock;
use HiFolks\DataType\Traits\ValidableBlock;
use Iterator;
/**
* Class Block
* @package HiFolks\DataType
*
* @implements Iterator<int|string, mixed>
* @implements ArrayAccess<int|string, mixed>
*/
final class Block implements Iterator, ArrayAccess, Countable
{
use QueryableBlock;
use EditableBlock;
use ExportableBlock;
use LoadableBlock;
use IteratableBlock;
use ValidableBlock;
use FormattableBlock;
use TypeableBlock;
/** @var array<int|string, mixed> */
private array $data;
/**
* Missing key handling mode: return default value silently.
*/
private const MISSING_KEY_SILENT = 0;
/**
* Missing key handling mode: emit a warning and continue execution.
*/
private const MISSING_KEY_WARNING = 1;
/**
* Missing key handling mode: throw an exception.
*/
private const MISSING_KEY_EXCEPTION = 2;
/**
* Current missing key handling mode.
*
* One of:
* - self::MISSING_KEY_SILENT
* - self::MISSING_KEY_WARNING
* - self::MISSING_KEY_EXCEPTION
*/
private int $missingKeyMode = self::MISSING_KEY_SILENT;
/** @var class-string<\Throwable>|null Exception class to throw on missing key */
private ?string $missingKeyExceptionClass = null;
/** @var string|null Optional hint appended to the exception message */
private ?string $missingKeyExceptionHint = null;
/** @param array<int|string, mixed> $data */
public function __construct(array $data = [], private bool $iteratorReturnsBlock = true)
{
$this->data = $data;
}
/**
* Use silent mode when accessing missing keys (return default value).
*/
public function silentOnMissingKey(): self
{
$this->missingKeyMode = self::MISSING_KEY_SILENT;
$this->missingKeyExceptionClass = null;
$this->missingKeyExceptionHint = null;
return $this;
}
/**
* Emit a warning when accessing a missing key.
*/
public function warnOnMissingKey(): self
{
$this->missingKeyMode = self::MISSING_KEY_WARNING;
return $this;
}
/**
* Configure the Block object to throw an exception when accessing a missing key.
*
* When enabled, any access to a non-existing key will throw an exception of the
* given class instead of returning the default value.
*
* An optional hint can be provided to add extra context to the exception message.
*
* @param class-string<\Throwable> $exceptionClass Exception class to throw (must extend Throwable)
* @param string|null $hint Optional additional context appended to the exception message
*
* @return self Returns the current instance for method chaining.
*
* @throws \InvalidArgumentException If the given class does not extend Throwable
*/
public function throwOnMissingKey(
string $exceptionClass = \OutOfBoundsException::class,
?string $hint = null,
): self {
/** @phpstan-ignore function.alreadyNarrowedType, booleanAnd.alwaysFalse */
if (!is_subclass_of($exceptionClass, \Throwable::class) && $exceptionClass !== \Throwable::class) {
throw new \InvalidArgumentException("Exception class must extend Throwable");
}
$this->missingKeyMode = self::MISSING_KEY_EXCEPTION;
$this->missingKeyExceptionClass = $exceptionClass;
$this->missingKeyExceptionHint = $hint;
return $this;
}
private function handleMissingKey(int|string $key, mixed $defaultValue): mixed
{
switch ($this->missingKeyMode) {
case self::MISSING_KEY_WARNING:
trigger_error("Undefined array key: " . $key, E_USER_WARNING);
return $defaultValue;
case self::MISSING_KEY_EXCEPTION:
$class = $this->missingKeyExceptionClass ?? \OutOfBoundsException::class;
$message = "Undefined array key: " . $key;
if ($this->missingKeyExceptionHint) {
$message = $message . " (" . $this->missingKeyExceptionHint . ")";
}
throw new $class($message);
case self::MISSING_KEY_SILENT:
default:
return $defaultValue;
}
}
public function iterateBlock(bool $returnsBlock = true): self
{
$this->iteratorReturnsBlock = $returnsBlock;
return $this;
}
/** @param array<int|string, mixed> $data */
public static function make(array $data = [], bool $iteratorReturnsBlock = true): self
{
return new self($data, $iteratorReturnsBlock);
}
public function count(): int
{
return count($this->data);
}
/** @param array<int|string, mixed> $encodedJson */
public static function fromEncodedJson(mixed $encodedJson): self
{
return new self($encodedJson);
}
/**
* Get the element with $key
*
* @param non-empty-string $charNestedKey
*/
public function get(int|string $key, mixed $defaultValue = null, string $charNestedKey = "."): mixed
{
if (is_string($key)) {
$keyString = strval($key);
if (str_contains($keyString, $charNestedKey)) {
$nestedValue = $this->data;
foreach (explode($charNestedKey, $keyString) as $nestedKey) {
if (is_array($nestedValue) && array_key_exists($nestedKey, $nestedValue)) {
$nestedValue = $nestedValue[$nestedKey];
} elseif ($nestedValue instanceof Block) {
$nestedValue = $nestedValue->get($nestedKey);
} else {
return $this->handleMissingKey($key, $defaultValue);
}
}
return $nestedValue;
}
}
if (!array_key_exists($key, $this->data)) {
return $this->handleMissingKey($key, $defaultValue);
}
return $this->data[$key];
}
/**
* Get the element with $key as Block object
* This is helpful when the element is an array, and you
* need to get the Block object instead of the classic array
* In the case the $key doesn't exist, an empty Block can be returned
* @param non-empty-string $charNestedKey
*/
public function getBlock(mixed $key, mixed $defaultValue = null, string $charNestedKey = "."): self
{
$value = $this->getBlockNullable($key, $defaultValue, $charNestedKey);
if (is_null($value)) {
return Block::make([]);
}
return $value;
}
/**
* Get the element with $key as Block object
* This is helpful when the element is an array, and you
* need to get the Block object instead of the classic array
* In the case the $key doesn't exist, null can be returned
* @param non-empty-string $charNestedKey
*/
public function getBlockNullable(mixed $key, mixed $defaultValue = null, string $charNestedKey = "."): ?self
{
$value = $this->get($key, $defaultValue, $charNestedKey);
if (is_null($value)) {
return null;
}
if (is_scalar($value)) {
return self::make([$value]);
}
if (is_array($value)) {
return self::make($value);
}
if ($value instanceof Block) {
return $value;
}
return Block::make([]);
}
/**
* Set a value to a specific $key
* You can use the dot notation for setting a nested value.
* @param non-empty-string $charNestedKey
*/
public function set(int|string $key, mixed $value, string $charNestedKey = "."): self
{
if (is_string($key)) {
$array = &$this->data;
$keys = explode($charNestedKey, $key);
foreach ($keys as $i => $key) {
if (count($keys) === 1) {
break;
}
unset($keys[$i]);
if (!isset($array[$key]) || !is_array($array[$key])) {
$array[$key] = [];
}
$array = &$array[$key];
}
$key = array_shift($keys);
if (!is_null($key)) {
$array[$key] = $value;
}
return $this;
}
$this->data[$key] = $value;
return $this;
}
/**
* @return Block object that contains the key/value pairs for each index in the array
*/
public function entries(): self
{
$pairs = [];
foreach ($this->data as $k => $v) {
$pairs[] = [$k, $v];
}
return self::make($pairs);
}
/**
* @return Block object that contains the key/value pairs for each index in the array
*/
public function values(): self
{
$pairs = $this->data;
return self::make($pairs);
}
/**
* Returns a new array [] or a new Blcok object that contains the keys
* for each index in the Block object
* It returns Block or [] depending on $returnArrClass value
*
* @param bool $returnBlockClass true if you need Block object
* @return array<int|string, mixed>|Block
*/
public function keys(bool $returnBlockClass = false): array|Block
{
if ($returnBlockClass) {
return self::make(array_keys($this->data));
}
return array_keys($this->data);
}
public function has(mixed $value): bool
{
return in_array($value, $this->values()->toArray());
}
public function hasKey(string|int $key): bool
{
/** @var array<int, int|string> $keys */
$keys = $this->keys();
return in_array($key, $keys);
}
/**
* Applies a callable function to a field and sets the result to a target field.
*
* @param string|int $key The key of the field to be processed.
* @param string|int $targetKey The key where the result should be stored.
* @param callable $callable The function to apply to the field value.
*
* @return self Returns the instance of the class for method chaining.
*/
public function applyField(
string|int $key,
string|int $targetKey,
callable $callable,
): self {
$this->set($targetKey, $callable($this->get($key)));
return $this;
}
}