Skip to content

Commit

Permalink
[10.x] Add str()->take($limit) and Str::take($string, $limit) (#48467)
Browse files Browse the repository at this point in the history
* Add str()->take($limit)

Take the first or last {$limit} characters.

* Add test for str()->take($limit)

* Styling

* Styling

* add take method to Str as well
  • Loading branch information
moshe-autoleadstar authored Sep 20, 2023
1 parent 1157523 commit 9e1c516
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 0 deletions.
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

0 comments on commit 9e1c516

Please sign in to comment.