-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPadRule.php
More file actions
49 lines (41 loc) · 1.29 KB
/
PadRule.php
File metadata and controls
49 lines (41 loc) · 1.29 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
<?php
declare(strict_types=1);
namespace KaririCode\Sanitizer\Rule\String;
use KaririCode\Sanitizer\Contract\SanitizationContext;
use KaririCode\Sanitizer\Contract\SanitizationRule;
/**
* Pads a string to a given length.
*
* Parameters: length (int), pad (string, default ' '), side ('left'|'right'|'both', default 'right').
*
* @author Walmir Silva <walmir.silva@kariricode.org>
*
* @since 3.1.0 ARFA 1.3
*/
final readonly class PadRule implements SanitizationRule
{
#[\Override]
public function sanitize(mixed $value, SanitizationContext $context): mixed
{
if (! \is_string($value)) {
return $value;
}
$lengthRaw = $context->getParameter('length', 0);
$length = \is_int($lengthRaw) ? $lengthRaw : 0;
$padRaw = $context->getParameter('pad', ' ');
$pad = \is_string($padRaw) ? $padRaw : ' ';
$sideRaw = $context->getParameter('side', 'right');
$side = \is_string($sideRaw) ? $sideRaw : 'right';
$padType = match ($side) {
'left' => STR_PAD_LEFT,
'both' => STR_PAD_BOTH,
default => STR_PAD_RIGHT,
};
return str_pad($value, $length, $pad, $padType);
}
#[\Override]
public function getName(): string
{
return 'string.pad';
}
}