-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPadding.php
More file actions
83 lines (64 loc) · 2.03 KB
/
Copy pathPadding.php
File metadata and controls
83 lines (64 loc) · 2.03 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
<?php
declare(strict_types=1);
namespace Zero\Lib\Support\Concerns\Str;
trait Padding
{
public static function padLeft(string $value, int $length, string $pad = ' '): string
{
return self::pad($value, $length, $pad, 'left');
}
public static function padRight(string $value, int $length, string $pad = ' '): string
{
return self::pad($value, $length, $pad, 'right');
}
public static function padBoth(string $value, int $length, string $pad = ' '): string
{
return self::pad($value, $length, $pad, 'both');
}
public static function repeat(string $value, int $times): string
{
if ($times < 0) {
throw new \InvalidArgumentException('Times must be zero or greater.');
}
return str_repeat($value, $times);
}
private static function pad(string $value, int $length, string $pad, string $side): string
{
if ($length <= 0) {
return '';
}
$valueLength = mb_strlen($value);
if ($valueLength >= $length) {
return $value;
}
$padLength = $length - $valueLength;
$pad = $pad === '' ? ' ' : $pad;
$left = 0;
$right = 0;
switch ($side) {
case 'left':
$left = $padLength;
break;
case 'right':
$right = $padLength;
break;
default:
$left = intdiv($padLength, 2);
$right = $padLength - $left;
}
return self::repeatToLength($pad, $left) . $value . self::repeatToLength($pad, $right);
}
private static function repeatToLength(string $pad, int $length): string
{
if ($length <= 0) {
return '';
}
$padLength = mb_strlen($pad);
if ($padLength === 0) {
return str_repeat(' ', $length);
}
$repeats = (int) ceil($length / $padLength);
$result = str_repeat($pad, $repeats);
return mb_substr($result, 0, $length);
}
}