Skip to content

Commit

Permalink
allow messages to be created through static factory methods
Browse files Browse the repository at this point in the history
  • Loading branch information
rikmeijer committed Dec 16, 2024
1 parent abebc43 commit f166b7f
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,23 @@ if (Key::verify($public_key, $signature, $hash)) {
echo 'Signature belongs to hash';
}
```


## Message usage

```
use nostriphant\NIP01\Message;
$message = Message::count(1);
print $message; // prints "['COUNT',1]"
```

```
use nostriphant\NIP01\Message;
use nostriphant\NIP01\Event;
$message = Message::event(new Event());
print $message; // prints "['EVENT',{...}]"
```
4 changes: 4 additions & 0 deletions src/Message.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,8 @@ public function __toString(): string {
static function decode(string $json): self {
return new self(...Nostr::decode($json));
}

static function __callStatic(string $name, array $arguments): self {
return new self(strtoupper($name), ...$arguments);
}
}
22 changes: 22 additions & 0 deletions tests/MessageTest.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php

use nostriphant\NIP01\Message;
use nostriphant\NIP01\Event;

it('can construct a message', function () {
$message = new Message('TYPE', 'a', ['b' => 'c']);
Expand All @@ -16,3 +17,24 @@
$message = Message::decode('["TYPE", "a", {"b":"c"}]');
expect($message())->toBe(['TYPE', 'a', ['b' => 'c']]);
});


it('can fabric a message', function () {
$message = Message::event('a', ['b' => 'c']);
expect($message())->toBe(['EVENT', 'a', ['b' => 'c']]);
});

it('can fabric a message with an Event', function () {
$message = Message::event($event = new Event(
id: '',
pubkey: '',
created_at: 1734349976,
kind: 1,
content: 'Hello World',
sig: '',
tags: []
));

expect($message())->toBe(["EVENT", $event]);
expect('' . $message)->toBe('["EVENT",{"id":"","pubkey":"","created_at":1734349976,"kind":1,"content":"Hello World","sig":"","tags":[]}]');
});

0 comments on commit f166b7f

Please sign in to comment.