Skip to content

Add subscribers autowiring feature #40

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
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
122 changes: 122 additions & 0 deletions src/DependencyInjection/Compiler/RegisterAutowiredSubscribers.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
<?php

namespace SimpleBus\SymfonyBridge\DependencyInjection\Compiler;

use ReflectionClass;
use ReflectionMethod;
use RuntimeException;
use SimpleBus\Message\Name\NamedMessage;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
*
*/
final class RegisterAutowiredSubscribers implements CompilerPassInterface
{
private $serviceId;
private $autowiredSubscriberTag;
private $manualSubscriberTag;

/**
* @param string $serviceId The service id of the MessageSubscriberCollection
* @param string $autowiredSubscriberTag The tag name of autowired message subscriber services
* @param string $manualSubscriberTag The tag name of manual message subscriber services
*/
public function __construct($serviceId, $autowiredSubscriberTag, $manualSubscriberTag)
{
$this->serviceId = $serviceId;
$this->autowiredSubscriberTag = $autowiredSubscriberTag;
$this->manualSubscriberTag = $manualSubscriberTag;
}

/**
* Search for message autowired subscriber services and provide them as a constructor argument to the message subscriber
* collection service.
*
* @param ContainerBuilder $container
*/
public function process(ContainerBuilder $container)
{
if (!$container->has($this->serviceId)) {
return;
}

$definition = $container->findDefinition($this->serviceId);

$handlers = $definition->getArgument(0);

foreach ($container->findTaggedServiceIds($this->autowiredSubscriberTag) as $serviceId => $tags) {
if (count($tags) > 1) {
throw new RuntimeException(
sprintf('Service "%s" must contain the only "%s" tag.', $serviceId, $this->autowiredSubscriberTag)
);
}

$tag = $tags[0];

$subscriberDefinition = $container->getDefinition($serviceId);

if ($subscriberDefinition->hasTag($this->manualSubscriberTag)) {
throw new RuntimeException(
sprintf('Service "%s" must contain either "%s" or "%s" tag, not both of them.', $serviceId, $tag, $this->manualSubscriberTag)
);
}

if (!$subscriberDefinition->getClass()) {
throw new RuntimeException(
sprintf('Class is missing in the "%s" service.', $serviceId)
);
}

$handlers = array_merge_recursive(
$handlers,
$this->getHandlersFrom(new ReflectionClass($subscriberDefinition->getClass()), $serviceId)
);
}

$definition->replaceArgument(0, $handlers);
}

private function getHandlersFrom(ReflectionClass $class, $serviceId)
{
$handlers = [];

foreach ($class->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
if (
$method->getNumberOfParameters() !== 1
|| !$method->getParameters()[0]->getClass()
) {
throw new RuntimeException(
sprintf(
'Method "%s::%s" in service "%s" contains inappropriate public method for autowiring.'
. ' You can try to register your subscribers manually with the "%s" tag.',
$class->getName(),
$method->getName(),
$serviceId,
$this->manualSubscriberTag
)
);
}

$eventClass = $method->getParameters()[0]->getClass();

if ($eventClass->implementsInterface(NamedMessage::class)) {
throw new RuntimeException(
sprintf(
'Event "%s" is incompatible with autowiring feature because it implements the %s in service "%s".'
. ' You can try to register your subscribers manually with the "%s" tag.',
$eventClass->getName(),
NamedMessage::class,
$serviceId,
$this->manualSubscriberTag
)
);
}

$handlers[$eventClass->getName()][] = [$serviceId, $method->getName()];
}

return $handlers;
}
}
2 changes: 1 addition & 1 deletion src/DependencyInjection/Compiler/RegisterSubscribers.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public function process(ContainerBuilder $container)

$definition = $container->findDefinition($this->serviceId);

$handlers = array();
$handlers = $definition->getArgument(0);

$this->collectServiceIds(
$container,
Expand Down
9 changes: 9 additions & 0 deletions src/SimpleBusEventBusBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use SimpleBus\SymfonyBridge\DependencyInjection\Compiler\AddMiddlewareTags;
use SimpleBus\SymfonyBridge\DependencyInjection\Compiler\CompilerPassUtil;
use SimpleBus\SymfonyBridge\DependencyInjection\Compiler\ConfigureMiddlewares;
use SimpleBus\SymfonyBridge\DependencyInjection\Compiler\RegisterAutowiredSubscribers;
use SimpleBus\SymfonyBridge\DependencyInjection\Compiler\RegisterMessageRecorders;
use SimpleBus\SymfonyBridge\DependencyInjection\Compiler\RegisterSubscribers;
use SimpleBus\SymfonyBridge\DependencyInjection\EventBusExtension;
Expand Down Expand Up @@ -48,6 +49,14 @@ public function build(ContainerBuilder $container)
)
);

$container->addCompilerPass(
new RegisterAutowiredSubscribers(
'simple_bus.event_bus.event_subscribers_collection',
'event_subscriber_autowired',
'event_subscriber'
)
);

CompilerPassUtil::prependBeforeOptimizationPass(
$container,
new AddMiddlewareTags(
Expand Down
33 changes: 33 additions & 0 deletions tests/Functional/AutowiringTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace SimpleBus\SymfonyBridge\Tests\Functional;

use SimpleBus\SymfonyBridge\Tests\Functional\AutowiringTest\SendEmailVerificationInstructionsSubscriber;
use SimpleBus\SymfonyBridge\Tests\Functional\AutowiringTest\UserChangedEmail;
use SimpleBus\SymfonyBridge\Tests\Functional\AutowiringTest\UserRegistered;

/**
*
*/
final class AutowiringTest extends \PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function it_registers_and_handlers_autowired_subscribers()
{
$kernel = new TestKernel('test', true, 'autowiring', __DIR__ . '/AutowiringTest/config.yml');
$kernel->boot();
$container = $kernel->getContainer();

$eventBus = $container->get('event_bus');
$eventBus->handle(new UserRegistered(42));
$eventBus->handle(new UserChangedEmail(42));

$subscriber = $container->get('test_event_subscriber');
/** @var $subscriber SendEmailVerificationInstructionsSubscriber */

$this->assertTrue($subscriber->userRegisteredHandled);
$this->assertTrue($subscriber->userChangedEmailHandled);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

namespace SimpleBus\SymfonyBridge\Tests\Functional\AutowiringTest;

/**
*
*/
final class SendEmailVerificationInstructionsSubscriber
{
public $userRegisteredHandled = false;
public $userChangedEmailHandled = false;

public function onUserRegistered(UserRegistered $event)
{
$this->userRegisteredHandled = true;
}

public function onUserChangedEmail(UserChangedEmail $event)
{
$this->userChangedEmailHandled = true;
}
}
19 changes: 19 additions & 0 deletions tests/Functional/AutowiringTest/UserChangedEmail.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

namespace SimpleBus\SymfonyBridge\Tests\Functional\AutowiringTest;

/**
*
*/
final class UserChangedEmail
{
private $userId;

/**
* @param int $userId
*/
public function __construct($userId)
{
$this->userId = $userId;
}
}
19 changes: 19 additions & 0 deletions tests/Functional/AutowiringTest/UserRegistered.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

namespace SimpleBus\SymfonyBridge\Tests\Functional\AutowiringTest;

/**
*
*/
final class UserRegistered
{
private $userId;

/**
* @param int $userId
*/
public function __construct($userId)
{
$this->userId = $userId;
}
}
18 changes: 18 additions & 0 deletions tests/Functional/AutowiringTest/config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
services:
test_event_subscriber:
class: SimpleBus\SymfonyBridge\Tests\Functional\AutowiringTest\SendEmailVerificationInstructionsSubscriber
tags:
- { name: event_subscriber_autowired }

event_bus:
event_name_resolver_strategy: class_based

doctrine:
dbal:
driver: pdo_sqlite
path: :memory:
memory: true
orm:
entity_managers:
default:
connection: default
4 changes: 2 additions & 2 deletions tests/Functional/SmokeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Tools\SchemaTool;
use SimpleBus\SymfonyBridge\Tests\Functional\SmokeTest\TestCommand;
use SimpleBus\SymfonyBridge\Tests\Functional\SmokeTest\TestKernel;
use SimpleBus\SymfonyBridge\Tests\Functional\TestKernel;
use Symfony\Component\DependencyInjection\ContainerInterface;

class SmokeTest extends \PHPUnit_Framework_TestCase
Expand All @@ -15,7 +15,7 @@ class SmokeTest extends \PHPUnit_Framework_TestCase
*/
public function it_handles_a_command_then_dispatches_events_for_all_modified_entities()
{
$kernel = new TestKernel('test', true);
$kernel = new TestKernel('test', true, 'smoke', __DIR__ . '/SmokeTest/config.yml');
$kernel->boot();
$container = $kernel->getContainer();

Expand Down
4 changes: 1 addition & 3 deletions tests/Functional/SmokeTest/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@ services:
class: SimpleBus\SymfonyBridge\Tests\Functional\SmokeTest\SomeOtherEventSubscriber
tags:
- { name: event_subscriber, subscribes_to: some_other_event }
arguments:
- '@command_bus'

doctrine:
dbal:
Expand All @@ -45,7 +43,7 @@ doctrine:
mappings:
test:
type: annotation
dir: "%kernel.root_dir%/Entity/"
dir: "%kernel.root_dir%/SmokeTest/Entity/"
prefix: SimpleBus\SymfonyBridge\Tests\Functional\SmokeTest\Entity
alias: Test
is_bundle: false
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

namespace SimpleBus\SymfonyBridge\Tests\Functional\SmokeTest;
namespace SimpleBus\SymfonyBridge\Tests\Functional;

use Doctrine\Bundle\DoctrineBundle\DoctrineBundle;
use SimpleBus\SymfonyBridge\SimpleBusCommandBusBundle;
Expand All @@ -13,13 +13,17 @@
class TestKernel extends Kernel
{
private $tempDir;
private $configPath;

public function __construct($environment, $debug)
public function __construct($environment, $debug, $name, $configPath)
{
parent::__construct($environment, $debug);

$this->tempDir = sys_get_temp_dir() . '/' . uniqid();
mkdir($this->tempDir, 0777, true);

$this->name = $name;
$this->configPath = $configPath;
}

public function registerBundles()
Expand All @@ -35,7 +39,7 @@ public function registerBundles()

public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__ . '/config.yml');
$loader->load($this->configPath);
}

public function getCacheDir()
Expand Down