Passed
Push — master ( ddbf8b...086098 )
by Robbie
11:17
created

UrlPathStartswith::checkRequestForBypass()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace SilverStripe\Control\Middleware\ConfirmationMiddleware;
4
5
use SilverStripe\Control\HTTPRequest;
6
use SilverStripe\Security\Confirmation;
7
8
/**
9
 * A rule to match beginning of URL
10
 */
11
class UrlPathStartswith implements Rule, Bypass
12
{
13
    use PathAware;
14
15
    /**
16
     * Initialize the rule with the path
17
     *
18
     * @param string $path
19
     */
20
    public function __construct($path)
21
    {
22
        $this->setPath($path);
23
    }
24
25
    /**
26
     * Generates the confirmation item
27
     *
28
     * @param string $token
29
     * @param string $url
30
     *
31
     * @return Confirmation\Item
32
     */
33
    protected function buildConfirmationItem($token, $url)
34
    {
35
        return new Confirmation\Item(
36
            $token,
37
            _t(__CLASS__.'.CONFIRMATION_NAME', 'URL begins with "{path}"', ['path' => $this->getPath()]),
38
            _t(__CLASS__.'.CONFIRMATION_DESCRIPTION', 'The complete URL is: "{url}"', ['url' => $url])
39
        );
40
    }
41
42
    /**
43
     * Generates the unique token depending on the path
44
     *
45
     * @param string $path URL path
46
     *
47
     * @return string
48
     */
49
    protected function generateToken($path)
50
    {
51
        return sprintf('%s::%s', static::class, $path);
52
    }
53
54
    /**
55
     * Checks the given path by the rules and
56
     * returns whether it should be protected
57
     *
58
     * @param string $path Path to be checked
59
     *
60
     * @return bool
61
     */
62
    protected function checkPath($path)
63
    {
64
        $targetPath = $this->getPath();
65
        return strncmp($this->normalisePath($path), $targetPath, strlen($targetPath)) === 0;
66
    }
67
68
    public function checkRequestForBypass(HTTPRequest $request)
69
    {
70
        return $this->checkPath($request->getURL());
71
    }
72
73
    public function getRequestConfirmationItem(HTTPRequest $request)
74
    {
75
        if (!$this->checkPath($request->getURL())) {
76
            return null;
77
        }
78
79
        $token = $this->generateToken($this->getPath());
80
81
        return $this->buildConfirmationItem($token, $request->getURL(true));
82
    }
83
}
84