Skip to content

Commit 42c39f0

Browse files
[12.x] Add encrypt and decrypt Str helper methods (#55931)
* feat: add encrypt and decrypt Str helper methods * fix: styling issues * fix: Creation of dynamic property is depcreated error * trigger tests * Update Stringable.php --------- Co-authored-by: Taylor Otwell <taylor@laravel.com>
1 parent 0be5c5b commit 42c39f0

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

src/Illuminate/Support/Stringable.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1346,6 +1346,28 @@ public function hash(string $algorithm)
13461346
return new static(hash($algorithm, $this->value));
13471347
}
13481348

1349+
/**
1350+
* Encrypt the string.
1351+
*
1352+
* @param bool $serialize
1353+
* @return static
1354+
*/
1355+
public function encrypt(bool $serialize = false)
1356+
{
1357+
return new static(encrypt($this->value, $serialize));
1358+
}
1359+
1360+
/**
1361+
* Decrypt the string.
1362+
*
1363+
* @param bool $serialize
1364+
* @return static
1365+
*/
1366+
public function decrypt(bool $serialize = false)
1367+
{
1368+
return new static(decrypt($this->value, $serialize));
1369+
}
1370+
13491371
/**
13501372
* Dump the string.
13511373
*

tests/Support/SupportStringableTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
namespace Illuminate\Tests\Support;
44

5+
use Illuminate\Container\Container;
6+
use Illuminate\Encryption\Encrypter;
57
use Illuminate\Support\Carbon;
68
use Illuminate\Support\Collection;
79
use Illuminate\Support\HtmlString;
@@ -13,6 +15,8 @@
1315

1416
class SupportStringableTest extends TestCase
1517
{
18+
protected Container $container;
19+
1620
/**
1721
* @param string $string
1822
* @return \Illuminate\Support\Stringable
@@ -1438,4 +1442,16 @@ public function testHash()
14381442
$this->assertSame(hash('xxh3', 'foobar'), (string) $this->stringable('foobar')->hash('xxh3'));
14391443
$this->assertSame(hash('sha256', 'foobarbaz'), (string) $this->stringable('foobarbaz')->hash('sha256'));
14401444
}
1445+
1446+
public function testEncryptAndDecrypt()
1447+
{
1448+
Container::setInstance($this->container = new Container);
1449+
1450+
$this->container->bind('encrypter', fn () => new Encrypter(str_repeat('b', 16)));
1451+
1452+
$encrypted = encrypt('foo');
1453+
1454+
$this->assertNotSame('foo', $encrypted);
1455+
$this->assertSame('foo', decrypt($encrypted));
1456+
}
14411457
}

0 commit comments

Comments
 (0)