Skip to content

Commit 5519cf6

Browse files
committed
add nostr encoding/decoding support
1 parent 01c2d47 commit 5519cf6

File tree

3 files changed

+35
-2
lines changed

3 files changed

+35
-2
lines changed

composer.lock

+2-2
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/Nostr.php

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?php
2+
3+
namespace nostriphant\NIP01;
4+
5+
class Nostr {
6+
7+
static function encode(mixed $json) : string {
8+
return json_encode($json, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
9+
}
10+
static function decode(string $json): mixed {
11+
$object = json_decode($json, true);
12+
if (isset($object) === false) {
13+
throw new \InvalidArgumentException('Invalid message');
14+
}
15+
return $object;
16+
}
17+
}

tests/NostrTest.php

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<?php
2+
3+
use nostriphant\NIP01\Nostr;
4+
5+
it('encodes and decodes data', function (mixed $in, string $expected) {
6+
$encoded = Nostr::encode($in);
7+
expect($encoded)->toBe($expected);
8+
expect(Nostr::decode($encoded))->toBe($in);
9+
})->with([
10+
[['this' => 'is data'], json_encode(['this' => 'is data'])]
11+
]);
12+
13+
14+
it('fails when invalid json', function () {
15+
expect(fn() => Nostr::decode('{invalid:json}'))->toThrow(\InvalidArgumentException::class);
16+
});

0 commit comments

Comments
 (0)