Skip to content

Commit

Permalink
Fix existing asset detection (#73)
Browse files Browse the repository at this point in the history
* Fix existing asset detection

Correctly detect existing assets if a folder is configured.

* Add test

* wip

---------

Co-authored-by: Duncan McClean <[email protected]>
  • Loading branch information
carstenjaksch and duncanmcclean authored Jan 7, 2025
1 parent dc06fd8 commit af6a249
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/Transformers/AssetsTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,13 @@ public function transform(string $value): null|string|array
->trim('/')
->__toString();

$asset = $assetContainer->asset($path);
$assetPath = $path;

if ($this->config('folder')) {
$assetPath = Str::ensureRight($this->config('folder'), '/').Str::afterLast($path, '/');
}

$asset = $assetContainer->asset($assetPath);

if (! $asset && $this->config('download_when_missing') && $relatedField === 'url') {
$request = Http::get(Str::removeRight($baseUrl, '/').Str::ensureLeft($path, '/'));
Expand Down
24 changes: 24 additions & 0 deletions tests/Transformers/AssetsTransformerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,30 @@ public function it_downloads_new_asset_using_url_and_stores_it_in_configured_fol
Storage::disk('public')->assertExists('custom-folder/image.png');
}

#[Test]
public function it_doesnt_downloads_new_asset_when_it_already_exists_in_the_configured_folder()
{
Http::preventStrayRequests();

Storage::disk('public')->put('custom-folder/image.png', 'original');

$transformer = new AssetsTransformer(
import: $this->import,
blueprint: $this->blueprint,
field: $this->field,
config: [
'related_field' => 'url',
'base_url' => 'https://example.com/wp-content/uploads',
'download_when_missing' => true,
'folder' => 'custom-folder',
]
);

$output = $transformer->transform('https://example.com/wp-content/uploads/2024/10/image.png');

$this->assertEquals('custom-folder/image.png', $output);
}

#[Test]
public function it_doesnt_download_new_asset_when_download_when_missing_option_is_disabled()
{
Expand Down

0 comments on commit af6a249

Please sign in to comment.