Skip to content

Commit

Permalink
Merge pull request #13 from DigitallyHappy/use-call-after-resolving
Browse files Browse the repository at this point in the history
load blade directives using callAfterResolving
  • Loading branch information
tabacitu authored Mar 8, 2022
2 parents a323b8f + 16f5cc0 commit a79e6b0
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 41 deletions.
43 changes: 42 additions & 1 deletion src/AssetsServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
namespace DigitallyHappy\Assets;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
use Illuminate\View\Compilers\BladeCompiler;

class AssetsServiceProvider extends ServiceProvider
{
Expand Down Expand Up @@ -31,7 +33,46 @@ public function register(): void
// $loader = \Illuminate\Foundation\AliasLoader::getInstance();
// $loader->alias('Assets', '\DigitallyHappy\Assets\Facade\Assets');

require_once __DIR__.'/blade_directives.php';
$this->registerBladeDirectives();
}

protected function registerBladeDirectives()
{
$this->callAfterResolving('blade.compiler', function (BladeCompiler $bladeCompiler) {
$bladeCompiler->directive('loadStyleOnce', function ($parameter) {
return "<?php Assets::echoCss({$parameter}); ?>";
});

$bladeCompiler->directive('loadScriptOnce', function ($parameter) {
return "<?php Assets::echoJs({$parameter}); ?>";
});

$bladeCompiler->directive('loadOnce', function ($parameter) {
// determine if it's a CSS or JS file
$cleanParameter = Str::of($parameter)->trim("'")->trim('"')->trim('`');
$filePath = Str::of($cleanParameter)->before('?')->before('#');

// mey be useful to get the second parameter
// if (Str::contains($parameter, ',')) {
// $secondParameter = Str::of($parameter)->after(',')->trim(' ');
// }

if (substr($filePath, -3) == '.js') {
return "<?php Assets::echoJs({$parameter}); ?>";
}

if (substr($filePath, -4) == '.css') {
return "<?php Assets::echoCss({$parameter}); ?>";
}

// it's a block start
return "<?php if(! Assets::isLoaded('".$cleanParameter."')) { Assets::markAsLoaded('".$cleanParameter."'); ?>";
});

$bladeCompiler->directive('endLoadOnce', function () {
return '<?php } ?>';
});
});
}

/**
Expand Down
40 changes: 0 additions & 40 deletions src/blade_directives.php

This file was deleted.

0 comments on commit a79e6b0

Please sign in to comment.