Passed
Branch v1 (36925c)
by Andrew
06:46
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 SCRIPTS_DIR = '@vendor/nystudio107/craft-plugin-vite/src/web/assets/dist/';
41
42
    /**
43
     * Return the contents of a local file (via path) or remote file (via URL),
44
     * or null if the file doesn't exist or couldn't be fetched
45
     * Yii2 aliases and/or environment variables may be used
46
     *
47
     * @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...
48
     * @param callable|null $callback
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
49
     * @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...
50
     *
51
     * @return string|array|null
52
     */
53
    public static function fetch(string $pathOrUrl, callable $callback = null, string $cacheKeySuffix = '')
54
    {
55
        $pathOrUrl = (string)Craft::parseEnv($pathOrUrl);
56
        // Create the dependency tags
57
        $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...
58
            'tags' => [
59
                self::CACHE_TAG . $cacheKeySuffix,
60
                self::CACHE_TAG . $cacheKeySuffix . $pathOrUrl,
61
            ],
62
        ]);
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...
63
        // If this is a file path such as for the `manifest.json`, add a FileDependency so it's cache bust if the file changes
64
        if (!UrlHelper::isAbsoluteUrl($pathOrUrl)) {
65
            $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...
66
                'dependencies' => [
67
                    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...
68
                        'fileName' => $pathOrUrl
69
                    ]),
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...
70
                    $dependency
71
                ]
72
            ]);
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...
73
        }
74
        // Set the cache duration based on devMode
75
        $cacheDuration = Craft::$app->getConfig()->getGeneral()->devMode
76
            ? self::DEVMODE_CACHE_DURATION
77
            : null;
78
        // Get the result from the cache, or parse the file
79
        $cache = Craft::$app->getCache();
80
        return $cache->getOrSet(
81
            self::CACHE_KEY . $cacheKeySuffix . $pathOrUrl,
82
            function () use ($pathOrUrl, $callback) {
83
                $contents = null;
84
                $result = null;
85
                if (UrlHelper::isAbsoluteUrl($pathOrUrl)) {
86
                    // See if we can connect to the server
87
                    $clientOptions = [
88
                        RequestOptions::HTTP_ERRORS => false,
89
                        RequestOptions::CONNECT_TIMEOUT => 3,
90
                        RequestOptions::VERIFY => false,
91
                        RequestOptions::TIMEOUT => 5,
92
                    ];
93
                    $client = new Client($clientOptions);
94
                    try {
95
                        $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...
96
                            RequestOptions::HEADERS => [
97
                                'Accept' => '*/*',
98
                            ],
99
                        ]);
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...
100
                        if ($response->getStatusCode() === 200) {
101
                            $contents = $response->getBody()->getContents();
102
                        }
103
                    } catch (Throwable $e) {
104
                        Craft::error($e, __METHOD__);
105
                    }
106
                } else {
107
                    $contents = @file_get_contents($pathOrUrl);
108
                }
109
                if ($contents) {
110
                    $result = $contents;
111
                    if ($callback) {
112
                        $result = $callback($result);
113
                    }
114
                }
115
116
                return $result;
117
            },
118
            $cacheDuration,
119
            $dependency
120
        );
121
    }
122
123
    /**
124
     * Combine a path with a URL to create a URL
125
     *
126
     * @param string $url
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
127
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
128
     *
129
     * @return string
130
     */
131
    public static function createUrl(string $url, string $path): string
132
    {
133
        $url = (string)Craft::parseEnv($url);
134
        return rtrim($url, '/') . '/' . trim($path, '/');
135
    }
136
137
    /**
138
     * Fetch a script file
139
     *
140
     * @param string $name
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...
141
     * @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...
142
     * @return string
0 ignored issues
show
Coding Style introduced by
Tag @return cannot be grouped with parameter tags in a doc comment
Loading history...
143
     */
144
    public static function fetchScript(string $name, string $cacheKeySuffix = ''): string
145
    {
146
        $path = self::createUrl(self::SCRIPTS_DIR, $name);
147
148
        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...
149
    }
150
}
151