Completed
Push — master ( 743104...baefb0 )
by Joel
05:56
created

DecoderPlugin::decodeOnEncodingHeader()   B

Complexity

Conditions 4
Paths 2

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4.0466

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 23
ccs 12
cts 14
cp 0.8571
rs 8.7972
cc 4
eloc 12
nc 2
nop 2
crap 4.0466
1
<?php
2
3
namespace Http\Client\Plugin;
4
5
use Http\Message\Encoding\DechunkStream;
6
use Http\Message\Encoding\DecompressStream;
7
use Http\Message\Encoding\GzipDecodeStream;
8
use Http\Message\Encoding\InflateStream;
9
use Psr\Http\Message\RequestInterface;
10
use Psr\Http\Message\ResponseInterface;
11
use Psr\Http\Message\StreamInterface;
12
use Symfony\Component\OptionsResolver\OptionsResolver;
13
14
/**
15
 * Allow to decode response body with a chunk, deflate, compress or gzip encoding.
16
 *
17
 * If zlib is not installed, only chunked encoding can be handled.
18
 *
19
 * If Content-Encoding is not disabled, the plugin will add an Accept-Encoding header for the encoding methods it supports.
20
 *
21
 * @author Joel Wurtz <[email protected]>
22
 */
23
class DecoderPlugin implements Plugin
24
{
25
    /**
26
     * @var bool Whether this plugin decode stream with value in the Content-Encoding header (default to true).
27
     *
28
     * If set to false only the Transfer-Encoding header will be used.
29
     */
30
    private $useContentEncoding;
31
32
    /**
33
     * Available options for $config are:
34
     *  - use_content_encoding: Whether this plugin should look at the Content-Encoding header first or only at the Transfer-Encoding (defaults to true).
35
     *
36
     * @param array $config
37
     */
38 7 View Code Duplication
    public function __construct(array $config = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
39
    {
40 7
        $resolver = new OptionsResolver();
41 7
        $resolver->setDefaults([
42 7
            'use_content_encoding' => true,
43 7
        ]);
44 7
        $resolver->setAllowedTypes('use_content_encoding', 'bool');
45 7
        $options = $resolver->resolve($config);
46
47 7
        $this->useContentEncoding = $options['use_content_encoding'];
48 7
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53 5
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
54
    {
55 5
        $encodings = extension_loaded('zlib') ? ['gzip', 'deflate', 'compress'] : [];
56
57 5
        if ($this->useContentEncoding && count($encodings)) {
58 4
            $request = $request->withHeader('Accept-Encoding', $encodings);
59 4
        }
60 5
        $encodings[] = 'chunked';
61 5
        $request = $request->withHeader('TE', $encodings);
62
63 5
        return $next($request)->then(function (ResponseInterface $response) {
64 5
            return $this->decodeResponse($response);
65 5
        });
66
    }
67
68
    /**
69
     * Decode a response body given its Transfer-Encoding or Content-Encoding value.
70
     *
71
     * @param ResponseInterface $response Response to decode
72
     *
73
     * @return ResponseInterface New response decoded
74
     */
75 5
    private function decodeResponse(ResponseInterface $response)
76
    {
77 5
        $response = $this->decodeOnEncodingHeader('Transfer-Encoding', $response);
78
79 5
        if ($this->useContentEncoding) {
80 4
            $response = $this->decodeOnEncodingHeader('Content-Encoding', $response);
81 4
        }
82
83 5
        return $response;
84
    }
85
86
    /**
87
     * Decode a response on a specific header (content encoding or transfer encoding mainly).
88
     *
89
     * @param string            $headerName Name of the header
90
     * @param ResponseInterface $response   Response
91
     *
92
     * @return ResponseInterface A new instance of the response decoded
93
     */
94 5
    private function decodeOnEncodingHeader($headerName, ResponseInterface $response)
95
    {
96 5
        if ($response->hasHeader($headerName)) {
97 4
            $encodings = $response->getHeader($headerName);
98 4
            $newEncodings = [];
99
100 4
            while ($encoding = array_pop($encodings)) {
101 4
                $stream = $this->decorateStream($encoding, $response->getBody());
102
103 4
                if (false === $stream) {
104
                    array_unshift($newEncodings, $encoding);
105
106
                    continue;
107
                }
108
109 4
                $response = $response->withBody($stream);
110 4
            }
111
112 4
            $response = $response->withHeader($headerName, $newEncodings);
113 4
        }
114
115 5
        return $response;
116
    }
117
118
    /**
119
     * Decorate a stream given an encoding.
120
     *
121
     * @param string          $encoding
122
     * @param StreamInterface $stream
123
     *
124
     * @return StreamInterface|false A new stream interface or false if encoding is not supported
125
     */
126 4
    private function decorateStream($encoding, StreamInterface $stream)
127
    {
128 4
        if (strtolower($encoding) == 'chunked') {
129 1
            return new DechunkStream($stream);
130
        }
131
132 3
        if (strtolower($encoding) == 'compress') {
133 1
            return new DecompressStream($stream);
134
        }
135
136 2
        if (strtolower($encoding) == 'deflate') {
137 1
            return new InflateStream($stream);
138
        }
139
140 1
        if (strtolower($encoding) == 'gzip') {
141 1
            return new GzipDecodeStream($stream);
142
        }
143
144
        return false;
145
    }
146
}
147