diff --git a/src/BassetManager.php b/src/BassetManager.php index a3bc92b..b001d2b 100644 --- a/src/BassetManager.php +++ b/src/BassetManager.php @@ -31,7 +31,7 @@ class BassetManager private bool $dev; - private bool $overwritesLoaded = false; + private bool $overridesLoaded = false; private bool $forceUrlCache; @@ -54,7 +54,7 @@ public function __construct() $this->disk = $disk; $this->basePath = (string) Str::of(config('backpack.basset.path'))->finish('/'); $this->dev = config('backpack.basset.dev_mode', false); - $this->forceUrlCache = config('backpack.basset.force_url_cache', false); + $this->forceUrlCache = config('backpack.basset.always_cache_external_urls', false); $this->cacheMap = new CacheMap($this->disk, $this->basePath); $this->loader = new LoadingTime(); $this->unarchiver = new Unarchiver(); @@ -84,7 +84,7 @@ public function markAsLoaded(CacheEntry|string $asset): void public function map(string $asset, string $source, array $attributes = []): void { - if (! $this->overwritesLoaded) { + if (! $this->overridesLoaded) { $this->initOverwrites(); } @@ -93,7 +93,7 @@ public function map(string $asset, string $source, array $attributes = []): void } $this->namedAssets[$asset] = [ - 'source' => $source, + 'source' => $source, 'attributes' => $attributes, ]; } @@ -155,7 +155,7 @@ public function clearLoadedAssets() $this->loaded = []; } - public function clearAssetMap() + public function clearNamedAssets() { $this->namedAssets = []; } @@ -483,7 +483,7 @@ private function replaceAsset(CacheEntry $asset, CacheEntry $mapped, $output): S private function getAssetContent(CacheEntry $asset, bool $output = true): StatusEnum|string { if (Str::isUrl($asset->getAssetPath())) { - // when in dev mode, cdn should be rendered + // when in dev mode, cdn should be rendered if external urls are not forced to be cached. if ($this->dev && ! $this->forceUrlCache) { $output && $this->output->write($asset, $this->dev); @@ -492,7 +492,7 @@ private function getAssetContent(CacheEntry $asset, bool $output = true): Status $content = $this->fetchContent($asset->getAssetPath()); } else { - if (! $asset->existsOnLocalPath()) { + if (! $asset->isLocalAsset()) { return $this->loader->finish(StatusEnum::INVALID); } $content = $asset->getContents(); @@ -522,7 +522,7 @@ private function uploadAssetToDisk(CacheEntry $asset, string $content, bool $out public function buildCacheEntry(CacheEntry|string $asset, $attributes = []): CacheEntry { - if (! $this->overwritesLoaded) { + if (! $this->overridesLoaded) { $this->initOverwrites(); } @@ -548,11 +548,11 @@ private function getNamedAsset(string $asset): array return $this->namedAssets[$asset]; } - private function initOverwrites() + private function initOverwrites(): void { - $class = config('backpack.basset.asset_overwrite'); - if ($class && class_exists($class) && is_a($class, AssetOverwrite::class, true)) { - $this->overwritesLoaded = true; + $class = config('backpack.basset.asset_overrides'); + if ($class && class_exists($class) && is_a($class, OverridesAssets::class, true)) { + $this->overridesLoaded = true; (new $class())->assets(); } } diff --git a/src/BassetServiceProvider.php b/src/BassetServiceProvider.php index e60f066..abaee73 100644 --- a/src/BassetServiceProvider.php +++ b/src/BassetServiceProvider.php @@ -21,7 +21,7 @@ class BassetServiceProvider extends ServiceProvider Console\Commands\BassetCheck::class, Console\Commands\BassetInstall::class, Console\Commands\BassetFresh::class, - Console\Commands\BassetNamedAssetsList::class, + Console\Commands\BassetList::class, ]; /** @@ -36,9 +36,6 @@ public function boot(): void $this->bootForConsole(); } - // Load basset disk - $this->loadDisk(); - // Run the terminate commands $this->app->terminating(fn () => $this->terminate()); } @@ -187,11 +184,11 @@ public function loadDisk(): void // add the basset disk to filesystem configuration app()->config['filesystems.disks.basset'] = [ - 'driver' => 'local', - 'root' => public_path(), - 'url' => url(''), + 'driver' => 'local', + 'root' => public_path(), + 'url' => url(''), 'visibility' => 'public', - 'throw' => false, + 'throw' => false, ]; } diff --git a/src/Console/Commands/BassetCache.php b/src/Console/Commands/BassetCache.php index d0f6ef8..b094d0d 100644 --- a/src/Console/Commands/BassetCache.php +++ b/src/Console/Commands/BassetCache.php @@ -39,8 +39,8 @@ class BassetCache extends Command */ public function handle(): void { - $internalized = []; - $failedToInternalize = []; + $internalizedAssets = []; + $notInternalizedAssets = []; $starttime = microtime(true); @@ -68,7 +68,7 @@ public function handle(): void // Map all bassets $content = File::get($file); preg_match_all('/(basset|@bassetArchive|@bassetDirectory)\((.+)\)/', $content, $matches); - //dump($matches[2]); + $matches[2] = collect($matches[2]) ->map(fn ($match) => collect(explode(',', $match)) ->map(function ($arg) { @@ -96,7 +96,7 @@ public function handle(): void $bar = $this->output->createProgressBar($totalBassets); $bar->start(); // Cache the bassets - $bassets->eachSpread(function (string $type, array $args, int $i) use ($bar, &$internalized, &$failedToInternalize) { + $bassets->eachSpread(function (string $type, array $args, int $i) use ($bar, &$internalizedAssets, &$notInternalizedAssets) { if ($args[0] === false) { return; } @@ -110,16 +110,16 @@ public function handle(): void if (in_array($type, ['basset', 'bassetArchive', 'bassetDirectory', 'bassetBlock'])) { $result = Basset::{$type}(...$args)->value; if ($result !== StatusEnum::INVALID->value) { - $internalized[] = $args[0]; + $internalizedAssets[] = $args[0]; } else { - $failedToInternalize[] = $args[0]; + $notInternalizedAssets[] = $args[0]; } } else { throw new \Exception('Invalid basset type'); } } catch (Throwable $th) { $result = StatusEnum::INVALID->value; - $failedToInternalize[] = $args[0]; + $notInternalizedAssets[] = $args[0]; } if ($this->getOutput()->isVerbose()) { @@ -131,34 +131,34 @@ public function handle(): void } }); - // we will not loop through the bassets that are in the named map, and internalize any that our script hasn't internalized yet + // we will now loop through the bassets that are in the named map, and internalize any that our script hasn't internalized yet $namedAssets = Basset::getNamedAssets(); // get the named assets that are not internalized yet $namedAssets = collect($namedAssets) - ->filter(function ($asset, $id) use ($internalized) { - return ! in_array($id, $internalized); + ->filter(function ($asset, $id) use ($internalizedAssets) { + return ! in_array($id, $internalizedAssets); }); foreach ($namedAssets as $id => $asset) { $result = Basset::basset($id, false)->value; if ($result !== StatusEnum::INVALID->value) { - $internalized[] = $id; + $internalizedAssets[] = $id; } else { - $failedToInternalize[] = $id; + $notInternalizedAssets[] = $id; } } - $failedToInternalize = implode(', ', array_unique($failedToInternalize)); + $notInternalizedAssets = implode(', ', array_unique($notInternalizedAssets)); // Save the cache map Basset::cacheMap()->save(); $bar->finish(); - if (! empty($failedToInternalize)) { + if (! empty($notInternalizedAssets)) { $this->newLine(2); - $this->line('Failed to cache: '.$failedToInternalize); + $this->line('Failed to cache: '.$notInternalizedAssets); } $this->newLine(2); diff --git a/src/Console/Commands/BassetInstall.php b/src/Console/Commands/BassetInstall.php index f79e808..d6ec44c 100644 --- a/src/Console/Commands/BassetInstall.php +++ b/src/Console/Commands/BassetInstall.php @@ -51,24 +51,29 @@ public function handle(): void private function addGitIgnore() { - $message = 'Adding public/'.config('backpack.basset.path').' to .gitignore'; + $publicPath = public_path(config('backpack.basset.path')); + $basePath = base_path(); + + $publicPath = Str::of($publicPath)->after($basePath)->replace('\\', '/')->start('/')->value(); + + $message = 'Adding '.$publicPath.' to .gitignore'; if (! file_exists(base_path('.gitignore'))) { - $this->components->task($message, function () { - file_put_contents(base_path('.gitignore'), 'public/'.config('backpack.basset.path')); + $this->components->task($message, function () use ($publicPath) { + file_put_contents(base_path('.gitignore'), $publicPath); }); return; } - if (Str::of(file_get_contents(base_path('.gitignore')))->contains('public/'.config('backpack.basset.path'))) { + if (Str::of(file_get_contents(base_path('.gitignore')))->contains($publicPath)) { $this->components->twoColumnDetail($message, 'BASSET PATH ALREADY EXISTS ON GITIGNORE'); return; } - $this->components->task($message, function () { - file_put_contents(base_path('.gitignore'), 'public/'.config('backpack.basset.path'), FILE_APPEND); + $this->components->task($message, function () use ($publicPath) { + file_put_contents(base_path('.gitignore'), $publicPath, FILE_APPEND); }); } diff --git a/src/Console/Commands/BassetNamedAssetsList.php b/src/Console/Commands/BassetList.php similarity index 90% rename from src/Console/Commands/BassetNamedAssetsList.php rename to src/Console/Commands/BassetList.php index 5341ac3..2e390e0 100644 --- a/src/Console/Commands/BassetNamedAssetsList.php +++ b/src/Console/Commands/BassetList.php @@ -11,14 +11,14 @@ * * @property object $output */ -class BassetNamedAssetsList extends Command +class BassetList extends Command { /** * The name and signature of the console command. * * @var string */ - protected $signature = 'basset:named-assets {--filter=*}'; + protected $signature = 'basset:list {--filter=*}'; /** * The console command description. diff --git a/src/Helpers/CacheEntry.php b/src/Helpers/CacheEntry.php index 88d373a..d29d11f 100644 --- a/src/Helpers/CacheEntry.php +++ b/src/Helpers/CacheEntry.php @@ -85,12 +85,23 @@ public function getAssetName(): string return $this->assetName; } + /** + * Check if an asset exists on the given disk. + * + * @param Filesystem $disk + * @return bool + */ public function existsOnDisk(Filesystem $disk): bool { return isset($this->assetDiskPath) && $disk->exists($this->assetDiskPath); } - public function existsOnLocalPath() + /** + * Check if the current asset is a local file. + * + * @return bool + */ + public function isLocalAsset() { return File::exists($this->assetPath); } @@ -98,11 +109,11 @@ public function existsOnLocalPath() public function toArray(): array { return [ - 'asset_name' => $this->assetName, - 'asset_path' => $this->assetPath, + 'asset_name' => $this->assetName, + 'asset_path' => $this->assetPath, 'asset_disk_path' => isset($this->assetDiskPath) ? $this->assetDiskPath : $this->getPathOnDisk($this->assetPath), - 'attributes' => $this->attributes, - 'content_hash' => $this->content_hash, + 'attributes' => $this->attributes, + 'content_hash' => $this->content_hash, ]; } diff --git a/src/Helpers/FileOutput.php b/src/Helpers/FileOutput.php index 3f4ae63..468ab34 100644 --- a/src/Helpers/FileOutput.php +++ b/src/Helpers/FileOutput.php @@ -35,8 +35,9 @@ public function __construct() * * @return void */ - public function write(CacheEntry $asset, bool $dev = false): void + public function write(CacheEntry $asset): void { + $dev = config('backpack.basset.dev_mode', false); $filePath = $dev ? $asset->getAssetPath() : $asset->getAssetDiskPath(); $extension = (string) Str::of($filePath)->afterLast('.'); @@ -44,8 +45,8 @@ public function write(CacheEntry $asset, bool $dev = false): void $file = match ($extension) { 'jpg', 'jpeg', 'png', 'webp', 'gif', 'svg' => 'img', 'mp3', 'ogg', 'wav', 'mp4', 'webm', 'avi' => 'source', - 'pdf' => 'object', - 'vtt' => 'track', + 'pdf' => 'object', + 'vtt' => 'track', default => $extension }; @@ -56,7 +57,7 @@ public function write(CacheEntry $asset, bool $dev = false): void } echo Blade::render($template, [ - 'src' => $this->assetPath($filePath, $dev), + 'src' => $this->assetPath($filePath, $dev), 'args' => $this->prepareAttributes($asset->getAttributes()), ]); } @@ -67,8 +68,10 @@ public function write(CacheEntry $asset, bool $dev = false): void * @param string $path * @return string */ - public function assetPath(string $path, bool $dev = false): string + public function assetPath(string $path): string { + $dev = config('backpack.basset.dev_mode', false); + $asset = Str::of(asset($path.($dev ? '' : $this->cachebusting))); if ($this->useRelativePaths && $asset->startsWith(url(''))) { diff --git a/src/AssetOverwrite.php b/src/OverridesAssets.php similarity index 74% rename from src/AssetOverwrite.php rename to src/OverridesAssets.php index c580ee9..d8a5f07 100644 --- a/src/AssetOverwrite.php +++ b/src/OverridesAssets.php @@ -2,7 +2,7 @@ namespace Backpack\Basset; -interface AssetOverwrite +interface OverridesAssets { public function assets(): void; } diff --git a/src/config/backpack/basset.php b/src/config/backpack/basset.php index 356725d..8dd3e0c 100644 --- a/src/config/backpack/basset.php +++ b/src/config/backpack/basset.php @@ -6,7 +6,7 @@ // all external urls (usually cdns) will be cached on first request or // when running `basset:cache` even if dev_mode is enabled - 'force_url_cache' => true, + 'always_cache_external_urls' => true, // verify ssl certificate while fetching assets 'verify_ssl_certificate' => env('BASSET_VERIFY_SSL_CERTIFICATE', true), @@ -27,18 +27,15 @@ resource_path('views'), ], - // a class that allow you to define assets that can overwrite the assets on the map. - // packages can define the assets they need in a map, that way you can overwrite - // the package assets without modifying the package files, eg: you want to use - // a different version of a package asset without modifying the package views. - // this file shouldn't be used to add new assets, but exclusively to overwrite existing ones. - // to implement it, create a new class that implements the `Backpack\Basset\AssetOverwrite` interface. + // define the final asset names and URLs in the asset map; this allows you to override + // anything added to the asset map by Composer packages; this config expects + // a class that implements `Backpack\Basset\OverridesAssets /** * namespace App;. * - * use Backpack\Basset\AssetOverwrite; + * use Backpack\Basset\OverridesAssets; * - * class AssetOverwrites implements AssetOverwrite + * class OverrideAssets implements OverridesAssets * { * public function assets(): void * { @@ -47,7 +44,7 @@ * * } */ - 'asset_overwrite' => null, + 'asset_overrides' => null, // content security policy nonce 'nonce' => null, diff --git a/tests/Feature/NamedAssetsTest.php b/tests/Feature/NamedAssetsTest.php index dc79690..80ca295 100644 --- a/tests/Feature/NamedAssetsTest.php +++ b/tests/Feature/NamedAssetsTest.php @@ -50,7 +50,7 @@ expect(disk()->get($oldPath))->toBe(getStub($oldPath.'.output')); - bassetInstance()->clearAssetMap(); + bassetInstance()->clearNamedAssets(); bassetInstance()->clearLoadedAssets();