ReadResponse   A
last analyzed

Complexity

Total Complexity 15

Size/Duplication

Total Lines 112
Duplicated Lines 6.25 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
wmc 15
lcom 1
cbo 6
dl 7
loc 112
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A parseRangeHeader() 0 11 3
A continueOnError() 0 6 1
B range() 0 22 4
C __invoke() 7 31 7

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Psr7Middlewares\Middleware;
4
5
use Psr7Middlewares\Utils;
6
use Psr\Http\Message\ServerRequestInterface;
7
use Psr\Http\Message\ResponseInterface;
8
9
/**
10
 * Middleware to read the response.
11
 */
12
class ReadResponse
13
{
14
    use Utils\FileTrait;
15
    use Utils\StreamTrait;
16
17
    private $continueOnError = false;
18
19
    /**
20
     * Configure if continue to the next middleware if the response has not found.
21
     *
22
     * @param bool $continueOnError
23
     *
24
     * @return self
25
     */
26
    public function continueOnError($continueOnError = true)
27
    {
28
        $this->continueOnError = $continueOnError;
29
30
        return $this;
31
    }
32
33
    /**
34
     * Execute the middleware.
35
     *
36
     * @param ServerRequestInterface $request
37
     * @param ResponseInterface      $response
38
     * @param callable               $next
39
     *
40
     * @return ResponseInterface
41
     */
42
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
43
    {
44
        //If the method is not allowed
45 View Code Duplication
        if ($request->getMethod() !== 'GET') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
46
            if ($this->continueOnError) {
47
                return $next($request, $response);
48
            }
49
50
            return $response->withStatus(405);
51
        }
52
53
        $file = $this->getFilename($request);
54
55
        //If the file does not exists, check if is gzipped
56
        if (!is_file($file)) {
57
            $file .= '.gz';
58
59
            if (EncodingNegotiator::getEncoding($request) !== 'gzip' || !is_file($file)) {
60
                if ($this->continueOnError) {
61
                    return $next($request, $response);
62
                }
63
64
                return $response->withStatus(404);
65
            }
66
67
            $response = $response->withHeader('Content-Encoding', 'gzip');
68
        }
69
70
        //Handle range header
71
        return $this->range($request, $response->withBody(self::createStream($file, 'r')));
72
    }
73
74
    /**
75
     * Handle range requests.
76
     *
77
     * @param ServerRequestInterface $request
78
     * @param ResponseInterface      $response
79
     *
80
     * @return ResponseInterface
81
     */
82
    private static function range(ServerRequestInterface $request, ResponseInterface $response)
83
    {
84
        $response = $response->withHeader('Accept-Ranges', 'bytes');
85
86
        $range = $request->getHeaderLine('Range');
87
88
        if (empty($range) || !($range = self::parseRangeHeader($range))) {
89
            return $response;
90
        }
91
92
        list($first, $last) = $range;
93
        $size = $response->getBody()->getSize();
94
95
        if ($last === null) {
96
            $last = $size - 1;
97
        }
98
99
        return $response
100
            ->withStatus(206)
101
            ->withHeader('Content-Length', (string) ($last - $first + 1))
102
            ->withHeader('Content-Range', sprintf('bytes %d-%d/%d', $first, $last, $size));
103
    }
104
105
    /**
106
     * Parses a range header, for example: bytes=500-999.
107
     *
108
     * @param string $header
109
     *
110
     * @return false|array [first, last]
111
     */
112
    private static function parseRangeHeader($header)
113
    {
114
        if (preg_match('/bytes=(?P<first>\d+)-(?P<last>\d+)?/', $header, $matches)) {
115
            return [
116
                (int) $matches['first'],
117
                isset($matches['last']) ? (int) $matches['last'] : null,
118
            ];
119
        }
120
121
        return false;
122
    }
123
}
124