Completed
Push — master ( b2e200...1332b8 )
by Oscar
04:48
created

SaveResponse::writeStream()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 22
rs 8.9197
cc 4
eloc 11
nc 6
nop 2
1
<?php
2
3
namespace Psr7Middlewares\Middleware;
4
5
use Psr7Middlewares\Utils;
6
use Psr\Http\Message\RequestInterface;
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\StreamInterface;
9
10
/**
11
 * Middleware to save the response into a file.
12
 */
13
class SaveResponse
14
{
15
    use Utils\CacheTrait;
16
    use Utils\FileTrait;
17
18
    /**
19
     * Execute the middleware.
20
     *
21
     * @param RequestInterface  $request
22
     * @param ResponseInterface $response
23
     * @param callable          $next
24
     *
25
     * @return ResponseInterface
26
     */
27
    public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next)
28
    {
29
        $response = $next($request, $response);
30
31
        if (
32
            $this->testBasePath($request->getUri()->getPath())
33
         && empty($request->getUri()->getQuery())
34
         && self::isCacheable($request, $response)
35
        ) {
36
            $path = $this->getFilename($request);
37
38
            //if it's gz compressed, append .gz
39
            if (strtolower($response->getHeaderLine('Content-Encoding')) === 'gzip') {
40
                $path .= '.gz';
41
            }
42
43
            self::writeStream($response->getBody(), $path);
44
        }
45
46
        return $response;
47
    }
48
49
    /**
50
     * Write the stream to the given path.
51
     *
52
     * @param StreamInterface $stream
53
     * @param string          $path
54
     */
55
    private static function writeStream(StreamInterface $stream, $path)
56
    {
57
        $dir = dirname($path);
58
59
        if (!is_dir($dir)) {
60
            mkdir($dir, 0777, true);
61
        }
62
63
        $handle = fopen($path, 'wb+');
64
65
        if (false === $handle) {
66
            throw new RuntimeException('Unable to write to designated path');
67
        }
68
69
        $stream->rewind();
70
71
        while (!$stream->eof()) {
72
            fwrite($handle, $stream->read(4096));
73
        }
74
75
        fclose($handle);
76
    }
77
}
78