Skip to content

Commit

Permalink
add hex strategy
Browse files Browse the repository at this point in the history
  • Loading branch information
mokhosh committed Nov 3, 2024
1 parent ecbf057 commit dfb50d5
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/Strategies/Link/Hex.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

namespace Mokhosh\Muddle\Strategies\Link;

use Mokhosh\Muddle\Contracts\LinkStrategy;
use Mokhosh\Muddle\Support\Str;

class Hex implements LinkStrategy
{
public function muddle(string $string, string $title): string
{
$id = Str::id();
$key = random_int(0, 255);
$hexed = Str::hex('mailto:'.$string, $key);
$script = <<<HTML
</a><script>(function() {
const codes = $id.getAttribute('href').split(' ')
$id.href = ''
for (const code of codes) $id.href = $id.getAttribute('href') + String.fromCharCode(parseInt(code, 16) ^ $key)
})()</script>
HTML;

return "<a id='$id' href='$hexed'>".$title.$script;
}

public function unmuddle(string $string): string
{
preg_match('/ \^ (\d+)/', $string, $key);
preg_match('/href=\'([^\']+)\'>/', $string, $hexed);
preg_match('/>([^<]+)<\/a>/', $string, $title);

return '<a href="'.Str::unhex($hexed[1], $key[1])."\">$title[1]</a>";
}
}
10 changes: 10 additions & 0 deletions tests/Strategies/Link/HexTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

use Mokhosh\Muddle\Strategies\Link\Hex;

it('muddles text', function () {
expect($muddled = (new Hex)->muddle('[email protected]', 'email'))
->not->toBe('<a href="mailto:[email protected]">email</a>')
->and((new Hex)->unmuddle($muddled))
->toBe('<a href="mailto:[email protected]">email</a>');
});

0 comments on commit dfb50d5

Please sign in to comment.