PageRedirectionTrait::manageRedirection()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 12
nc 5
nop 0
dl 0
loc 19
ccs 0
cts 13
cp 0
crap 20
rs 9.8666
c 0
b 0
f 0
1
<?php
2
3
namespace PiedWeb\CMSBundle\Entity;
4
5
trait PageRedirectionTrait
6
{
7
    protected $redirectionUrl;
8
    protected $redirectionCode;
9
10
    abstract public function getMainContent(): ?string;
11
12
    /**
13
     * Check if a content don't start by 'Location: http://valid-url.tld/eg'.
14
     */
15
    protected function manageRedirection()
16
    {
17
        $content = $this->getMainContent();
18
        $code = 301; // default symfony is 302...
19
        if ('Location:' == substr($content, 0, 9)) {
20
            $url = trim(substr($content, 9));
21
            if (preg_match('/ [1-5][0-9]{2}$/', $url, $match)) {
22
                $code = (int) (trim($match[0]));
23
                $url = preg_replace('/ [1-5][0-9]{2}$/', '', $url);
24
            }
25
            if (filter_var($url, FILTER_VALIDATE_URL)) {
26
                $this->redirectionUrl = $url;
27
                $this->redirectionCode = $code;
28
29
                return $url;
30
            }
31
        }
32
33
        $this->redirectionUrl = false;
34
    }
35
36
    public function getRedirection()
37
    {
38
        if (null === $this->redirectionUrl) {
39
            $this->manageRedirection();
40
        }
41
42
        return $this->redirectionUrl;
43
    }
44
45
    public function getRedirectionCode()
46
    {
47
        if (null === $this->redirectionUrl) {
48
            $this->manageRedirection();
49
        }
50
51
        return $this->redirectionCode;
52
    }
53
}
54