GuzzleClient::getResponseClass()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace Guzzle\ConfigOperationsBundle;
4
5
use GuzzleHttp\ClientInterface;
6
use GuzzleHttp\Command\CommandInterface;
7
use GuzzleHttp\Command\Guzzle\DescriptionInterface;
8
use GuzzleHttp\Command\Guzzle\GuzzleClient as BaseGuzzleClient;
9
use Psr\Http\Message\RequestInterface;
10
use Psr\Http\Message\ResponseInterface;
11
use Symfony\Component\Serializer\SerializerInterface;
12
13
/**
14
 * Overloads the original GuzzleClient to add the Serializer
15
 *
16
 * @author Pierre Rolland <[email protected]>
17
 */
18
class GuzzleClient extends BaseGuzzleClient
19
{
20
    /**
21
     * @var array
22
     */
23
    protected $responseClasses = [];
24
25
    /**
26
     * @var ClientInterface
27
     */
28
    protected $client;
29
30
    /**
31
     * @var SerializerInterface|\JMS\Serializer\SerializerInterface
32
     */
33
    protected $serializer;
34
35
    /**
36
     * @param ClientInterface $client
37
     * @param DescriptionInterface $description
38
     * @param array $responseClasses
39
     * @param SerializerInterface|\JMS\Serializer\SerializerInterface $serializer
40
     * @param array $config
41
     */
42
    public function __construct(
43
        ClientInterface $client,
44
        DescriptionInterface $description,
45
        array $responseClasses,
46
        $serializer,
47
        array $config = []
48
    ) {
49
        $this->client = $client;
50
        $this->responseClasses = $responseClasses;
51
        $this->serializer = $serializer;
52
53
        parent::__construct(
54
            $client,
55
            $description,
56
            null,
57
            [$this, 'transformResponse'],
58
            null,
59
            $config
60
        );
61
    }
62
63
    protected function getResponseClass(string $name): ?string
64
    {
65
        return array_key_exists($name, $this->responseClasses) ? $this->responseClasses[$name] : null;
66
    }
67
68
    /**
69
     * @param ResponseInterface $response
70
     * @param RequestInterface $request
71
     * @param CommandInterface $command
72
     *
73
     * @return ResponseInterface|object|array
74
     */
75
    public function transformResponse(ResponseInterface $response, RequestInterface $request, CommandInterface $command)
76
    {
77
        $responseClass = $this->getResponseClass($command->getName());
78
79
        if (null === $responseClass) {
80
            return $response;
81
        }
82
83
        $body = $response->getBody()->getContents();
84
85
        if (empty($body)) {
86
            return null;
87
        }
88
89
        return $responseClass === 'array' ? json_decode($body, true) : $this
90
            ->serializer
91
            ->deserialize($body, $responseClass, 'json');
92
    }
93
}
94