Completed
Push — 8.2 ( 737f16...22bfc7 )
by David
17:32
created

CacheRouter::process()   C

Complexity

Conditions 10
Paths 16

Size

Total Lines 67
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 67
rs 6.1506
c 0
b 0
f 0
cc 10
eloc 41
nc 16
nop 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Mouf\Mvc\Splash\Routers;
4
5
use Interop\Http\ServerMiddleware\DelegateInterface;
6
use Interop\Http\ServerMiddleware\MiddlewareInterface;
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Mouf\Utils\Cache\CacheInterface;
10
use Psr\Log\LoggerInterface;
11
use Mouf\Utils\Common\ConditionInterface\ConditionInterface;
12
13
class CacheRouter implements MiddlewareInterface
14
{
15
    /**
16
     * @var CacheInterface
17
     */
18
    private $cache;
19
20
    /**
21
     * @var ConditionInterface
22
     */
23
    private $cacheCondition;
24
25
    /**
26
     * @var LoggerInterface
27
     */
28
    private $log;
29
30
    public function __construct(CacheInterface $cache, LoggerInterface $log, ConditionInterface $cacheCondition)
31
    {
32
        $this->cache = $cache;
33
        $this->cacheCondition = $cacheCondition;
34
        $this->log = $log;
35
    }
36
37
    /**
38
     * Process an incoming server request and return a response, optionally delegating
39
     * to the next middleware component to create the response.
40
     *
41
     * @param ServerRequestInterface $request
42
     * @param DelegateInterface $delegate
43
     *
44
     * @return ResponseInterface
45
     */
46
    public function process(ServerRequestInterface $request, DelegateInterface $delegate)
47
    {
48
        $requestMethod = $request->getMethod();
49
        $key = str_replace(['\\', '/', ':', '*', '?', '"', '<', '>', '|'], '_', $request->getUri()->getPath().'?'.$request->getUri()->getQuery());
50
51
        if ($this->cacheCondition->isOk() && $requestMethod == 'GET') {
52
            $cacheResponse = $this->cache->get($key);
53
            if ($cacheResponse) {
54
                $this->log->debug("Cache HIT on $key");
55
56
                return $cacheResponse;
57
            } else {
58
                $this->log->debug("Cache MISS on key $key");
59
                $response = $delegate->process($request);
60
61
                $noCache = false;
62
                if ($response->hasHeader('Mouf-Cache-Control') && $response->getHeader('Mouf-Cache-Control')[0] == 'no-cache') {
63
                    $noCache = true;
64
                }
65
66
                if ($noCache) {
67
                    $this->log->debug("Mouf NO CACHE header found, not storing '$key'");
68
                } else {
69
                    $ttl = null;
70
71
                    // TODO: continue here!
72
                    // Use PSR-7 response to analyze maxage and expires...
73
                    // ...or... use a completely different HTTP cache implementation!!!
74
                    // There must be one around for PSR-7!
75
76
                    $maxAge = $response->getMaxAge();
0 ignored issues
show
Bug introduced by
The method getMaxAge() does not seem to exist on object<Psr\Http\Message\ResponseInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
77
                    $expires = $response->getExpires();
0 ignored issues
show
Bug introduced by
The method getExpires() does not seem to exist on object<Psr\Http\Message\ResponseInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
78
                    if ($maxAge) {
79
                        $this->log->debug("MaxAge specified : $maxAge");
80
                        $ttl = $maxAge;
81
                    } elseif ($expires) {
82
                        $this->log->debug("Expires specified : $expires");
83
                        $ttl = date_diff($expires, new \DateTime())->s;
84
                    }
85
86
                    if ($ttl) {
87
                        $this->log->debug("TTL is  : $ttl");
88
                    }
89
90
                    // Make sure the response is serializable
91
                    $serializableResponse = new Response();
0 ignored issues
show
Bug Compatibility introduced by
The expression new \Mouf\Mvc\Splash\Routers\Response(); of type Mouf\Mvc\Splash\Routers\Response adds the type Mouf\Mvc\Splash\Routers\Response to the return on line 105 which is incompatible with the return type declared by the interface Interop\Http\ServerMiddl...ewareInterface::process of type Psr\Http\Message\ResponseInterface.
Loading history...
92
                    $serializableResponse->headers = $response->headers;
0 ignored issues
show
Bug introduced by
Accessing headers on the interface Psr\Http\Message\ResponseInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
93
94
                    ob_start();
95
                    $response->sendContent();
0 ignored issues
show
Bug introduced by
The method sendContent() does not seem to exist on object<Psr\Http\Message\ResponseInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
96
                    $content = ob_get_clean();
97
98
                    $serializableResponse->setContent($content);
99
100
                    $this->cache->set($key, $serializableResponse, $ttl);
101
                    $this->log->debug("Cache STORED on key $key");
102
                    $response = $serializableResponse;
103
                }
104
105
                return $response;
106
            }
107
        } else {
108
            $this->log->debug("No cache for $key");
109
110
            return $this->fallBackRouter->handle($request, $type, $catch);
0 ignored issues
show
Bug introduced by
The property fallBackRouter does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
Bug introduced by
The variable $type does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $catch does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
111
        }
112
    }
113
}
114