FileHelper   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 130
Duplicated Lines 0 %

Importance

Changes 4
Bugs 1 Features 0
Metric Value
eloc 54
c 4
b 1
f 0
dl 0
loc 130
rs 10
wmc 12

4 Methods

Rating   Name   Duplication   Size   Complexity  
A fetchResponse() 0 21 2
A createUrl() 0 4 1
A fetchScript() 0 5 1
B fetch() 0 49 8
1
<?php
2
/**
3
 * Vite plugin for Craft CMS
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\FileHelper as CraftFileHelper;
15
use craft\helpers\UrlHelper;
16
use GuzzleHttp\Client;
17
use GuzzleHttp\RequestOptions;
18
use Psr\Http\Message\ResponseInterface;
19
use Throwable;
20
use yii\caching\ChainedDependency;
21
use yii\caching\FileDependency;
22
use yii\caching\TagDependency;
23
24
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
25
 * @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...
26
 * @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...
27
 * @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...
28
 */
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...
29
class FileHelper
30
{
31
    // Constants
32
    // =========================================================================
33
34
    public const CACHE_KEY = 'vite';
35
    public const CACHE_TAG = 'vite';
36
37
    public const DEVMODE_CACHE_DURATION = 1;
38
39
    public const SCRIPTS_DIR = '@vendor/nystudio107/craft-plugin-vite/src/web/assets/dist/';
40
41
    /**
42
     * Return the contents of a local file (via path) or remote file (via URL),
43
     * or null if the file doesn't exist or couldn't be fetched
44
     * Yii2 aliases and/or environment variables may be used
45
     *
46
     * @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...
47
     * @param callable|null $callback
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
48
     * @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...
49
     *
50
     * @return string|array|null
51
     */
52
    public static function fetch(string $pathOrUrl, callable $callback = null, string $cacheKeySuffix = '')
53
    {
54
        $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

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

143
        $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...
144
        return rtrim($url, '/') . '/' . trim($path, '/');
145
    }
146
147
    /**
148
     * Fetch a script file
149
     *
150
     * @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...
151
     * @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...
152
     * @return string
0 ignored issues
show
Coding Style introduced by
Tag @return cannot be grouped with parameter tags in a doc comment
Loading history...
153
     */
154
    public static function fetchScript(string $name, string $cacheKeySuffix = ''): string
155
    {
156
        $path = self::createUrl(self::SCRIPTS_DIR, $name);
157
158
        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...
159
    }
160
}
161