Passed
Pull Request — develop (#17)
by
unknown
16:34
created

FileHelper::createPath()   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
use GuzzleHttp\Client;
16
use GuzzleHttp\RequestOptions;
17
use Psr\Http\Message\ResponseInterface;
18
use Throwable;
19
use yii\caching\ChainedDependency;
20
use yii\caching\FileDependency;
21
use yii\caching\TagDependency;
22
23
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
24
 * @author    nystudio107
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @package tag
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
Tag value for @author tag indented incorrectly; expected 2 spaces but found 4
Loading history...
25
 * @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...
26
 * @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...
27
 */
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...
28
class FileHelper
29
{
30
    // Constants
31
    // =========================================================================
32
33
    const CACHE_KEY = 'vite';
34
    const CACHE_TAG = 'vite';
35
36
    const DEVMODE_CACHE_DURATION = 1;
37
38
    const SCRIPTS_DIR = '@vendor/nystudio107/craft-plugin-vite/src/web/assets/dist/';
39
40
    /**
41
     * Return the contents of a local file (via path) or remote file (via URL),
42
     * or null if the file doesn't exist or couldn't be fetched
43
     * Yii2 aliases and/or environment variables may be used
44
     *
45
     * @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...
46
     * @param callable|null $callback
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
47
     * @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...
48
     *
49
     * @return string|array|null
50
     */
51
    public static function fetch(string $pathOrUrl, callable $callback = null, string $cacheKeySuffix = '')
52
    {
53
        $pathOrUrl = (string)Craft::parseEnv($pathOrUrl);
0 ignored issues
show
Deprecated Code introduced by
The function Craft::parseEnv() has been deprecated: in 3.7.29. [[App::parseEnv()]] should be used instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

53
        $pathOrUrl = (string)/** @scrutinizer ignore-deprecated */ Craft::parseEnv($pathOrUrl);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
54
        // Create the dependency tags
55
        $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...
56
            'tags' => [
57
                self::CACHE_TAG . $cacheKeySuffix,
58
                self::CACHE_TAG . $cacheKeySuffix . $pathOrUrl,
59
            ],
60
        ]);
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...
61
        // If this is a file path such as for the `manifest.json`, add a FileDependency so it's cache bust if the file changes
62
        if (!UrlHelper::isAbsoluteUrl($pathOrUrl)) {
63
            $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...
64
                'dependencies' => [
65
                    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...
66
                        'fileName' => $pathOrUrl
67
                    ]),
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...
68
                    $dependency
69
                ]
70
            ]);
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...
71
        }
72
        // Set the cache duration based on devMode
73
        $cacheDuration = Craft::$app->getConfig()->getGeneral()->devMode
74
            ? self::DEVMODE_CACHE_DURATION
75
            : null;
76
        // Get the result from the cache, or parse the file
77
        $cache = Craft::$app->getCache();
78
        return $cache->getOrSet(
79
            self::CACHE_KEY . $cacheKeySuffix . $pathOrUrl,
80
            function () use ($pathOrUrl, $callback) {
81
                $contents = null;
82
                if (UrlHelper::isAbsoluteUrl($pathOrUrl)) {
83
                    $response = self::fetchResponse($pathOrUrl);
84
                    if ($response && $response->getStatusCode() === 200) {
85
                        $contents = $response->getBody()->getContents();
86
                    }
87
                } else {
88
                    $contents = @file_get_contents($pathOrUrl);
89
                }
90
                if ($contents && $callback) {
91
                    $contents = $callback($contents);
92
                }
93
94
                return $contents;
95
            },
96
            $cacheDuration,
97
            $dependency
98
        );
99
    }
100
101
    /**
102
     * Return a Guzzle ResponseInterface for the passed in $url
103
     *
104
     * @param string $url
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...
105
     * @return ResponseInterface|null
0 ignored issues
show
Coding Style introduced by
Tag @return cannot be grouped with parameter tags in a doc comment
Loading history...
106
     */
107
    public static function fetchResponse(string $url): ?ResponseInterface
108
    {
109
        $response = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $response is dead and can be removed.
Loading history...
110
        $clientOptions = [
111
            RequestOptions::HTTP_ERRORS => false,
112
            RequestOptions::CONNECT_TIMEOUT => 3,
113
            RequestOptions::VERIFY => false,
114
            RequestOptions::TIMEOUT => 5,
115
        ];
116
        $client = new Client($clientOptions);
117
        try {
118
            $response = $client->request('GET', $url, [
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...
119
                RequestOptions::HEADERS => [
120
                    'Accept' => '*/*',
121
                ],
122
            ]);
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...
123
        } catch (Throwable $e) {
124
            Craft::error($e->getMessage(), __METHOD__);
125
        }
126
127
        return $response;
128
    }
129
130
    /**
131
     * Combine a path with a URL to create a URL
132
     *
133
     * @param string $url
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
134
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
135
     *
136
     * @return string
137
     */
138
    public static function createUrl(string $url, string $path): string
139
    {
140
        $url = (string)Craft::parseEnv($url);
0 ignored issues
show
Deprecated Code introduced by
The function Craft::parseEnv() has been deprecated: in 3.7.29. [[App::parseEnv()]] should be used instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

140
        $url = (string)/** @scrutinizer ignore-deprecated */ Craft::parseEnv($url);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
141
        return rtrim($url, '/') . '/' . trim($path, '/');
142
    }
143
144
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $distPath should have a doc-comment as per coding-style.
Loading history...
145
     * Combine a path with dist to create a full path
146
     * @param string $url
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
There must be exactly one blank line before the tags in a doc comment
Loading history...
Coding Style introduced by
Doc comment for parameter $url does not match actual variable name $distPath
Loading history...
147
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
148
     *
149
     * @return string
150
     */
151
    public static function createPath(string $distPath, string $path): string
152
    {
153
        $distPath = (string)Craft::parseEnv($distPath);
0 ignored issues
show
Deprecated Code introduced by
The function Craft::parseEnv() has been deprecated: in 3.7.29. [[App::parseEnv()]] should be used instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

153
        $distPath = (string)/** @scrutinizer ignore-deprecated */ Craft::parseEnv($distPath);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
154
        return rtrim($distPath, '/') . '/' . trim($path, '/');
155
    }
156
157
    /**
158
     * Fetch a script file
159
     *
160
     * @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...
161
     * @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...
162
     * @return string
0 ignored issues
show
Coding Style introduced by
Tag @return cannot be grouped with parameter tags in a doc comment
Loading history...
163
     */
164
    public static function fetchScript(string $name, string $cacheKeySuffix = ''): string
165
    {
166
        $path = self::createUrl(self::SCRIPTS_DIR, $name);
167
168
        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...
169
    }
170
}
171