Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
3 / 3
CRAP
100.00% covered (success)
100.00%
1 / 1
YiiAssetManager
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
3 / 3
5
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getAssetUrl
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
3
 resetCache
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3declare(strict_types=1);
4
5/** @license For full copyright and license information, please see the LICENSE.md file. */
6
7namespace App\Core\Asset;
8
9defined('AMMONLY_APP') || exit('Direct script access is forbidden.');
10
11/**
12 * YiiAssetManager.
13 *
14 * Provides high-performance asset URL generation with automatic content-hash cache busting.
15 *
16 * @package App\Core\Asset
17 */
18final class YiiAssetManager implements AssetManagerInterface
19{
20    /** @var array<string, string> In-memory hash cache */
21    private static array $hashCache = [];
22
23    /**
24     * YiiAssetManager constructor.
25     *
26     * @param string $publicPath Absolute path to public web root.
27     */
28    public function __construct(private readonly string $publicPath)
29    {
30    }
31
32    /**
33     * Resolves a public asset path into a versioned URL with automated cache busting.
34     *
35     * @param string $path Asset path relative to public directory.
36     * @return string Versioned asset URL.
37     */
38    public function getAssetUrl(string $path): string
39    {
40        $cleanPath = '/' . ltrim($path, '/');
41        $filePath = $this->publicPath . $cleanPath;
42
43        if (isset(self::$hashCache[$filePath])) {
44            return $cleanPath . '?v=' . self::$hashCache[$filePath];
45        }
46
47        if (file_exists($filePath)) {
48            $mtime = (int)filemtime($filePath);
49            $hash = substr(md5((string)$mtime), 0, 8);
50            self::$hashCache[$filePath] = $hash;
51            return $cleanPath . '?v=' . $hash;
52        }
53
54        return $cleanPath;
55    }
56
57    /**
58     * Resets hash cache for testing.
59     */
60    public static function resetCache(): void
61    {
62        self::$hashCache = [];
63    }
64}