Completed
Pull Request — master (#76)
by Thibaud
02:50
created

GuzzleClient::addRequestParameters()   C

Complexity

Conditions 7
Paths 14

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 24
rs 6.7272
cc 7
eloc 14
nc 14
nop 4
1
<?php
2
3
/*
4
 * This file is part of Phraseanet SDK.
5
 *
6
 * (c) Alchemy <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace PhraseanetSDK\Http\Guzzle;
13
14
use Guzzle\Common\Exception\GuzzleException;
15
use Guzzle\Http\Client as Guzzle;
16
use Guzzle\Http\ClientInterface;
17
use Guzzle\Http\Exception\BadResponseException as GuzzleBadResponse;
18
use Guzzle\Http\Exception\CurlException;
19
use Guzzle\Http\Message\EntityEnclosingRequestInterface;
20
use Guzzle\Http\Message\RequestInterface;
21
use PhraseanetSDK\ApplicationInterface;
22
use PhraseanetSDK\Exception\BadResponseException;
23
use PhraseanetSDK\Exception\InvalidArgumentException;
24
use PhraseanetSDK\Exception\RuntimeException;
25
use PhraseanetSDK\Http\Client;
26
use PhraseanetSDK\Http\Endpoint;
27
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
28
29
class GuzzleClient implements Client
30
{
31
    /**
32
     * Creates a new instance of GuzzleAdapter
33
     *
34
     * @param Endpoint $endpoint
35
     * @param EventSubscriberInterface[] $plugins
36
     * @return static
37
     */
38
    public static function create(Endpoint $endpoint, array $plugins = array())
39
    {
40
        $userAgent = sprintf('%s version %s', ApplicationInterface::USER_AGENT, ApplicationInterface::VERSION);
41
        $guzzle = new Guzzle($endpoint->getUrl());
42
43
        $guzzle->setUserAgent($userAgent);
44
45
        foreach ($plugins as $plugin) {
46
            $guzzle->addSubscriber($plugin);
47
        }
48
49
        return new static($guzzle, $endpoint);
50
    }
51
52
    /**
53
     * @var ClientInterface
54
     */
55
    private $guzzle;
56
57
    /**
58
     * @var Endpoint
59
     */
60
    private $endpoint;
61
62
    /**
63
     * @param ClientInterface $guzzle
64
     * @param Endpoint $endpoint
65
     */
66
    public function __construct(ClientInterface $guzzle, Endpoint $endpoint)
67
    {
68
        $this->guzzle = $guzzle;
69
        $this->endpoint = $endpoint;
70
    }
71
72
    /**
73
     * @return Endpoint
74
     */
75
    public function getEndpoint()
76
    {
77
        return $this->endpoint;
78
    }
79
80
    /**
81
     * @return ClientInterface
82
     */
83
    public function getGuzzle()
84
    {
85
        return $this->guzzle;
86
    }
87
88
    /**
89
     * Returns the client base URL
90
     *
91
     * @return string
92
     */
93
    public function getBaseUrl()
94
    {
95
        return $this->guzzle->getBaseUrl();
96
    }
97
98
    /**
99
     * Sets the user agent
100
     *
101
     * @param string $userAgent
102
     */
103
    public function setUserAgent($userAgent)
104
    {
105
        $this->guzzle->setUserAgent($userAgent);
106
    }
107
108
    /**
109
     * Performs an HTTP request, returns the body response
110
     *
111
     * @param string $method The method
112
     * @param string $path The path to query
113
     * @param array $query An array of query parameters
114
     * @param array $postFields An array of post fields
115
     * @param array $files An array of post files
116
     * @param array $headers An array of request headers
117
     *
118
     * @return string The response body
119
     *
120
     * @throws BadResponseException
121
     * @throws RuntimeException
122
     */
123
    public function call(
124
        $method,
125
        $path,
126
        array $query = array(),
127
        array $postFields = array(),
128
        array $files = array(),
129
        array $headers = array()
130
    ) {
131
        try {
132
            $request = $this->guzzle->createRequest($method, $path, $headers);
133
            $this->addRequestParameters($request, $query, $postFields, $files);
134
            $response = $request->send();
135
        } catch (CurlException $e) {
136
            throw new RuntimeException($e->getMessage(), $e->getErrorNo(), $e);
137
        } catch (GuzzleBadResponse $e) {
138
            throw BadResponseException::fromGuzzleResponse($e);
139
        } catch (GuzzleException $e) {
140
            throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
141
        }
142
143
        return $response->getBody(true);
144
    }
145
146
    private function addRequestParameters(RequestInterface $request, $query, $postFields, $files)
147
    {
148
        foreach ($query as $name => $value) {
149
            $request->getQuery()->add($name, $value);
150
        }
151
152
        if ($request instanceof EntityEnclosingRequestInterface) {
153
            if ($request->getHeader('Content-Type') == 'application/json') {
154
                $request->getHeaders()->offsetUnset('Content-Type');
155
                $request->setBody(json_encode($postFields));
156
157
                return;
158
            }
159
160
            foreach ($postFields as $name => $value) {
161
                $request->getPostFields()->add($name, $value);
162
            }
163
            foreach ($files as $name => $filename) {
164
                $request->addPostFile($name, $filename);
165
            }
166
        } elseif (0 < count($postFields)) {
167
            throw new InvalidArgumentException('Can not add post fields to GET request');
168
        }
169
    }
170
}
171