Passed
Push — master ( c75158...e25554 )
by Caen
03:33 queued 14s
created

AssetService::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
eloc 2
nc 2
nop 0
dl 0
loc 4
rs 10
c 2
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
     * @var string HydeFront SemVer Tag
24
     */
25
    public string $version = 'v2.0';
26
27
    public function __construct()
28
    {
29
        if (config('hyde.hydefront_version')) {
30
            $this->version = config('hyde.hydefront_version');
31
        }
32
    }
33
34
    public function version(): string
35
    {
36
        return $this->version;
37
    }
38
39
    public function constructCdnPath(string $file): string
40
    {
41
        return 'https://cdn.jsdelivr.net/npm/hydefront@'.$this->version().'/dist/'.$file;
42
    }
43
44
    /**
45
     * Alias for constructCdnPath.
46
     */
47
    public function cdnLink(string $file): string
48
    {
49
        return $this->constructCdnPath($file);
50
    }
51
52
    public function mediaLink(string $file): string
53
    {
54
        return Hyde::mediaLink("$file").$this->getCacheBustKey($file);
55
    }
56
57
    public function hasMediaFile(string $file): bool
58
    {
59
        return file_exists(Hyde::mediaPath().'/'.$file);
60
    }
61
62
    public function injectTailwindConfig(): string
63
    {
64
        $config = Str::between(file_get_contents(Hyde::path('tailwind.config.js')), '{', '}');
65
66
        if (str_contains($config, 'plugins: [')) {
67
            $tokens = explode('plugins: [', $config, 2);
68
            $tokens[1] = Str::after($tokens[1], ']');
69
            $config = implode('', $tokens);
70
        }
71
72
        return preg_replace('/\s+/', ' ', "/* tailwind.config.js */ \n".rtrim($config, ",\n\r"));
73
    }
74
75
    protected function getCacheBustKey(string $file): string
76
    {
77
        if (! config('hyde.cache_busting', true)) {
78
            return '';
79
        }
80
81
        return '?v='.md5_file(Hyde::mediaPath("$file"));
82
    }
83
}
84