Skip to content

Commit 42d6b62

Browse files
committed
Improve Str::set
1 parent 39cc10a commit 42d6b62

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

src/Support/Str.php

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,22 +49,27 @@ public static function literal(array|string $string): array|string
4949
*/
5050
public static function set(array|int $from, int|float|null $to = null): string
5151
{
52+
// If $from is an array with multiple elements, return them as a comma-separated list.
5253
if (is_array($from) && count($from) > 1) {
5354
return implode(',', $from);
5455
}
5556

57+
// If $from is an array with a single element, return that element.
5658
if (is_array($from) && count($from) === 1) {
57-
return $from[0].':'.$from[0];
59+
return (string) reset($from);
5860
}
5961

62+
// At this point, $from is an integer. No upper bound provided, return $from as a string.
6063
if (is_null($to)) {
61-
return $from;
64+
return (string) $from;
6265
}
6366

67+
// If the upper bound is infinite, use the '*' notation.
6468
if ($to == INF) {
6569
return $from.':*';
6670
}
6771

72+
// Otherwise, return a typical range string.
6873
return $from.':'.$to;
6974
}
7075

tests/Support/StrTest.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,18 @@
66
expect(Str::set(5, 10))->toBe('5:10');
77
expect(Str::set(5, INF))->toBe('5:*');
88
expect(Str::set([5, 10]))->toBe('5,10');
9-
expect(Str::set([5]))->toBe('5:5');
9+
expect(Str::set([5]))->toBe('5');
1010
expect(Str::set(5))->toBe('5');
1111
});
1212

13+
test('set ignores $to when $from is a single-element array', function () {
14+
expect(Str::set([5], 10))->toBe('5');
15+
});
16+
17+
test('set ignores $to when $from is a multi-element array', function () {
18+
expect(Str::set([5, 6], 10))->toBe('5,6');
19+
});
20+
1321
test('escape removes newlines/control characters and escapes backslashes and double quotes', function () {
1422
// Newlines and control characters removed
1523
expect(Str::escape("Hello\nWorld"))->toBe('HelloWorld');

0 commit comments

Comments
 (0)