GuzzleClientFactory::extractResponseClasses()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.7333
c 0
b 0
f 0
cc 4
nc 4
nop 1
1
<?php
2
3
namespace Guzzle\ConfigOperationsBundle;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\Command\Guzzle\Description;
7
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
8
use Symfony\Component\DependencyInjection\ContainerInterface;
9
use Symfony\Component\Serializer\SerializerInterface;
10
11
/**
12
 * Factory for guzzle clients
13
 *
14
 * @author Pierre Rolland <[email protected]>
15
 */
16
class GuzzleClientFactory implements ContainerAwareInterface
17
{
18
    /**
19
     * @var ContainerInterface
20
     */
21
    protected $container;
22
23
    /**
24
     * @var SerializerInterface|\JMS\Serializer\SerializerInterface
25
     */
26
    protected $serializer;
27
28
    /**
29
     * @param SerializerInterface|\JMS\Serializer\SerializerInterface $serializer
30
     */
31
    public function __construct($serializer)
32
    {
33
        $this->serializer = $serializer;
34
    }
35
36
    public function getClient(string $clientId): GuzzleClient
37
    {
38
        /* @var Client $client */
39
        $client = $this->container->get($clientId);
40
        $config = $client->getConfig();
41
        $responseClasses = $this->extractResponseClasses($config);
42
        $description = new Description($config);
43
44
        return new GuzzleClient($client, $description, $responseClasses, $this->serializer);
45
    }
46
47
    protected function extractResponseClasses(array &$config): array
48
    {
49
        if (!array_key_exists('operations', $config)) {
50
            return [];
51
        }
52
53
        $responseClasses = [];
54
        foreach ($config['operations'] as $operationName => $operation) {
55
            if (array_key_exists('responseClass', $operation)) {
56
                $responseClasses[$operationName] = $operation['responseClass'];
57
                unset($config['operations'][$operationName]['responseClass']);
58
            }
59
        }
60
61
        return $responseClasses;
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67
    public function setContainer(ContainerInterface $container = null): void
68
    {
69
        $this->container = $container;
70
    }
71
}
72