diff --git a/config/services.php b/config/services.php index e54490f..a4cacfe 100644 --- a/config/services.php +++ b/config/services.php @@ -5,6 +5,8 @@ use Symfonycasts\SassBundle\SassBuilder; use Symfonycasts\SassBundle\AssetMapper\SassCssCompiler; use Symfonycasts\SassBundle\AssetMapper\SassPublicPathAssetPathResolver; +use Symfonycasts\SassBundle\Listener\PreAssetsCompileEventListener; +use Symfony\Component\AssetMapper\Event\PreAssetsCompileEvent; use function Symfony\Component\DependencyInjection\Loader\Configurator\abstract_arg; use function Symfony\Component\DependencyInjection\Loader\Configurator\service; use function Symfony\Component\DependencyInjection\Loader\Configurator\param; @@ -35,10 +37,18 @@ abstract_arg('path to css output directory'), service('sass.builder'), ]) + ->set('sass.public_asset_path_resolver', SassPublicPathAssetPathResolver::class) ->decorate('asset_mapper.public_assets_path_resolver') ->args([ service('.inner') ]) + + ->set('sass.listener.pre_assets_compile', PreAssetsCompileEventListener::class) + ->tag('kernel.event_listener', [ + 'event' => PreAssetsCompileEvent::class, + 'method' => '__invoke' + ]) + ; ; }; diff --git a/src/AssetMapper/SassPublicPathAssetPathResolver.php b/src/AssetMapper/SassPublicPathAssetPathResolver.php index 053b66d..9c05c00 100644 --- a/src/AssetMapper/SassPublicPathAssetPathResolver.php +++ b/src/AssetMapper/SassPublicPathAssetPathResolver.php @@ -30,6 +30,10 @@ public function resolvePublicPath(string $logicalPath): string public function getPublicFilesystemPath(): string { + if (!method_exists($this->decorator, 'getPublicFilesystemPath')) { + throw new \Exception('Something weird happened, we should never reach this line!'); + } + $path = $this->decorator->getPublicFilesystemPath(); if (str_contains($path, '.scss')) { diff --git a/src/Listener/PreAssetsCompileEventListener.php b/src/Listener/PreAssetsCompileEventListener.php new file mode 100644 index 0000000..8fc99da --- /dev/null +++ b/src/Listener/PreAssetsCompileEventListener.php @@ -0,0 +1,40 @@ + + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfonycasts\SassBundle\Listener; + +use Symfony\Component\AssetMapper\Event\PreAssetsCompileEvent; +use Symfony\Component\Console\Input\ArrayInput; +use Symfony\Component\Console\Style\SymfonyStyle; +use Symfonycasts\SassBundle\SassBuilder; + +class PreAssetsCompileEventListener +{ + public function __construct(private readonly SassBuilder $sassBuilder) + { + } + + public function __invoke(PreAssetsCompileEvent $preAssetsCompileEvent): void + { + $this->sassBuilder->setOutput( + new SymfonyStyle( + new ArrayInput([]), + $preAssetsCompileEvent->getOutput() + ) + ); + + $process = $this->sassBuilder->runBuild(false); + + if ($process->isSuccessful()) { + return; + } + + throw new \RuntimeException(sprintf('Error compiling sass: "%s"', $process->getErrorOutput())); + } +}