Completed
Pull Request — master (#14)
by Márk
06:15
created

ContentLengthPlugin   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 23
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 3
Bugs 0 Features 2
Metric Value
wmc 3
c 3
b 0
f 2
lcom 0
cbo 3
dl 0
loc 23
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A handleRequest() 0 17 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
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
20
    {
21
        if (!$request->hasHeader('Content-Length')) {
22
            $stream = $request->getBody();
23
24
            // Cannot determine the size so we use a chunk stream
25
            if (null === $stream->getSize()) {
26
                $stream = new ChunkStream($stream);
27
                $request = $request->withBody($stream);
28
                $request = $request->withAddedHeader('Transfer-Encoding', 'chunked');
29
            } else {
30
                $request = $request->withHeader('Content-Length', $stream->getSize());
31
            }
32
        }
33
34
        return $next($request);
35
    }
36
}
37