Completed
Push — resource-url-generator ( 79ebbf )
by Sam
09:20
created

SimpleResourceURLGenerator::getNonceStyle()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace SilverStripe\Control;
4
5
use SilverStripe\Core\Manifest\ResourceURLGenerator;
6
7
/**
8
 * Generate URLs assuming that BASE_PATH is also the webroot
9
 * Standard SilverStripe 3 operation
10
 */
11
class SimpleResourceURLGenerator implements ResourceURLGenerator
12
{
13
    /*
14
     * @var string
15
     */
16
    private $nonceStyle;
17
18
    /*
19
     * Get the style of nonce-suffixes to use, or null if disabled
20
     *
21
     * @return string|null
22
     */
23
    public function getNonceStyle()
24
    {
25
        return $this->nonceStyle;
26
    }
27
28
    /*
29
     * Set the style of nonce-suffixes to use, or null to disable
30
     * Currently only "mtime" is allowed
31
     *
32
     * @param string|null $nonceStyle The style of nonces to apply, or null to disable
33
     */
34
    public function setNonceStyle($nonceStyle)
35
    {
36
        if ($nonceStyle && $nonceStyle !== 'mtime') {
0 ignored issues
show
Bug Best Practice introduced by
The expression $nonceStyle of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
37
            throw new InvalidArgumentException('The only allowed NonceStyle is mtime');
38
        }
39
        $this->nonceStyle = $nonceStyle;
40
    }
41
42
    /**
43
     * Return the URL for a resource, prefixing with Director::baseURL() and suffixing with a nonce
44
     *
45
     * @inherit
46
     */
47
    public function urlForResource($relativePath)
48
    {
49
        $absolutePath = preg_replace('/\?.*/', '', Director::baseFolder() . '/' . $relativePath);
50
51
        if (!file_exists($absolutePath)) {
52
            throw new InvalidArgumentException("File {$relativePath} does not exist");
53
        }
54
55
        $nonce = '';
56
        if ($this->nonceStyle) {
57
            $nonce = (strpos($relativePath, '?') === false) ? '?' : '&';
58
59
            switch ($this->nonceStyle) {
60
                case 'mtime':
61
                    $nonce .= "m=" . filemtime($absolutePath);
62
                    break;
63
            }
64
        }
65
66
        return Director::baseURL() . $relativePath . $nonce;
67
    }
68
}
69