-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathArrayStringifier.php
85 lines (68 loc) · 2.21 KB
/
ArrayStringifier.php
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
<?php
/*
* This file is part of Respect/Stringifier.
* Copyright (c) Henrique Moody <henriquemoody@gmail.com>
* SPDX-License-Identifier: MIT
*/
declare(strict_types=1);
namespace Respect\Stringifier\Stringifiers;
use Respect\Stringifier\Quoter;
use Respect\Stringifier\Stringifier;
use function array_keys;
use function count;
use function implode;
use function is_array;
use function range;
use function sprintf;
final class ArrayStringifier implements Stringifier
{
private const LIMIT_EXCEEDED_PLACEHOLDER = '...';
public function __construct(
private readonly Stringifier $stringifier,
private readonly Quoter $quoter,
private readonly int $maximumDepth,
private readonly int $maximumNumberOfItems
) {
}
public function stringify(mixed $raw, int $depth): ?string
{
if (!is_array($raw)) {
return null;
}
if (empty($raw)) {
return $this->quoter->quote('[]', $depth);
}
if ($depth >= $this->maximumDepth) {
return $this->quoter->quote(self::LIMIT_EXCEEDED_PLACEHOLDER, $depth);
}
$items = [];
$isSequential = $this->isSequential($raw);
foreach ($raw as $key => $value) {
if (count($items) >= $this->maximumNumberOfItems) {
$items[] = self::LIMIT_EXCEEDED_PLACEHOLDER;
break;
}
$stringifiedValue = $this->stringifyKeyValue($value, $depth + 1);
if ($isSequential === true) {
$items[] = $stringifiedValue;
continue;
}
$items[] = sprintf('%s: %s', $this->stringifier->stringify($key, $depth + 1), $stringifiedValue);
}
return $this->quoter->quote(sprintf('[%s]', implode(', ', $items)), $depth);
}
private function stringifyKeyValue(mixed $value, int $depth): ?string
{
if (is_array($value)) {
return $this->stringify($value, $depth);
}
return $this->stringifier->stringify($value, $depth);
}
/**
* @param mixed[] $array
*/
private function isSequential(array $array): bool
{
return array_keys($array) === range(0, count($array) - 1);
}
}