Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
pxpm committed Dec 16, 2024
1 parent dde32a7 commit b88a1b5
Show file tree
Hide file tree
Showing 10 changed files with 78 additions and 65 deletions.
24 changes: 12 additions & 12 deletions src/BassetManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class BassetManager

private bool $dev;

private bool $overwritesLoaded = false;
private bool $overridesLoaded = false;

private bool $forceUrlCache;

Expand All @@ -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();
Expand Down Expand Up @@ -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();
}

Expand All @@ -93,7 +93,7 @@ public function map(string $asset, string $source, array $attributes = []): void
}

$this->namedAssets[$asset] = [
'source' => $source,
'source' => $source,
'attributes' => $attributes,
];
}
Expand Down Expand Up @@ -155,7 +155,7 @@ public function clearLoadedAssets()
$this->loaded = [];
}

public function clearAssetMap()
public function clearNamedAssets()
{
$this->namedAssets = [];
}
Expand Down Expand Up @@ -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);

Check failure on line 488 in src/BassetManager.php

View workflow job for this annotation

GitHub Actions / PHP 8.1 / Laravel ^10.15

Method Backpack\Basset\Helpers\FileOutput::write() invoked with 2 parameters, 1 required.

Check failure on line 488 in src/BassetManager.php

View workflow job for this annotation

GitHub Actions / PHP 8.2 / Laravel ^10.15

Method Backpack\Basset\Helpers\FileOutput::write() invoked with 2 parameters, 1 required.

Expand All @@ -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();
Expand Down Expand Up @@ -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();
}

Expand All @@ -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();
}
}
Expand Down
13 changes: 5 additions & 8 deletions src/BassetServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
];

/**
Expand All @@ -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());
}
Expand Down Expand Up @@ -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,
];
}

Expand Down
30 changes: 15 additions & 15 deletions src/Console/Commands/BassetCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ class BassetCache extends Command
*/
public function handle(): void
{
$internalized = [];
$failedToInternalize = [];
$internalizedAssets = [];
$notInternalizedAssets = [];

$starttime = microtime(true);

Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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;
}
Expand All @@ -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()) {
Expand All @@ -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);
Expand Down
17 changes: 11 additions & 6 deletions src/Console/Commands/BassetInstall.php
Original file line number Diff line number Diff line change
Expand Up @@ -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, '<fg=yellow;options=bold>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);
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
21 changes: 16 additions & 5 deletions src/Helpers/CacheEntry.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,24 +85,35 @@ 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);
}

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,
];
}

Expand Down
13 changes: 8 additions & 5 deletions src/Helpers/FileOutput.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,17 +35,18 @@ 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('.');

// map extensions
$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
};

Expand All @@ -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),

Check failure on line 60 in src/Helpers/FileOutput.php

View workflow job for this annotation

GitHub Actions / PHP 8.1 / Laravel ^10.15

Method Backpack\Basset\Helpers\FileOutput::assetPath() invoked with 2 parameters, 1 required.

Check failure on line 60 in src/Helpers/FileOutput.php

View workflow job for this annotation

GitHub Actions / PHP 8.2 / Laravel ^10.15

Method Backpack\Basset\Helpers\FileOutput::assetPath() invoked with 2 parameters, 1 required.
'args' => $this->prepareAttributes($asset->getAttributes()),
]);
}
Expand All @@ -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(''))) {
Expand Down
2 changes: 1 addition & 1 deletion src/AssetOverwrite.php → src/OverridesAssets.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace Backpack\Basset;

interface AssetOverwrite
interface OverridesAssets
{
public function assets(): void;
}
Loading

0 comments on commit b88a1b5

Please sign in to comment.