Completed
Push — jquery-cdn ( 400c4e...bf2c1a )
by Doğa
02:48
created

Asset   A

Complexity

Total Complexity 25

Size/Duplication

Total Lines 134
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
dl 0
loc 134
rs 10
c 0
b 0
f 0
wmc 25
lcom 1
cbo 1

7 Methods

Rating   Name   Duplication   Size   Complexity  
A requireUrl() 0 4 1
A requirePath() 0 4 1
A register() 0 4 1
A enqueue() 0 4 1
B get() 0 28 6
C add() 0 58 13
A loadFromCdn() 0 7 2
1
<?php
2
3
namespace Flynt\Utils;
4
5
// TODO: add async & defer (see https://matthewhorne.me/defer-async-wordpress-scripts/); also add to cdn fallback
6
7
class Asset
8
{
9
    const DEFAULT_OPTIONS = [
10
        'dependencies' => [],
11
        'version' => null,
12
        'inFooter' => true,
13
        'media' => 'all',
14
        'cdn' => []
15
    ];
16
17
    protected static $assetManifest;
18
    protected static $loadFromCdn = false;
19
20
    public static function requireUrl($asset)
21
    {
22
        return self::get('url', $asset);
23
    }
24
25
    public static function requirePath($asset)
26
    {
27
        return self::get('path', $asset);
28
    }
29
30
    public static function register($options)
31
    {
32
        return self::add('register', $options);
33
    }
34
35
    public static function enqueue($options)
36
    {
37
        return self::add('enqueue', $options);
38
    }
39
40
    protected static function get($returnType, $asset)
41
    {
42
        $distPath = get_template_directory() . '/dist';
43
44
        if (!isset(self::$assetManifest)) {
45
            $manifestPath = $distPath . '/rev-manifest.json';
46
            if (is_file($manifestPath)) {
47
                self::$assetManifest = json_decode(file_get_contents($manifestPath), true);
48
            } else {
49
                self::$assetManifest = [];
50
            }
51
        }
52
53
        if (array_key_exists($asset, self::$assetManifest)) {
54
            $assetSuffix = self::$assetManifest[$asset];
55
        } else {
56
            $assetSuffix = $asset;
57
        }
58
59
        if ('path' == $returnType) {
60
            return $distPath . '/' . $assetSuffix;
61
        } else if ('url' == $returnType) {
62
            $distUrl = get_template_directory_uri() . '/dist';
63
            return $distUrl . '/' . $assetSuffix;
64
        }
65
66
        return false;
67
    }
68
69
    protected static function add($funcType, $options)
70
    {
71
        $options = array_merge(self::DEFAULT_OPTIONS, $options);
72
73
        if (!array_key_exists('name', $options)) {
74
            trigger_error('Cannot add asset: Name not provided!', E_USER_WARNING);
75
            return false;
76
        }
77
78
        if (!array_key_exists('path', $options)) {
79
            trigger_error('Cannot add asset: Path not provided!', E_USER_WARNING);
80
            return false;
81
        }
82
83
        $funcName = "wp_{$funcType}_{$options['type']}";
84
        $lastVar = $options['type'] === 'script' ? $options['inFooter'] : $options['media'];
85
86
        // allow external urls
87
        $path = $options['path'];
88
        if (!(StringHelpers::startsWith('http://', $path))
89
            && !(StringHelpers::startsWith('https://', $path))
90
            && !(StringHelpers::startsWith('//', $path))
91
        ) {
92
            $path = Asset::requireUrl($path);
93
        }
94
95
        // TODO: What if a script is registered twice?
96
        if (true === self::$loadFromCdn
97
            && !empty($options['cdn'])
98
            && !empty($options['cdn']['check'])
99
            && !empty($options['cdn']['url'])
100
        ) {
101
            $cdnCheck = $options['cdn']['check'];
102
            $localPath = $path;
103
            $path = $options['cdn']['url'];
104
        }
105
106
        if (function_exists($funcName)) {
107
            $funcName(
108
                $options['name'],
109
                $path,
110
                $options['dependencies'],
111
                $options['version'],
112
                $lastVar
113
            );
114
115
            if (isset($localPath)) {
116
                wp_add_inline_script(
117
                    $options['name'],
118
                    "${cdnCheck}||document.write(\"<script src=\\\"${localPath}\\\"><\/script>\")"
0 ignored issues
show
Bug introduced by
The variable $cdnCheck does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
119
                );
120
            }
121
122
            return true;
123
        }
124
125
        return false;
126
    }
127
128
    /**
129
     * Getter and setter for the loadFromCdn setting.
130
     *
131
     * @param boolean $load (optional) Value to set the parameter to.
132
     **/
133
    public static function loadFromCdn($load = null)
134
    {
135
        if (!isset($load)) {
136
            return self::$loadFromCdn;
137
        }
138
        self::$loadFromCdn = (bool) $load;
139
    }
140
}
141