forked from muglug/psl
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpad_left.php
53 lines (46 loc) · 1.51 KB
/
pad_left.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
<?php
declare(strict_types=1);
namespace Psl\Str;
use Psl;
/**
* Returns the string padded to the total length by appending the `$pad_string`
* to the left.
*
* If the length of the input string plus the pad string exceeds the total
* length, the pad string will be truncated. If the total length is less than or
* equal to the length of the input string, no padding will occur.
*
* Example:
*
* Str\pad_left('Ay', 4)
* => Str(' Ay')
*
* Str\pad_left('ay', 3, 'A')
* => Str('Aay')
*
* Str\pad_left('eet', 4, 'Yeeeee')
* => Str('Yeet')
*
* Str\pad_left('مرحبا', 8, 'م')
* => Str('ممممرحبا')
*
* @param non-empty-string $pad_string
*
* @pure
*
* @throws Psl\Exception\InvariantViolationException If the $pad_string is empty, a negative $total_length is given,
* or an invalid $encoding is provided.
*/
function pad_left(string $string, int $total_length, string $pad_string = ' ', ?string $encoding = null): string
{
Psl\invariant('' !== $pad_string, 'Expected a non-empty pad string.');
Psl\invariant($total_length >= 0, 'Expected a non-negative total length.');
while (length($string, $encoding) < $total_length) {
$remaining = $total_length - length($string, $encoding);
if ($remaining <= length($pad_string, $encoding)) {
$pad_string = slice($pad_string, 0, $remaining, $encoding);
}
$string = $pad_string . $string;
}
return $string;
}