Passed
Push — develop ( 58391b...81b463 )
by Andrew
04:32
created

FileHelper::createUrl()   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 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Vite plugin for Craft CMS 3.x
4
 *
5
 * Allows the use of the Vite.js next generation frontend tooling with Craft CMS
6
 *
7
 * @link      https://nystudio107.com
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @copyright tag
Loading history...
8
 * @copyright Copyright (c) 2021 nystudio107
0 ignored issues
show
Coding Style introduced by
@copyright tag must contain a year and the name of the copyright holder
Loading history...
9
 */
0 ignored issues
show
Coding Style introduced by
PHP version not specified
Loading history...
Coding Style introduced by
Missing @category tag in file comment
Loading history...
Coding Style introduced by
Missing @package tag in file comment
Loading history...
Coding Style introduced by
Missing @author tag in file comment
Loading history...
Coding Style introduced by
Missing @license tag in file comment
Loading history...
10
11
namespace nystudio107\pluginvite\helpers;
12
13
use Craft;
14
use craft\helpers\UrlHelper;
15
16
use yii\caching\ChainedDependency;
17
use yii\caching\FileDependency;
18
use yii\caching\TagDependency;
19
20
use GuzzleHttp\Client;
21
use GuzzleHttp\RequestOptions;
22
23
use Throwable;
24
25
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
26
 * @author    nystudio107
0 ignored issues
show
Coding Style introduced by
Tag value for @author tag indented incorrectly; expected 2 spaces but found 4
Loading history...
Coding Style introduced by
Content of the @author tag must be in the form "Display Name <[email protected]>"
Loading history...
Coding Style introduced by
The tag in position 1 should be the @package tag
Loading history...
27
 * @package   Vite
0 ignored issues
show
Coding Style introduced by
Tag value for @package tag indented incorrectly; expected 1 spaces but found 3
Loading history...
28
 * @since     1.0.5
0 ignored issues
show
Coding Style introduced by
The tag in position 3 should be the @author tag
Loading history...
Coding Style introduced by
Tag value for @since tag indented incorrectly; expected 3 spaces but found 5
Loading history...
29
 */
0 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
30
class FileHelper
31
{
32
    // Constants
33
    // =========================================================================
34
35
    const CACHE_KEY = 'vite';
36
    const CACHE_TAG = 'vite';
37
38
    const DEVMODE_CACHE_DURATION = 30;
39
40
    const USER_AGENT_STRING = 'User-Agent:Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13';
41
42
    const SCRIPTS_DIR = '@vendor/nystudio107/craft-plugin-vite/src/web/assets/dist/';
43
44
    /**
45
     * Return the contents of a local file (via path) or remote file (via URL),
46
     * or null if the file doesn't exist or couldn't be fetched
47
     * Yii2 aliases and/or environment variables may be used
48
     *
49
     * @param string $pathOrUrl
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 8 spaces after parameter type; 1 found
Loading history...
50
     * @param callable|null $callback
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
51
     * @param string $cacheKeySuffix
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 8 spaces after parameter type; 1 found
Loading history...
52
     *
53
     * @return string|array|null
54
     */
55
    public static function fetch(string $pathOrUrl, callable $callback = null, string $cacheKeySuffix = '')
56
    {
57
        $pathOrUrl = (string)Craft::parseEnv($pathOrUrl);
58
        // Create the dependency tags
59
        $dependency = new TagDependency([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
60
            'tags' => [
61
                self::CACHE_TAG . $cacheKeySuffix,
62
                self::CACHE_TAG . $cacheKeySuffix . $pathOrUrl,
63
            ],
64
        ]);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
65
        // If this is a file path such as for the `manifest.json`, add a FileDependency so it's cache bust if the file changes
66
        if (!UrlHelper::isAbsoluteUrl($pathOrUrl)) {
67
            $dependency = new ChainedDependency([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
68
                'dependencies' => [
69
                    new FileDependency([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
70
                        'fileName' => $pathOrUrl
71
                    ]),
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
72
                    $dependency
73
                ]
74
            ]);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
75
        }
76
        // Set the cache duration based on devMode
77
        $cacheDuration = Craft::$app->getConfig()->getGeneral()->devMode
78
            ? self::DEVMODE_CACHE_DURATION
79
            : null;
80
        // Get the result from the cache, or parse the file
81
        $cache = Craft::$app->getCache();
82
        return $cache->getOrSet(
83
            self::CACHE_KEY . $cacheKeySuffix . $pathOrUrl,
84
            function () use ($pathOrUrl, $callback) {
85
                $contents = null;
86
                $result = null;
87
                if (UrlHelper::isAbsoluteUrl($pathOrUrl)) {
88
                    // See if we can connect to the server
89
                    $clientOptions = [
90
                        RequestOptions::HTTP_ERRORS => false,
91
                        RequestOptions::CONNECT_TIMEOUT => 3,
92
                        RequestOptions::VERIFY => false,
93
                        RequestOptions::TIMEOUT => 5,
94
                    ];
95
                    $client = new Client($clientOptions);
96
                    try {
97
                        $response = $client->request('GET', $pathOrUrl, [
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
98
                            RequestOptions::HEADERS => [
99
                                'User-Agent' => self::USER_AGENT_STRING,
100
                                'Accept' => '*/*',
101
                            ],
102
                        ]);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
103
                        if ($response->getStatusCode() === 200) {
104
                            $contents = $response->getBody()->getContents();
105
                        }
106
                    } catch (Throwable $e) {
107
                        Craft::error($e, __METHOD__);
108
                    }
109
                } else {
110
                    $contents = @file_get_contents($pathOrUrl);
111
                }
112
                if ($contents) {
113
                    $result = $contents;
114
                    if ($callback) {
115
                        $result = $callback($result);
116
                    }
117
                }
118
119
                return $result;
120
            },
121
            $cacheDuration,
122
            $dependency
123
        );
124
    }
125
126
    /**
127
     * Combine a path with a URL to create a URL
128
     *
129
     * @param string $url
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
130
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
131
     *
132
     * @return string
133
     */
134
    public static function createUrl(string $url, string $path): string
135
    {
136
        $url = (string)Craft::parseEnv($url);
137
        return rtrim($url, '/') . '/' . trim($path, '/');
138
    }
139
140
    /**
141
     * Fetch a script file
142
     *
143
     * @param string $name
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
144
     * @param string $cacheKeySuffix
0 ignored issues
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
Coding Style introduced by
Missing parameter comment
Loading history...
145
     * @return string
0 ignored issues
show
Coding Style introduced by
Tag @return cannot be grouped with parameter tags in a doc comment
Loading history...
146
     */
147
    public static function fetchScript(string $name, string $cacheKeySuffix = ''): string
148
    {
149
        $path = self::createUrl(self::SCRIPTS_DIR, $name);
150
151
        return self::fetch($path, null, $cacheKeySuffix) ?? '';
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::fetch($path... $cacheKeySuffix) ?? '' could return the type array which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
152
    }
153
}
154