Completed
Pull Request — master (#14)
by Márk
03:42
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 1
Metric Value
c 1
b 0
f 1
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
 * TODO: make class final in version 2.0, once plugins does not extend it anymore.
15
 */
16
/*final*/ class ContentLengthPlugin implements Plugin
17
{
18
    /**
19
     * {@inheritdoc}
20
     */
21 2
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
22
    {
23 2
        if (!$request->hasHeader('Content-Length')) {
24 2
            $stream = $request->getBody();
25
26
            // Cannot determine the size so we use a chunk stream
27 2
            if (null === $stream->getSize()) {
28 1
                $stream = new ChunkStream($stream);
29 1
                $request = $request->withBody($stream);
30 1
                $request = $request->withAddedHeader('Transfer-Encoding', 'chunked');
31 1
            } else {
32 1
                $request = $request->withHeader('Content-Length', $stream->getSize());
33
            }
34 2
        }
35
36 2
        return $next($request);
37
    }
38
}
39