Passed
Push — master ( e0b8f2...8b4c58 )
by Caen
03:04 queued 12s
created

AssetService::cdnLink()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Hyde\Framework\Services;
6
7
use Hyde\Hyde;
8
use Illuminate\Support\Str;
9
use function str_contains;
10
11
/**
12
 * Handles the retrieval of core asset files. Commonly used through the Asset facade.
13
 *
14
 * This class is loaded into the service container, making it easy to access and modify.
15
 *
16
 * @see \Hyde\Facades\Asset
17
 */
18
class AssetService
19
{
20
    /**
21
     * The default HydeFront version to load.
22
     *
23
     * @property string $version HydeFront SemVer Tag
24
     */
25
    public string $version = 'v2.0';
26
27
    public function version(): string
28
    {
29
        return $this->version;
30
    }
31
32
    public function constructCdnPath(string $file): string
33
    {
34
        return 'https://cdn.jsdelivr.net/npm/hydefront@'.$this->version().'/dist/'.$file;
35
    }
36
37
    /**
38
     * Alias for constructCdnPath.
39
     */
40
    public function cdnLink(string $file): string
41
    {
42
        return $this->constructCdnPath($file);
43
    }
44
45
    public function mediaLink(string $file): string
46
    {
47
        return Hyde::relativeLink("media/$file").$this->getCacheBustKey($file);
48
    }
49
50
    public function hasMediaFile(string $file): bool
51
    {
52
        return file_exists(Hyde::path('_media').'/'.$file);
53
    }
54
55
    public function injectTailwindConfig(): string
56
    {
57
        $config = Str::between(file_get_contents(Hyde::path('tailwind.config.js')), '{', '}');
58
59
        if (str_contains($config, 'plugins: [')) {
60
            $tokens = explode('plugins: [', $config, 2);
61
            $tokens[1] = Str::after($tokens[1], ']');
62
            $config = implode('', $tokens);
63
        }
64
65
        return preg_replace('/\s+/', ' ', "/* tailwind.config.js */ \n".rtrim($config, ",\n\r"));
66
    }
67
68
    protected function getCacheBustKey(string $file): string
69
    {
70
        if (! config('hyde.cache_busting', true)) {
71
            return '';
72
        }
73
74
        return '?v='.md5_file(Hyde::path("_media/$file"));
75
    }
76
}
77