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

Minify   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 8
Bugs 0 Features 2
Metric Value
wmc 7
c 8
b 0
f 2
lcom 1
cbo 6
dl 0
loc 53
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A forCache() 0 6 1
B __invoke() 0 19 6
1
<?php
2
3
namespace Psr7Middlewares\Middleware;
4
5
use Psr7Middlewares\Utils;
6
use Psr7Middlewares\Middleware;
7
use Psr\Http\Message\ServerRequestInterface;
8
use Psr\Http\Message\ResponseInterface;
9
use Psr7Middlewares\Transformers;
10
use RuntimeException;
11
12
class Minify
13
{
14
    use Utils\CacheTrait;
15
    use Utils\ResolverTrait;
16
17
    /**
18
     * @var bool Minify only cacheable responses
19
     */
20
    private $forCache = false;
21
22
    /**
23
     * Set forCache directive.
24
     *
25
     * @param bool $forCache
26
     *
27
     * @return self
28
     */
29
    public function forCache($forCache = true)
30
    {
31
        $this->forCache = $forCache;
32
33
        return $this;
34
    }
35
36
    /**
37
     * Execute the middleware.
38
     *
39
     * @param ServerRequestInterface $request
40
     * @param ResponseInterface      $response
41
     * @param callable               $next
42
     *
43
     * @return ResponseInterface
44
     */
45
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
46
    {
47
        if ($this->forCache && !self::isCacheable($request, $response)) {
48
            return $next($request, $response);
49
        }
50
51
        if (!Middleware::hasAttribute($request, FormatNegotiator::KEY)) {
52
            throw new RuntimeException('Minify middleware needs FormatNegotiator executed before');
53
        }
54
55
        $resolver = $this->resolver ?: new Transformers\Minifier();
56
        $transformer = $resolver->resolve(FormatNegotiator::getFormat($request));
57
58
        if ($transformer) {
59
            $response = $transformer($response);
60
        }
61
62
        return $next($request, $response);
63
    }
64
}
65