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

Commit 3622ad5

Browse files
author
iamluc
committed
Use factory to inject subscribers to clients
1 parent 3ea17af commit 3622ad5

File tree

3 files changed

+24
-14
lines changed

3 files changed

+24
-14
lines changed

dist/DependencyInjection/CompilerPass/SubscriberPass.php

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -30,17 +30,12 @@ public function process(ContainerBuilder $container)
3030
return;
3131
}
3232

33-
$clients = $container->findTaggedServiceIds('csa_guzzle.client');
34-
35-
if (!count($clients)) {
36-
return;
37-
}
38-
39-
foreach ($clients as $id => $options) {
40-
$client = $container->findDefinition($id);
41-
foreach ($subscribers as $subscriber => $options) {
42-
$client->addMethodCall('addSubscriber', [new Reference($subscriber)]);
43-
}
33+
// Factory
34+
$factory = $container->findDefinition('csa_guzzle.client_factory');
35+
$arg = [];
36+
foreach ($subscribers as $subscriber => $options) {
37+
$arg[] = new Reference($subscriber);
4438
}
39+
$factory->replaceArgument(1, $arg);
4540
}
4641
}

dist/Factory/ClientFactory.php

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@
1111

1212
namespace Csa\Bundle\GuzzleBundle\Factory;
1313

14+
use GuzzleHttp\Event\HasEmitterInterface;
15+
use GuzzleHttp\Event\SubscriberInterface;
16+
1417
/**
1518
* Csa Guzzle client compiler pass
1619
*
@@ -19,17 +22,28 @@
1922
class ClientFactory
2023
{
2124
private $class;
25+
private $subscribers;
2226

2327
/**
24-
* @param string $class The client's class
28+
* @param string $class The client's class
29+
* @param SubscriberInterface[] $subscribers A list of subscribers to attach to each client
2530
*/
26-
public function __construct($class)
31+
public function __construct($class, array $subscribers = [])
2732
{
2833
$this->class = $class;
34+
$this->subscribers = $subscribers;
2935
}
3036

3137
public function create(array $options = [])
3238
{
33-
return new $this->class($options);
39+
$client = new $this->class($options);
40+
41+
if ($client instanceof HasEmitterInterface) {
42+
foreach ($this->subscribers as $subscriber) {
43+
$client->getEmitter()->attach($subscriber);
44+
}
45+
}
46+
47+
return $client;
3448
}
3549
}

dist/Resources/config/factory.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
<service id="csa_guzzle.client_factory" class="%csa_guzzle.client_factory.class%">
1515
<argument>%csa_guzzle.client.class%</argument>
16+
<argument />
1617
</service>
1718

1819
</services>

0 commit comments

Comments
 (0)