Skip to content
This repository has been archived by the owner on Jul 15, 2021. It is now read-only.

Commit

Permalink
Use factory to inject subscribers to clients
Browse files Browse the repository at this point in the history
  • Loading branch information
iamluc committed Oct 17, 2014
1 parent 3ea17af commit 3622ad5
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 14 deletions.
17 changes: 6 additions & 11 deletions dist/DependencyInjection/CompilerPass/SubscriberPass.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,12 @@ public function process(ContainerBuilder $container)
return;
}

$clients = $container->findTaggedServiceIds('csa_guzzle.client');

if (!count($clients)) {
return;
}

foreach ($clients as $id => $options) {
$client = $container->findDefinition($id);
foreach ($subscribers as $subscriber => $options) {
$client->addMethodCall('addSubscriber', [new Reference($subscriber)]);
}
// Factory
$factory = $container->findDefinition('csa_guzzle.client_factory');
$arg = [];
foreach ($subscribers as $subscriber => $options) {
$arg[] = new Reference($subscriber);
}
$factory->replaceArgument(1, $arg);
}
}
20 changes: 17 additions & 3 deletions dist/Factory/ClientFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@

namespace Csa\Bundle\GuzzleBundle\Factory;

use GuzzleHttp\Event\HasEmitterInterface;
use GuzzleHttp\Event\SubscriberInterface;

/**
* Csa Guzzle client compiler pass
*
Expand All @@ -19,17 +22,28 @@
class ClientFactory
{
private $class;
private $subscribers;

/**
* @param string $class The client's class
* @param string $class The client's class
* @param SubscriberInterface[] $subscribers A list of subscribers to attach to each client
*/
public function __construct($class)
public function __construct($class, array $subscribers = [])
{
$this->class = $class;
$this->subscribers = $subscribers;
}

public function create(array $options = [])
{
return new $this->class($options);
$client = new $this->class($options);

if ($client instanceof HasEmitterInterface) {
foreach ($this->subscribers as $subscriber) {
$client->getEmitter()->attach($subscriber);
}
}

return $client;
}
}
1 change: 1 addition & 0 deletions dist/Resources/config/factory.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

<service id="csa_guzzle.client_factory" class="%csa_guzzle.client_factory.class%">
<argument>%csa_guzzle.client.class%</argument>
<argument />
</service>

</services>
Expand Down

0 comments on commit 3622ad5

Please sign in to comment.