|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace OpenForgeProject\MageForge\Service; |
| 6 | + |
| 7 | +use Magento\Framework\App\State; |
| 8 | +use Magento\Framework\Filesystem\Driver\File; |
| 9 | +use Symfony\Component\Console\Style\SymfonyStyle; |
| 10 | + |
| 11 | +/** |
| 12 | + * Service for cleaning symlinks in theme CSS directories |
| 13 | + * |
| 14 | + * In developer mode, symlinks in {theme}/web/css/ can cause issues during |
| 15 | + * the build process. This service detects and removes all symlinks before |
| 16 | + * the build starts to ensure a clean workflow. |
| 17 | + */ |
| 18 | +class SymlinkCleaner |
| 19 | +{ |
| 20 | + public function __construct( |
| 21 | + private readonly File $fileDriver, |
| 22 | + private readonly State $state |
| 23 | + ) { |
| 24 | + } |
| 25 | + |
| 26 | + /** |
| 27 | + * Remove all symlinks from {theme}/web/css/ directory in developer mode |
| 28 | + * |
| 29 | + * @param string $themePath Path to theme directory |
| 30 | + * @param SymfonyStyle $io Symfony style output |
| 31 | + * @param bool $isVerbose Whether to show verbose output |
| 32 | + * @return bool True on success or if no action needed, false on error |
| 33 | + */ |
| 34 | + public function cleanSymlinks( |
| 35 | + string $themePath, |
| 36 | + SymfonyStyle $io, |
| 37 | + bool $isVerbose |
| 38 | + ): bool { |
| 39 | + try { |
| 40 | + // Only clean symlinks in developer mode |
| 41 | + if ($this->state->getMode() !== State::MODE_DEVELOPER) { |
| 42 | + return true; |
| 43 | + } |
| 44 | + |
| 45 | + $cssPath = rtrim($themePath, '/') . '/web/css'; |
| 46 | + |
| 47 | + // Nothing to clean if directory doesn't exist |
| 48 | + if (!$this->fileDriver->isDirectory($cssPath)) { |
| 49 | + return true; |
| 50 | + } |
| 51 | + |
| 52 | + $items = $this->fileDriver->readDirectory($cssPath); |
| 53 | + $deletedCount = 0; |
| 54 | + |
| 55 | + foreach ($items as $item) { |
| 56 | + // Check if item is a symlink |
| 57 | + if (is_link($item)) { |
| 58 | + $this->fileDriver->deleteFile($item); |
| 59 | + $deletedCount++; |
| 60 | + |
| 61 | + if ($isVerbose) { |
| 62 | + $io->writeln(sprintf( |
| 63 | + ' <fg=yellow>⚠</> Removed symlink: %s', |
| 64 | + basename($item) |
| 65 | + )); |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + if ($deletedCount > 0 && $isVerbose) { |
| 71 | + $io->success(sprintf( |
| 72 | + 'Removed %d symlink(s) from web/css/', |
| 73 | + $deletedCount |
| 74 | + )); |
| 75 | + } |
| 76 | + |
| 77 | + return true; |
| 78 | + } catch (\Exception $e) { |
| 79 | + // Don't fail the build process if symlink cleanup fails |
| 80 | + // Just warn the user and continue |
| 81 | + if ($isVerbose) { |
| 82 | + $io->warning(sprintf( |
| 83 | + 'Could not clean symlinks: %s', |
| 84 | + $e->getMessage() |
| 85 | + )); |
| 86 | + } |
| 87 | + return true; |
| 88 | + } |
| 89 | + } |
| 90 | +} |
0 commit comments