Skip to content

Commit

Permalink
Improve Str::set
Browse files Browse the repository at this point in the history
  • Loading branch information
stevebauman committed Feb 9, 2025
1 parent 39cc10a commit 42d6b62
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
9 changes: 7 additions & 2 deletions src/Support/Str.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,22 +49,27 @@ public static function literal(array|string $string): array|string
*/
public static function set(array|int $from, int|float|null $to = null): string
{
// If $from is an array with multiple elements, return them as a comma-separated list.
if (is_array($from) && count($from) > 1) {
return implode(',', $from);
}

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

// At this point, $from is an integer. No upper bound provided, return $from as a string.
if (is_null($to)) {
return $from;
return (string) $from;
}

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

// Otherwise, return a typical range string.
return $from.':'.$to;
}

Expand Down
10 changes: 9 additions & 1 deletion tests/Support/StrTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,18 @@
expect(Str::set(5, 10))->toBe('5:10');
expect(Str::set(5, INF))->toBe('5:*');
expect(Str::set([5, 10]))->toBe('5,10');
expect(Str::set([5]))->toBe('5:5');
expect(Str::set([5]))->toBe('5');
expect(Str::set(5))->toBe('5');
});

test('set ignores $to when $from is a single-element array', function () {
expect(Str::set([5], 10))->toBe('5');
});

test('set ignores $to when $from is a multi-element array', function () {
expect(Str::set([5, 6], 10))->toBe('5,6');
});

test('escape removes newlines/control characters and escapes backslashes and double quotes', function () {
// Newlines and control characters removed
expect(Str::escape("Hello\nWorld"))->toBe('HelloWorld');
Expand Down

0 comments on commit 42d6b62

Please sign in to comment.