Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@
"symfony/property-info": "^5.0 || ^6.0",
"phpdocumentor/reflection-docblock": "^5.0",
"phpstan/phpdoc-parser": "^1.24",
"webmozart/assert": "^1.11"
"webmozart/assert": "^1.11",
"jolicode/automapper": "^9.2"
},
"require-dev": {
"phpunit/phpunit": "^9.5",
Expand Down
2 changes: 2 additions & 0 deletions src/Attribute/Event.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@ final class Event extends Attribute
* @param array<On> $dispatch
* @param array<string>|string|null $handler
* @param array<string>|string|null $transport
* @param class-string|null $messageClass
*/
public function __construct(
array|string|null $handler = null,
array|string|null $transport = null,
public readonly ?string $name = null,
public readonly ?string $queue = null,
public readonly array $dispatch = [On::POST],
public readonly ?string $messageClass = null,
) {
parent::__construct();
Assert::allIsInstanceOf($dispatch, On::class);
Expand Down
3 changes: 1 addition & 2 deletions src/Handler/Contract/EventHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@
namespace OpenClassrooms\ServiceProxy\Handler\Contract;

use OpenClassrooms\ServiceProxy\Attribute\Event\Transport;
use OpenClassrooms\ServiceProxy\Model\Event;
use OpenClassrooms\ServiceProxy\Model\Request\Instance;

interface EventHandler extends AnnotationHandler
{
public function dispatch(Event $event, ?string $queue = null): void;
public function dispatch(object $event, ?string $queue = null): void;

public function listen(Instance $instance, string $name, Transport $transport = null, int $priority = 0): void;
}
5 changes: 4 additions & 1 deletion src/Handler/Impl/Event/HttpEventHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,11 @@ public function __construct(
* @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
*/
public function dispatch(Event $event, ?string $queue = null): void
public function dispatch(object $event, ?string $queue = null): void
{
if (!$event instanceof Event) {
throw new \InvalidArgumentException('Event must be an instance of ' . Event::class);
}
$message = $this->createMessage($event, $queue);
$response = $this->httpClient->request('POST', $this->config->brokerEndpoint, [
'body' => $this->serializer->serialize([
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,11 @@ public function __construct(
) {
}

public function dispatch(Event $event, ?string $queue = null): void
public function dispatch(object $event, ?string $queue = null): void
{
if (!$event instanceof Event) {
throw new \InvalidArgumentException('Event must be an instance of ' . Event::class);
}
$this->eventDispatcher->dispatch(
$event,
$event->name,
Expand Down
9 changes: 7 additions & 2 deletions src/Handler/Impl/Event/SymfonyMessengerEventHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,14 @@ public function __construct(
$this->logger = $logger ?? new NullLogger();
}

public function dispatch(Event $event, ?string $queue = null): void
public function dispatch(object $event, ?string $queue = null): void
{
$message = $this->createMessage($event, $queue);
if ($event instanceof Event) {
$message = $this->createMessage($event, $queue);
} else {
$message = $event;
}

try {
$this->bus->dispatch($message);
} catch (\Throwable $exception) {
Expand Down
1 change: 1 addition & 0 deletions src/Interceptor/Config/EventInterceptorConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ final class EventInterceptorConfig
*/
public function __construct(
public readonly string $eventInstanceClassName = Event::class,
public readonly ?string $mapperCacheDir = null,
) {
}
}
47 changes: 41 additions & 6 deletions src/Interceptor/Impl/EventInterceptor.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

namespace OpenClassrooms\ServiceProxy\Interceptor\Impl;

use AutoMapper\AutoMapper;
use AutoMapper\AutoMapperInterface;
use OpenClassrooms\ServiceProxy\Attribute\Event;
use OpenClassrooms\ServiceProxy\Handler\Contract\EventHandler;
use OpenClassrooms\ServiceProxy\Interceptor\Config\EventInterceptorConfig;
Expand All @@ -17,12 +19,16 @@

final class EventInterceptor extends AbstractInterceptor implements SuffixInterceptor, PrefixInterceptor
{
private AutoMapperInterface $mapper;

public function __construct(
private readonly EventFactory $eventFactory,
private readonly EventInterceptorConfig $config,
iterable $handlers = [],
) {
parent::__construct($handlers);
$tmpDir = $this->config->mapperCacheDir ?? sys_get_temp_dir() . '/mapper-cache';
$this->mapper = AutoMapper::create(cacheDirectory: $tmpDir);
}

public function getPrefixPriority(): int
Expand Down Expand Up @@ -68,12 +74,19 @@ public function suffix(Instance $instance): Response
$handlers = $this->getHandlers(EventHandler::class, $attribute);
foreach ($handlers as $handler) {
if ($attribute->isPost() && !$instance->getMethod()->threwException()) {
$event = $this->eventFactory->createFromSenderInstance(
$instance,
Moment::SUFFIX,
$attribute->name,
$this->config->eventInstanceClassName,
);
if ($attribute->messageClass) {
$event = $this->createMessage(
$attribute->messageClass,
$instance->getMethod()->getReturnedValue(),
);
} else {
$event = $this->eventFactory->createFromSenderInstance(
$instance,
Moment::SUFFIX,
$attribute->name,
$this->config->eventInstanceClassName,
);
}
$handler->dispatch($event, $attribute->queue);
}

Expand Down Expand Up @@ -102,4 +115,26 @@ public function supportsPrefix(Instance $instance): bool
return $instance->getMethod()
->hasAttribute(Event::class);
}

/**
* @template T of object
* @param class-string<T> $messageClass
* @return T
*
* @throws \InvalidArgumentException
*/
private function createMessage(string $messageClass, mixed $response): object
{
if (!\is_object($response) && !\is_array($response)) {
throw new \InvalidArgumentException(
sprintf(
'The response must be an object to guess arguments for message class "%s".',
$messageClass
)
);
}

/** @var T */
return $this->mapper->map($response, $messageClass);
}
}
3 changes: 1 addition & 2 deletions tests/Double/Mock/Event/EventHandlerMock.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

use OpenClassrooms\ServiceProxy\Attribute\Event\Transport;
use OpenClassrooms\ServiceProxy\Handler\Contract\EventHandler;
use OpenClassrooms\ServiceProxy\Model\Event;
use OpenClassrooms\ServiceProxy\Model\Request\Instance;

final class EventHandlerMock implements EventHandler
Expand All @@ -26,7 +25,7 @@ public function getName(): string
return 'array';
}

public function dispatch(Event $event, ?string $queue = null): void
public function dispatch(object $event, ?string $queue = null): void
{
$this->events[] = $event;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

declare(strict_types=1);

namespace OpenClassrooms\ServiceProxy\Tests\Double\Stub\Event;

use OpenClassrooms\ServiceProxy\Attribute\Event;

class InvalidResponseMessageClassAnnotatedClass
{
#[Event(messageClass: CustomMessage::class)]
public function invalid(string $value): int
{
return 42;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

declare(strict_types=1);

namespace OpenClassrooms\ServiceProxy\Tests\Double\Stub\Event;

use OpenClassrooms\ServiceProxy\Attribute\Event;

class CustomMessage
{
public function __construct(
public string $content,
public int $id,
public \DateTimeImmutable $createdAt,
public Metadata $meta = new Metadata(active: false),
) {
}
}

class Metadata
{
public function __construct(
public readonly bool $active,
public readonly \DateTimeImmutable $createdAt = new \DateTimeImmutable(),
) {
}
}

class ResponseObject
{
public function __construct(
public string $content,
public int $id,
public Metadata $meta,
public \DateTimeImmutable $createdAt,
) {
}
}

class ObjectResponseMessageClassAnnotatedClass
{
/**
* @throws \Random\RandomException
*/
#[Event(messageClass: CustomMessage::class)]
public function handle(string $content): ResponseObject
{
return new ResponseObject(
content: $content,
id: random_int(1, 100),
meta: new Metadata(active: true),
createdAt: new \DateTimeImmutable(),
);
}
}
38 changes: 38 additions & 0 deletions tests/Interceptor/EventInterceptorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,13 @@
use OpenClassrooms\ServiceProxy\Interceptor\Impl\EventInterceptor;
use OpenClassrooms\ServiceProxy\ProxyFactory;
use OpenClassrooms\ServiceProxy\Tests\Double\Mock\Event\EventHandlerMock;
use OpenClassrooms\ServiceProxy\Tests\Double\Stub\Event\CustomMessage;
use OpenClassrooms\ServiceProxy\Tests\Double\Stub\Event\EventAnnotatedClass;
use OpenClassrooms\ServiceProxy\Tests\Double\Stub\Event\InvalidMethodEventAnnotatedClass;
use OpenClassrooms\ServiceProxy\Tests\Double\Stub\Event\InvalidResponseMessageClassAnnotatedClass;
use OpenClassrooms\ServiceProxy\Tests\Double\Stub\Event\Metadata;
use OpenClassrooms\ServiceProxy\Tests\Double\Stub\Event\ObjectResponseMessageClassAnnotatedClass;
use OpenClassrooms\ServiceProxy\Tests\Double\Stub\Event\ResponseObject;
use OpenClassrooms\ServiceProxy\Tests\ProxyTestTrait;
use PHPUnit\Framework\TestCase;

Expand Down Expand Up @@ -114,6 +119,39 @@ public function testMultiEventsSendMultiple(): void
);
}

public function testMessageClassEventDispatchedWithObjectResponse(): void
{
$proxy = $this->proxyFactory->createProxy(new ObjectResponseMessageClassAnnotatedClass());
$result = $proxy->handle('world');

$this->assertInstanceOf(ResponseObject::class, $result);
$this->assertSame('world', $result->content);
$this->assertIsInt($result->id);
$this->assertInstanceOf(Metadata::class, $result->meta);
$this->assertInstanceOf(\DateTimeImmutable::class, $result->createdAt);

$this->assertEventsCount(1);
$event = $this->handler->getEvents()[0];
$this->assertInstanceOf(CustomMessage::class, $event);
$this->assertSame('world', $event->content);
$this->assertSame($result->id, $event->id);
$this->assertInstanceOf(\DateTimeImmutable::class, $event->createdAt);
$this->assertSame(
$result->createdAt->format(\DateTimeInterface::ATOM),
$event->createdAt->format(\DateTimeInterface::ATOM)
);
$this->assertInstanceOf(Metadata::class, $event->meta);
$this->assertTrue($event->meta->active);
}

public function testInvalidResponseForMessageClassThrowsException(): void
{
$proxy = $this->proxyFactory->createProxy(new InvalidResponseMessageClassAnnotatedClass());

$this->expectException(\InvalidArgumentException::class);
$proxy->invalid('test');
}

private function assertEventsCount(int $count): void
{
$this->assertCount($count, $this->handler->getEvents());
Expand Down