Completed
Push — master ( 206c33...9e77c2 )
by Oscar
05:44
created

RedirectTrait   D

Complexity

Total Complexity 93

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 6
Bugs 1 Features 0
Metric Value
wmc 93
c 6
b 1
f 0
lcom 1
cbo 2
dl 0
loc 40
rs 4.8718

2 Methods

Rating   Name   Duplication   Size   Complexity  
A redirect() 0 10 2
A getRedirectResponse() 0 7 1

How to fix   Complexity   

Complex Class

Complex classes like RedirectTrait often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use RedirectTrait, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Psr7Middlewares\Utils;
4
5
use Psr7Middlewares\Middleware;
6
use Psr\Http\Message\ResponseInterface;
7
use Psr\Http\Message\UriInterface;
8
use InvalidArgumentException;
9
10
/**
11
 * Trait used by all middlewares with redirect() option.
12
 */
13
trait RedirectTrait
14
{
15
    /** 
16
     * @var int Redirect HTTP status code
17
     */
18
    protected $redirectStatus;
19
20
    /**
21
     * Set HTTP redirect status code.
22
     *
23
     * @param int $redirectStatus Redirect HTTP status code
24
     * 
25
     * @return self
26
     */
27
    public function redirect($redirectStatus = 302)
28
    {
29
        if (!in_array($redirectStatus, [301, 302], true)) {
30
            throw new InvalidArgumentException('The redirect status code must be 301 or 302');
31
        }
32
33
        $this->redirectStatus = $redirectStatus;
34
35
        return $this;
36
    }
37
38
    /**
39
     * Returns a redirect response.
40
     * 
41
     * @param int               $redirectStatus
42
     * @param UriInterface      $uri
43
     * @param ResponseInterface $response
44
     */
45
    protected static function getRedirectResponse($redirectStatus, UriInterface $uri, ResponseInterface $response)
46
    {
47
        return $response
48
            ->withStatus($redirectStatus)
49
            ->withHeader('Location', (string) $uri)
50
            ->withBody(Middleware::createStream());
51
    }
52
}
53