Completed
Pull Request — master (#14)
by Márk
03:38
created

ContentLengthPlugin::handleRequest()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 17
ccs 11
cts 11
cp 1
rs 9.4285
cc 3
eloc 10
nc 3
nop 3
crap 3
1
<?php
2
3
namespace Http\Client\Common\Plugin;
4
5
use Http\Client\Common\Plugin;
6
use Http\Message\Encoding\ChunkStream;
7
use Psr\Http\Message\RequestInterface;
8
9
/**
10
 * Allow to set the correct content length header on the request or to transfer it as a chunk if not possible.
11
 *
12
 * @author Joel Wurtz <[email protected]>
13
 */
14
final class ContentLengthPlugin implements Plugin
15
{
16
    /**
17
     * {@inheritdoc}
18
     */
19 2
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
20
    {
21 2
        if (!$request->hasHeader('Content-Length')) {
22 2
            $stream = $request->getBody();
23
24
            // Cannot determine the size so we use a chunk stream
25 2
            if (null === $stream->getSize()) {
26 1
                $stream = new ChunkStream($stream);
27 1
                $request = $request->withBody($stream);
28 1
                $request = $request->withAddedHeader('Transfer-Encoding', 'chunked');
29 1
            } else {
30 1
                $request = $request->withHeader('Content-Length', $stream->getSize());
31
            }
32 2
        }
33
34 2
        return $next($request);
35
    }
36
}
37