-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathListModifier.php
More file actions
59 lines (45 loc) · 1.61 KB
/
Copy pathListModifier.php
File metadata and controls
59 lines (45 loc) · 1.61 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
<?php
/*
* SPDX-FileCopyrightText: (c) Respect Project Contributors
* SPDX-License-Identifier: ISC
* SPDX-FileContributor: Henrique Moody <henriquemoody@gmail.com>
*/
declare(strict_types=1);
namespace Respect\StringFormatter\Modifiers;
use Respect\StringFormatter\BypassTranslator;
use Respect\StringFormatter\Modifier;
use Symfony\Contracts\Translation\TranslatorInterface;
use function array_map;
use function array_pop;
use function count;
use function implode;
use function in_array;
use function is_array;
final readonly class ListModifier implements Modifier
{
private const array ALLOWED_PIPES = ['list', 'list:and', 'list:or'];
public function __construct(
private Modifier $nextModifier,
private TranslatorInterface $translator = new BypassTranslator(),
) {
}
public function modify(mixed $value, string|null $pipe): string
{
if (!$pipe || !in_array($pipe, self::ALLOWED_PIPES) || !is_array($value)) {
return $this->nextModifier->modify($value, $pipe);
}
if ($value === []) {
return $this->nextModifier->modify($value, $pipe);
}
$modifiedValues = array_map(fn($item) => $this->nextModifier->modify($item, null), $value);
$conjunction = $this->translator->trans(match ($pipe) {
'list:and', 'list' => 'and',
'list:or' => 'or',
});
if (count($value) < 3) {
return implode(' ' . $conjunction . ' ', $modifiedValues);
}
$last = array_pop($modifiedValues);
return implode(', ', $modifiedValues) . ', ' . $conjunction . ' ' . $last;
}
}