Completed
Push — master ( e37e46...c75450 )
by David
01:07
created

src/Plugin/DecoderPlugin.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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