Completed
Push — travis ( f94b47...369e8a )
by Eric
02:24
created

src/Guzzle3HttpAdapter.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
/*
4
 * This file is part of the Ivory Http Adapter package.
5
 *
6
 * (c) Eric GELOEN <[email protected]>
7
 *
8
 * For the full copyright and license information, please read the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Ivory\HttpAdapter;
13
14
use Guzzle\Common\Event;
15
use Guzzle\Http\Client;
16
use Guzzle\Http\ClientInterface;
17
use Guzzle\Http\Exception\RequestException;
18
use Ivory\HttpAdapter\Message\InternalRequestInterface;
19
use Ivory\HttpAdapter\Normalizer\BodyNormalizer;
20
21
/**
22
 * Guzzle 3 http adapter.
23
 *
24
 * @author GeLo <[email protected]>
25
 */
26
class Guzzle3HttpAdapter extends AbstractCurlHttpAdapter
27
{
28
    /** @var \Guzzle\Http\ClientInterface */
29
    private $client;
30
31
    /**
32
     * Creates a guzzle 3 http adapter.
33
     *
34
     * @param \Guzzle\Http\ClientInterface|null              $client        The guzzle 3 client.
35
     * @param \Ivory\HttpAdapter\ConfigurationInterface|null $configuration The configuration.
36
     */
37
    public function __construct(ClientInterface $client = null, ConfigurationInterface $configuration = null)
38
    {
39
        parent::__construct($configuration);
40
41
        $this->client = $client ?: new Client();
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47
    public function getName()
48
    {
49
        return 'guzzle3';
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55
    protected function sendInternalRequest(InternalRequestInterface $internalRequest)
56
    {
57
        try {
58
            $response = $this->createRequest($internalRequest)->send();
59
        } catch (RequestException $e) {
60
            throw HttpAdapterException::cannotFetchUri(
61
                $e->getRequest()->getUrl(),
62
                $this->getName(),
63
                $e->getMessage()
64
            );
65
        }
66
67
        return $this->getConfiguration()->getMessageFactory()->createResponse(
68
            $response->getStatusCode(),
69
            $response->getProtocolVersion(),
70
            $response->getHeaders()->toArray(),
71
            BodyNormalizer::normalize(
72
                function () use ($response) {
73
                    $resource = $response->getBody()->getStream();
74
                    $response->getBody()->detachStream();
75
76
                    return $resource;
77
                },
78
                $internalRequest->getMethod()
79
            )
80
        );
81
    }
82
83
    /**
84
     * {@inheritdoc}
85
     */
86
    protected function sendInternalRequests(array $internalRequests, $success, $error)
87
    {
88
        $requests = array();
89
        foreach ($internalRequests as $internalRequest) {
90
            $requests[] = $this->createRequest($internalRequest, $success, $error);
91
        }
92
93
        try {
94
            $this->client->send($requests);
95
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
96
        }
97
    }
98
99
    /**
100
     * {@inheritdoc}
101
     */
102
    protected function createFile($file)
103
    {
104
        return '@'.$file;
105
    }
106
107
    /**
108
     * Creates a request.
109
     *
110
     * @param \Ivory\HttpAdapter\Message\InternalRequestInterface $internalRequest The internal request.
111
     * @param callable|null                                       $success         The success callable.
112
     * @param callable|null                                       $error           The error callable.
113
     *
114
     * @return \Ivory\HttpAdapter\Message\RequestInterface The request.
115
     */
116
    private function createRequest(InternalRequestInterface $internalRequest, $success = null, $error = null)
117
    {
118
        $request = $this->client->createRequest(
119
            $internalRequest->getMethod(),
120
            (string) $internalRequest->getUri(),
121
            $this->prepareHeaders($internalRequest),
122
            $this->prepareContent($internalRequest),
123
            array(
124
                'exceptions'      => false,
125
                'allow_redirects' => false,
126
                'timeout'         => $this->getConfiguration()->getTimeout(),
127
                'connect_timeout' => $this->getConfiguration()->getTimeout(),
128
            )
129
        );
130
131
        $request->setProtocolVersion($internalRequest->getProtocolVersion());
132
133
        if (is_callable($success)) {
134
            $messageFactory = $this->getConfiguration()->getMessageFactory();
135
136
            $request->getEventDispatcher()->addListener(
137
                'request.success',
138
                function (Event $event) use ($messageFactory, $success, $internalRequest) {
139
                    $response = $messageFactory->createResponse(
140
                        $event['response']->getStatusCode(),
141
                        $event['response']->getProtocolVersion(),
142
                        $event['response']->getHeaders()->toArray(),
143
                        BodyNormalizer::normalize(
144
                            function () use ($event) {
145
                                $resource = $event['response']->getBody()->getStream();
146
                                $event['response']->getBody()->detachStream();
147
148
                                return $resource;
149
                            },
150
                            $internalRequest->getMethod()
151
                        )
152
                    );
153
154
                    $response = $response->withParameter('request', $internalRequest);
155
                    call_user_func($success, $response);
156
                }
157
            );
158
        }
159
160
        if (is_callable($error)) {
161
            $httpAdapterName = $this->getName();
162
163
            $request->getEventDispatcher()->addListener(
164
                'request.exception',
165
                function (Event $event) use ($error, $internalRequest, $httpAdapterName) {
166
                    $exception = HttpAdapterException::cannotFetchUri(
167
                        $event['exception']->getRequest()->getUrl(),
168
                        $httpAdapterName,
169
                        $event['exception']->getMessage()
170
                    );
171
172
                    $exception->setRequest($internalRequest);
173
                    call_user_func($error, $exception);
174
                }
175
            );
176
        }
177
178
        return $request;
179
    }
180
}
181