Completed
Pull Request — master (#129)
by Eric
257:01 queued 192:06
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 35239
    public function __construct(ConfigurationInterface $configuration = null)
35
    {
36 35239
        $this->setConfiguration($configuration ?: new Configuration());
37 35239
    }
38
39
    /**
40
     * {@inheritdoc}
41
     */
42 33638
    public function getConfiguration()
43
    {
44 33638
        return $this->configuration;
45 1
    }
46
47
    /**
48
     * {@inheritdoc}
49
     */
50 35239
    public function setConfiguration(ConfigurationInterface $configuration)
51
    {
52 35239
        $this->configuration = $configuration;
53 35239
    }
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 33543
    protected function prepareHeaders(
66
        InternalRequestInterface &$internalRequest,
67
        $associative = true,
68
        $contentType = true,
69
        $contentLength = false
70
    ) {
71 33543
        if (!$internalRequest->hasHeader('Connection')) {
72 33543
            $internalRequest = $internalRequest->withHeader(
73 33543
                'Connection',
74 33543
                $this->configuration->getKeepAlive() ? 'keep-alive' : 'close'
75 31782
            );
76 31782
        }
77
78 33543
        if (!$internalRequest->hasHeader('Content-Type')) {
79 33543
            $rawDatas = (string) $internalRequest->getBody();
80 33543
            $datas = $internalRequest->getDatas();
81 33543
            $files = $internalRequest->getFiles();
82
83 33543
            if ($this->configuration->hasEncodingType()) {
84
                $internalRequest = $internalRequest->withHeader(
85
                    'Content-Type',
86
                    $this->configuration->getEncodingType()
87
                );
88 33543
            } elseif ($contentType && !empty($files)) {
89 3820
                $internalRequest = $internalRequest->withHeader(
90 3820
                    'Content-Type',
91 3820
                    ConfigurationInterface::ENCODING_TYPE_FORMDATA.'; boundary='.$this->configuration->getBoundary()
92 3620
                );
93 33343
            } elseif ($contentType && (!empty($datas) || !empty($rawDatas))) {
94 6876
                $internalRequest = $internalRequest->withHeader(
95 6876
                    'Content-Type',
96 360
                    ConfigurationInterface::ENCODING_TYPE_URLENCODED
97 6516
                );
98 6516
            }
99 31782
        }
100
101 33543
        if ($contentLength && !$internalRequest->hasHeader('Content-Length')
102 33543
            && ($length = strlen($this->prepareBody($internalRequest))) > 0) {
103 1064
            $internalRequest = $internalRequest->withHeader('Content-Length', (string) $length);
104 1008
        }
105
106 33543
        if (!$internalRequest->hasHeader('User-Agent')) {
107 33543
            $internalRequest = $internalRequest->withHeader('User-Agent', $this->configuration->getUserAgent());
108 31782
        }
109
110 33543
        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 32315
    protected function prepareBody(InternalRequestInterface $internalRequest)
121
    {
122 32315
        $body = (string) $internalRequest->getBody();
123
124 32315
        if (!empty($body)) {
125 2800
            return $body;
126
        }
127
128 30315
        $files = $internalRequest->getFiles();
129
130 30315
        if (empty($files)) {
131 27075
            return http_build_query($internalRequest->getDatas(), null, '&');
132
        }
133
134 3240
        $body = '';
135
136 3240
        foreach ($internalRequest->getDatas() as $name => $value) {
137 3240
            $body .= $this->prepareRawBody($name, $value);
138 3070
        }
139
140 3240
        foreach ($internalRequest->getFiles() as $name => $file) {
141 3240
            $body .= $this->prepareRawBody($name, $file, true);
142 3070
        }
143
144 3240
        $body .= '--'.$this->configuration->getBoundary().'--'."\r\n";
145
146 3240
        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 4000
    protected function prepareName($name, $subName)
158
    {
159 4000
        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 3240
    private function prepareRawBody($name, $data, $isFile = false)
172
    {
173 3240 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 3240
            $body = '';
175
176 3240
            foreach ($data as $subName => $subData) {
177 3240
                $body .= $this->prepareRawBody($this->prepareName($name, $subName), $subData, $isFile);
178 3070
            }
179
180 3240
            return $body;
181
        }
182
183 3240
        $body = '--'.$this->configuration->getBoundary()."\r\n".'Content-Disposition: form-data; name="'.$name.'"';
184
185 3240
        if ($isFile) {
186 3240
            $body .= '; filename="'.basename($data).'"';
187 3240
            $data = file_get_contents($data);
188 3070
        }
189
190 3240
        return $body."\r\n\r\n".$data."\r\n";
191
    }
192
}
193