|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace AppBundle\AssetMapper; |
| 6 | + |
| 7 | +use Symfony\Component\AssetMapper\Compressor\CompressorInterface; |
| 8 | +use Symfony\Component\AssetMapper\Path\PublicAssetsFilesystemInterface; |
| 9 | +use Symfony\Component\DependencyInjection\Attribute\Autowire; |
| 10 | +use Symfony\Component\Filesystem\Filesystem; |
| 11 | + |
| 12 | +/** |
| 13 | + * cf. https://symfony.com/doc/current/frontend/asset_mapper.html#serving-assets-in-dev-vs-prod |
| 14 | + */ |
| 15 | +class PostCompilationCopyHandler implements PublicAssetsFilesystemInterface |
| 16 | +{ |
| 17 | + private Filesystem $filesystem; |
| 18 | + |
| 19 | + /** |
| 20 | + * @param string[] $extensionsToCompress |
| 21 | + */ |
| 22 | + public function __construct( |
| 23 | + #[Autowire('%kernel.project_dir%/../htdocs')] |
| 24 | + private readonly string $publicDir, |
| 25 | + private readonly ?CompressorInterface $compressor = null, |
| 26 | + private readonly array $extensionsToCompress = [], |
| 27 | + ) { |
| 28 | + $this->filesystem = new Filesystem(); |
| 29 | + } |
| 30 | + |
| 31 | + public function write(string $path, string $contents): void |
| 32 | + { |
| 33 | + $targetPath = $this->publicDir . '/' . ltrim($path, '/'); |
| 34 | + |
| 35 | + $this->filesystem->dumpFile($targetPath, $contents); |
| 36 | + $this->compress($targetPath); |
| 37 | + } |
| 38 | + |
| 39 | + public function copy(string $originPath, string $path): void |
| 40 | + { |
| 41 | + $targetPath = $this->publicDir . '/' . ltrim($path, '/'); |
| 42 | + |
| 43 | + $this->filesystem->copy($originPath, $targetPath, true); |
| 44 | + $this->compress($targetPath); |
| 45 | + } |
| 46 | + |
| 47 | + public function getDestinationPath(): string |
| 48 | + { |
| 49 | + return $this->publicDir; |
| 50 | + } |
| 51 | + |
| 52 | + private function compress(string $targetPath): void |
| 53 | + { |
| 54 | + foreach ($this->extensionsToCompress as $ext) { |
| 55 | + if (!str_ends_with($targetPath, ".$ext")) { |
| 56 | + continue; |
| 57 | + } |
| 58 | + |
| 59 | + $this->compressor?->compress($targetPath); |
| 60 | + |
| 61 | + return; |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments