diff --git a/CHANGELOG.md b/CHANGELOG.md index c22f6b5..6cc7866 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ CHANGELOG for 1.x ## v1.7.1 - (2024-06-20) ### Added - `ArrayUtils::hasDuplicateValue` + tests +- `StringUtils::fillPrefix` Fill a prefix to value until specified length + tests ## v1.7.0 - (2024-06-14) ### Added diff --git a/src/Utils/StringUtils.php b/src/Utils/StringUtils.php index 678e34e..9697f94 100644 --- a/src/Utils/StringUtils.php +++ b/src/Utils/StringUtils.php @@ -186,4 +186,22 @@ public static function formatSpaceBetween(?string $first, ?string $last): string return $first . $space . $last; } + + /** + * Fill a prefix to value until specified length + * + *
+ * + *+ * The above example will output: + *
+ * '0001' + *+ */ + public static function fillPrefix(int|string $value, int $length, string $prefixValue): string + { + return sprintf("%$prefixValue{$length}s", $value); + } } diff --git a/tests/Utils/StringUtilsTest.php b/tests/Utils/StringUtilsTest.php index be73fe3..674d68a 100644 --- a/tests/Utils/StringUtilsTest.php +++ b/tests/Utils/StringUtilsTest.php @@ -316,4 +316,36 @@ public function formatSpaceBetweenProvider(): array ] ]; } + + /** + * @dataProvider fillPrefixProvider + */ + public function testFillPrefix(string $expected, int|string $value, int $length, string $prefixValue): void + { + $this->assertSame($expected, StringUtils::fillPrefix($value, $length, $prefixValue)); + } + + public function fillPrefixProvider(): array + { + return [ + 'simple' => [ + '0001', + 1, + 4, + '0' + ], + 'full' => [ + '99999', + '99999', + 5, + '0' + ], + 'big_prefix' => [ + '0011', + 11, + 4, + '000000000000000' + ], + ]; + } }