Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[10.x] Add str()->take($limit) and Str::take($string, $limit) #48467

Merged
merged 5 commits into from
Sep 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/Illuminate/Support/Str.php
Original file line number Diff line number Diff line change
Expand Up @@ -1386,6 +1386,22 @@ public static function swap(array $map, $subject)
return strtr($subject, $map);
}

/**
* Take the first or last {$limit} characters of a string.
*
* @param string $string
* @param int $limit
* @return string
*/
public static function take($string, int $limit): string
{
if ($limit < 0) {
return static::substr($string, $limit);
}

return static::substr($string, 0, $limit);
}

/**
* Make a string's first character lowercase.
*
Expand Down
15 changes: 15 additions & 0 deletions src/Illuminate/Support/Stringable.php
Original file line number Diff line number Diff line change
Expand Up @@ -900,6 +900,21 @@ public function swap(array $map)
return new static(strtr($this->value, $map));
}

/**
* Take the first or last {$limit} characters.
*
* @param int $limit
* @return static
*/
public function take(int $limit)
{
if ($limit < 0) {
return $this->substr($limit);
}

return $this->substr(0, $limit);
}

/**
* Trim the string of the given characters.
*
Expand Down
6 changes: 6 additions & 0 deletions tests/Support/SupportStrTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -847,6 +847,12 @@ public function testSubstrReplace()
$this->assertSame('Laravel – The PHP Framework for Web Artisans', Str::substrReplace('Laravel Framework', '– The PHP Framework for Web Artisans', 8));
}

public function testTake()
{
$this->assertSame('ab', Str::take('abcdef', 2));
$this->assertSame('ef', Str::take('abcdef', -2));
}

public function testLcfirst()
{
$this->assertSame('laravel', Str::lcfirst('Laravel'));
Expand Down
6 changes: 6 additions & 0 deletions tests/Support/SupportStringableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,12 @@ public function testMatch()
$this->assertTrue($stringable->matchAll('/nothing/')->isEmpty());
}

public function testTake()
{
$this->assertSame('ab', (string) $this->stringable('abcdef')->take(2));
$this->assertSame('ef', (string) $this->stringable('abcdef')->take(-2));
}

public function testTest()
{
$stringable = $this->stringable('foo bar');
Expand Down