DecoderPlugin::handleRequest()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 10
cts 10
cp 1
rs 9.7998
c 0
b 0
f 0
cc 3
nc 4
nop 3
crap 3
1
<?php
2
3
namespace Http\Client\Plugin;
4
5 1
@trigger_error('The '.__NAMESPACE__.'\DecoderPlugin class is deprecated since version 1.1 and will be removed in 2.0. Use Http\Client\Common\Plugin\DecoderPlugin instead.', E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
6
7
use Http\Message\Encoding\DechunkStream;
8
use Http\Message\Encoding\DecompressStream;
9
use Http\Message\Encoding\GzipDecodeStream;
10
use Http\Message\Encoding\InflateStream;
11
use Psr\Http\Message\RequestInterface;
12
use Psr\Http\Message\ResponseInterface;
13
use Psr\Http\Message\StreamInterface;
14
use Symfony\Component\OptionsResolver\OptionsResolver;
15
16
/**
17
 * Allow to decode response body with a chunk, deflate, compress or gzip encoding.
18
 *
19
 * If zlib is not installed, only chunked encoding can be handled.
20
 *
21
 * If Content-Encoding is not disabled, the plugin will add an Accept-Encoding header for the encoding methods it supports.
22
 *
23
 * @author Joel Wurtz <[email protected]>
24
 *
25
 * @deprecated since since version 1.1, and will be removed in 2.0. Use {@link \Http\Client\Common\Plugin\DecoderPlugin} instead.
26
 */
27
class DecoderPlugin implements Plugin
0 ignored issues
show
Deprecated Code introduced by
The interface Http\Client\Plugin\Plugin has been deprecated with message: since since version 1.1, and will be removed in 2.0. Use {@link \Http\Client\Common\Plugin} instead.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
28
{
29
    /**
30
     * @var bool Whether this plugin decode stream with value in the Content-Encoding header (default to true).
31
     *
32
     * If set to false only the Transfer-Encoding header will be used.
33
     */
34
    private $useContentEncoding;
35
36
    /**
37
     * @param array $config {
38
     *
39
     *    @var bool $use_content_encoding Whether this plugin should look at the Content-Encoding header first or only at the Transfer-Encoding (defaults to true).
40
     * }
41
     */
42 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...
43
    {
44 7
        $resolver = new OptionsResolver();
45 7
        $resolver->setDefaults([
46 7
            'use_content_encoding' => true,
47 7
        ]);
48 7
        $resolver->setAllowedTypes('use_content_encoding', 'bool');
49 7
        $options = $resolver->resolve($config);
50
51 7
        $this->useContentEncoding = $options['use_content_encoding'];
52 7
    }
53
54
    /**
55
     * {@inheritdoc}
56
     */
57 5
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
58
    {
59 5
        $encodings = extension_loaded('zlib') ? ['gzip', 'deflate', 'compress'] : ['identity'];
60
61 5
        if ($this->useContentEncoding) {
62 4
            $request = $request->withHeader('Accept-Encoding', $encodings);
63 4
        }
64 5
        $encodings[] = 'chunked';
65 5
        $request = $request->withHeader('TE', $encodings);
66
67 5
        return $next($request)->then(function (ResponseInterface $response) {
68 5
            return $this->decodeResponse($response);
69 5
        });
70
    }
71
72
    /**
73
     * Decode a response body given its Transfer-Encoding or Content-Encoding value.
74
     *
75
     * @param ResponseInterface $response Response to decode
76
     *
77
     * @return ResponseInterface New response decoded
78
     */
79 5
    private function decodeResponse(ResponseInterface $response)
80
    {
81 5
        $response = $this->decodeOnEncodingHeader('Transfer-Encoding', $response);
82
83 5
        if ($this->useContentEncoding) {
84 4
            $response = $this->decodeOnEncodingHeader('Content-Encoding', $response);
85 4
        }
86
87 5
        return $response;
88
    }
89
90
    /**
91
     * Decode a response on a specific header (content encoding or transfer encoding mainly).
92
     *
93
     * @param string            $headerName Name of the header
94
     * @param ResponseInterface $response   Response
95
     *
96
     * @return ResponseInterface A new instance of the response decoded
97
     */
98 5
    private function decodeOnEncodingHeader($headerName, ResponseInterface $response)
99
    {
100 5
        if ($response->hasHeader($headerName)) {
101 4
            $encodings = $response->getHeader($headerName);
102 4
            $newEncodings = [];
103
104 4
            while ($encoding = array_pop($encodings)) {
105 4
                $stream = $this->decorateStream($encoding, $response->getBody());
106
107 4
                if (false === $stream) {
108
                    array_unshift($newEncodings, $encoding);
109
110
                    continue;
111
                }
112
113 4
                $response = $response->withBody($stream);
114 4
            }
115
116 4
            $response = $response->withHeader($headerName, $newEncodings);
117 4
        }
118
119 5
        return $response;
120
    }
121
122
    /**
123
     * Decorate a stream given an encoding.
124
     *
125
     * @param string          $encoding
126
     * @param StreamInterface $stream
127
     *
128
     * @return StreamInterface|false A new stream interface or false if encoding is not supported
129
     */
130 4
    private function decorateStream($encoding, StreamInterface $stream)
131
    {
132 4
        if ('chunked' == strtolower($encoding)) {
133 1
            return new DechunkStream($stream);
134
        }
135
136 3
        if ('compress' == strtolower($encoding)) {
137 1
            return new DecompressStream($stream);
138
        }
139
140 2
        if ('deflate' == strtolower($encoding)) {
141 1
            return new InflateStream($stream);
142
        }
143
144 1
        if ('gzip' == strtolower($encoding)) {
145 1
            return new GzipDecodeStream($stream);
146
        }
147
148
        return false;
149
    }
150
}
151