Completed
Push — travis ( f0ed02...4279e5 )
by Eric
192:27 queued 127:20
created

src/AbstractHttpAdapter.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 Ivory\HttpAdapter\Message\InternalRequestInterface;
15
use Ivory\HttpAdapter\Normalizer\HeadersNormalizer;
16
17
/**
18
 * Abstract http adapter.
19
 *
20
 * @author GeLo <[email protected]>
21
 */
22
abstract class AbstractHttpAdapter implements HttpAdapterInterface
23
{
24
    use HttpAdapterTrait;
25
26
    /** @var \Ivory\HttpAdapter\ConfigurationInterface */
27
    private $configuration;
28
29
    /**
30
     * Creates an http adapter.
31
     *
32
     * @param \Ivory\HttpAdapter\ConfigurationInterface|null $configuration The configuration.
33
     */
34
    public function __construct(ConfigurationInterface $configuration = null)
35
    {
36
        $this->setConfiguration($configuration ?: new Configuration());
37
    }
38
39
    /**
40
     * {@inheritdoc}
41
     */
42
    public function getConfiguration()
43
    {
44
        return $this->configuration;
45
    }
46
47
    /**
48
     * {@inheritdoc}
49
     */
50
    public function setConfiguration(ConfigurationInterface $configuration)
51
    {
52
        $this->configuration = $configuration;
53
    }
54
55
    /**
56
     * Prepares the headers.
57
     *
58
     * @param \Ivory\HttpAdapter\Message\InternalRequestInterface $internalRequest The internal request.
59
     * @param boolean                                             $associative     TRUE if the prepared headers should be associative else FALSE.
60
     * @param boolean                                             $contentType     TRUE if the content type header should be prepared else FALSE.
61
     * @param boolean                                             $contentLength   TRUE if the content length header should be prepared else FALSE.
62
     *
63
     * @return array The prepared headers.
64
     */
65
    protected function prepareHeaders(
66
        InternalRequestInterface &$internalRequest,
67
        $associative = true,
68
        $contentType = true,
69
        $contentLength = false
70
    ) {
71
        if (!$internalRequest->hasHeader('Connection')) {
72
            $internalRequest = $internalRequest->withHeader(
73
                'Connection',
74
                $this->configuration->getKeepAlive() ? 'keep-alive' : 'close'
75
            );
76
        }
77
78
        if (!$internalRequest->hasHeader('Content-Type')) {
79
            $rawDatas = (string) $internalRequest->getBody();
80
            $datas = $internalRequest->getDatas();
81
            $files = $internalRequest->getFiles();
82
83
            if ($this->configuration->hasEncodingType()) {
84
                $internalRequest = $internalRequest->withHeader(
85
                    'Content-Type',
86
                    $this->configuration->getEncodingType()
87
                );
88
            } elseif ($contentType && !empty($files)) {
89
                $internalRequest = $internalRequest->withHeader(
90
                    'Content-Type',
91
                    ConfigurationInterface::ENCODING_TYPE_FORMDATA.'; boundary='.$this->configuration->getBoundary()
92
                );
93
            } elseif ($contentType && (!empty($datas) || !empty($rawDatas))) {
94
                $internalRequest = $internalRequest->withHeader(
95
                    'Content-Type',
96
                    ConfigurationInterface::ENCODING_TYPE_URLENCODED
97
                );
98
            }
99
        }
100
101
        if ($contentLength && !$internalRequest->hasHeader('Content-Length')
102
            && ($length = strlen($this->prepareBody($internalRequest))) > 0) {
103
            $internalRequest = $internalRequest->withHeader('Content-Length', (string) $length);
104
        }
105
106
        if (!$internalRequest->hasHeader('User-Agent')) {
107
            $internalRequest = $internalRequest->withHeader('User-Agent', $this->configuration->getUserAgent());
108
        }
109
110
        return HeadersNormalizer::normalize($internalRequest->getHeaders(), $associative);
111
    }
112
113
    /**
114
     * Prepares the body.
115
     *
116
     * @param \Ivory\HttpAdapter\Message\InternalRequestInterface $internalRequest The internal request.
117
     *
118
     * @return string The prepared body.
119
     */
120
    protected function prepareBody(InternalRequestInterface $internalRequest)
121
    {
122
        $body = (string) $internalRequest->getBody();
123
124
        if (!empty($body)) {
125
            return $body;
126
        }
127
128
        $files = $internalRequest->getFiles();
129
130
        if (empty($files)) {
131
            return http_build_query($internalRequest->getDatas(), null, '&');
132
        }
133
134
        $body = '';
135
136
        foreach ($internalRequest->getDatas() as $name => $value) {
137
            $body .= $this->prepareRawBody($name, $value);
138
        }
139
140
        foreach ($internalRequest->getFiles() as $name => $file) {
141
            $body .= $this->prepareRawBody($name, $file, true);
142
        }
143
144
        $body .= '--'.$this->configuration->getBoundary().'--'."\r\n";
145
146
        return $body;
147
    }
148
149
    /**
150
     * Prepares the name.
151
     *
152
     * @param string $name    The name.
153
     * @param string $subName The sub name.
154
     *
155
     * @return string The prepared name.
156
     */
157
    protected function prepareName($name, $subName)
158
    {
159
        return $name.'['.$subName.']';
160
    }
161
162
    /**
163
     * Prepares the raw body.
164
     *
165
     * @param string       $name   The name.
166
     * @param array|string $data   The data.
167
     * @param boolean      $isFile TRUE if the data is a file path else FALSE.
168
     *
169
     * @return string The formatted raw body.
170
     */
171
    private function prepareRawBody($name, $data, $isFile = false)
172
    {
173 View Code Duplication
        if (is_array($data)) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
174
            $body = '';
175
176
            foreach ($data as $subName => $subData) {
177
                $body .= $this->prepareRawBody($this->prepareName($name, $subName), $subData, $isFile);
178
            }
179
180
            return $body;
181
        }
182
183
        $body = '--'.$this->configuration->getBoundary()."\r\n".'Content-Disposition: form-data; name="'.$name.'"';
184
185
        if ($isFile) {
186
            $body .= '; filename="'.basename($data).'"';
187
            $data = file_get_contents($data);
188
        }
189
190
        return $body."\r\n\r\n".$data."\r\n";
191
    }
192
}
193