Skip to content

Commit

Permalink
Apply Router to Websocket RPC class
Browse files Browse the repository at this point in the history
  • Loading branch information
roxblnfk committed Dec 12, 2023
1 parent 296d608 commit 9502d57
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 18 deletions.
47 changes: 30 additions & 17 deletions src/Sender/Websocket/RPC.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@

namespace Buggregator\Trap\Sender\Websocket;

use Buggregator\Trap\Info;
use Buggregator\Trap\Handler\Router\Attribute\RegexpRoute;
use Buggregator\Trap\Handler\Router\Attribute\StaticRoute;
use Buggregator\Trap\Handler\Router\Method;
use Buggregator\Trap\Handler\Router\Router;
use Buggregator\Trap\Logger;
use Buggregator\Trap\Support\Json;
use Buggregator\Trap\Support\Uuid;
use JsonSerializable;

Expand All @@ -15,10 +17,13 @@
*/
final class RPC
{
private readonly Router $router;

public function __construct(
private readonly Logger $logger,
private readonly EventsStorage $eventsStorage,
) {
$this->router = Router::new($this);
}

public function handleMessage(string $message): ?object
Expand Down Expand Up @@ -49,26 +54,34 @@ public function handleMessage(string $message): ?object
return null;
}

#[RegexpRoute(Method::Delete, '#^/api/events/(?<uuid>[a-f0-9-]++)#i')]
public function eventDelete(string $uuid): bool
{
$this->eventsStorage->delete($uuid);
return true;
}

#[StaticRoute(Method::Delete, 'api/events')]
public function eventsDelete(): bool
{
$this->eventsStorage->clear();
return true;
}

private function callMethod(int|string $id, string $initMethod): ?JsonSerializable
{
[$method, $path] = \explode(':', $initMethod, 2);

switch ($method) {
case 'delete':
if (\str_starts_with($path, 'api/event/')) {
$uuid = \substr($path, 10);
$this->eventsStorage->delete($uuid);
return new RPC\Success(id: $id, code: 200, status: true);
}
if (\str_starts_with($path, 'api/events')) {
$this->eventsStorage->clear();
return new RPC\Success(id: $id, code: 200, status: true);
}
break;
default:
$this->logger->error('Unknown RPC method: ' . $initMethod);
$route = $this->router->match(Method::fromString($method), $path ?? '');

if ($route === null) {
// todo: Error message
return null;
}
$result = $route(id: $id);

return null;
return $result === true
? new RPC\Success(id: $id, code: 200, status: true)
: $result;
}
}
1 change: 0 additions & 1 deletion src/Support/ProtobufCaster.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
namespace Buggregator\Trap\Support;

use Buggregator\Trap\Support\Caster\EnumValue;
use Google\Protobuf\FieldDescriptor;
use Google\Protobuf\Internal\Descriptor as InternalDescriptor;
use Google\Protobuf\Descriptor as PublicDescriptor;
use Google\Protobuf\Internal\DescriptorPool;
Expand Down

0 comments on commit 9502d57

Please sign in to comment.