Passed
Push — develop ( e19290...7cbc6e )
by Andrew
03:54
created

FileHelper   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 91
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 50
c 1
b 0
f 0
dl 0
loc 91
rs 10
wmc 8

1 Method

Rating   Name   Duplication   Size   Complexity  
B fetch() 0 68 8
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;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, nystudio107\pluginvite\helpers\UrlHelper. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
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
    /**
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
                                'User-Agent' => self::USER_AGENT_STRING,
98
                                'Accept' => '*/*',
99
                            ],
100
                        ]);
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...
101
                        if ($response->getStatusCode() === 200) {
102
                            $contents = $response->getBody()->getContents();
103
                        }
104
                    } catch (Throwable $e) {
105
                        Craft::error($e, __METHOD__);
106
                    }
107
                } else {
108
                    $contents = @file_get_contents($pathOrUrl);
109
                }
110
                if ($contents) {
111
                    $result = $contents;
112
                    if ($callback) {
113
                        $result = $callback($result);
114
                    }
115
                }
116
117
                return $result;
118
            },
119
            $cacheDuration,
120
            $dependency
121
        );
122
    }
123
}
124