Skip to content

Commit f2cac74

Browse files
committed
feat(str): add swap() method
1 parent 20968da commit f2cac74

3 files changed

Lines changed: 60 additions & 0 deletions

File tree

docs/methods.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -752,6 +752,21 @@ echo $str->surround('!!!');
752752
// !!!Foo Bar!!!
753753
```
754754

755+
### swap `Utility`
756+
Swap multiple keywords in the string using a key/value map
757+
758+
```php
759+
$str = new Utility('foo bar')
760+
761+
echo $str->swap(['foo' => 'bar', 'bar' => 'foo']);
762+
// bar foo
763+
764+
$str = new Utility('a-b-c')
765+
766+
echo $str->swap(['a' => '1', 'b' => '2', 'c' => '3']);
767+
// 1-2-3
768+
```
769+
755770
### toAlphanumeric `Utility`
756771
Convert the string to only contain alphanumeric values
757772

src/Utility.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -835,6 +835,20 @@ public function surround(string|Stringable|Utility $with): Utility
835835
return static::make(implode('', [$utility, $this->string, $utility]), $this->encoding);
836836
}
837837

838+
/**
839+
* Swap multiple keywords in the string using a key/value map
840+
*
841+
* @param array<string, string> $map
842+
*/
843+
public function swap(array $map): Utility
844+
{
845+
if ($map === []) {
846+
return static::make($this->string, $this->encoding);
847+
}
848+
849+
return static::make(strtr($this->string, $map), $this->encoding);
850+
}
851+
838852
/**
839853
* Sanitize a string to only contain letters
840854
*/

tests/SwapTest.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Tests;
6+
7+
use PHPUnit\Framework\Attributes\DataProvider;
8+
use Iterator;
9+
10+
final class SwapTest extends BaseStringSuite
11+
{
12+
public static function __validData(): Iterator
13+
{
14+
yield ['bar foo', 'foo bar', ['foo' => 'bar', 'bar' => 'foo']];
15+
yield ['Hello World', 'Hello World', []];
16+
yield ['Hello World', 'Hi World', ['Hi' => 'Hello']];
17+
yield ['abc', 'xyz', ['x' => 'a', 'y' => 'b', 'z' => 'c']];
18+
yield ['', '', ['foo' => 'bar']];
19+
yield ['Hello World', 'Hello World', ['xyz' => 'abc']];
20+
yield ['foobär', 'foobaz', ['baz' => 'bär']];
21+
yield ['1-2-3', 'a-b-c', ['a' => '1', 'b' => '2', 'c' => '3']];
22+
yield ['HELLO world', 'hello WORLD', ['hello' => 'HELLO', 'WORLD' => 'world']];
23+
yield ['foo foo', 'bar bar', ['bar' => 'foo']];
24+
}
25+
26+
#[DataProvider('__validData')]
27+
public function testSwapMethod(string $expected, string $string, array $map): void
28+
{
29+
$this->assertSame($expected, $this->utility($string)->swap($map)->value());
30+
}
31+
}

0 commit comments

Comments
 (0)