Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion docs/guide/form-fields/upload.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ Set the destination base storage path.
If you want to use a `{id}` special placeholder to add the instance id in the path (for instance: `$field->setStorageBasePath('/users/{id}/avatar')`), you must be the Eloquent case, leveraging `Code16\Sharp\Form\Eloquent\WithSharpFormEloquentUpdater` (see [Eloquent form](../building-form#eloquent-case-where-the-magic-happens))
:::

### `setStorageTemporary()`

Keep the file only in the upload directory/disk (configured [here](#general-configuration)). `setStorageDisk()` and `setStorageBasePath()` will be ignored.

### `setAllowedExtensions(string|array $allowedExtensions)`

Define the allowed file extensions.
Expand Down Expand Up @@ -246,4 +250,4 @@ class SharpServiceProvider extends SharpAppServiceProvider
}
```

Queue and connection should be [properly configured](https://laravel.com/docs/queues).
Queue and connection should be [properly configured](https://laravel.com/docs/queues).
11 changes: 10 additions & 1 deletion src/Form/Fields/Editor/Uploads/SharpFormEditorUpload.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Code16\Sharp\Form\Fields\Editor\Uploads;

use Code16\Sharp\Exceptions\SharpInvalidConfigException;
use Code16\Sharp\Form\Fields\Formatters\UploadFormatter;
use Code16\Sharp\Form\Fields\SharpFormUploadField;

Expand All @@ -13,7 +14,15 @@ public static function make(?string $key = 'file'): self
{
return new static($key, 'upload', app(UploadFormatter::class));
}


/**
* @throws SharpInvalidConfigException
*/
public function setStorageTemporary(): SharpFormUploadField
{
throw new SharpInvalidConfigException('Temporary storage is not available for editor uploads');
}

public function setHasLegend(bool $hasLegend = true): self
{
$this->hasLegend = $hasLegend;
Expand Down
36 changes: 20 additions & 16 deletions src/Form/Fields/Formatters/UploadFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,31 +31,35 @@ public function fromFront(SharpFormField $field, string $attribute, $value): ?ar
);

return tap($this->normalizeFromFront($value, [
'file_name' => sprintf(
'%s/%s',
str($field->storageBasePath())->replace('{id}', $this->instanceId ?? '{id}'),
app(FileUtil::class)->findAvailableName(
$value['name'], $field->storageBasePath(), $field->storageDisk(),
'file_name' => $field->storageDisk()
? sprintf(
'%s/%s',
str($field->storageBasePath())->replace('{id}', $this->instanceId ?? '{id}'),
app(FileUtil::class)->findAvailableName(
$value['name'], $field->storageBasePath(), $field->storageDisk(),
)
)
),
: $uploadedFieldRelativePath,
'size' => Storage::disk(sharp()->config()->get('uploads.tmp_disk'))
->size($uploadedFieldRelativePath),
'mime_type' => Storage::disk(sharp()->config()->get('uploads.tmp_disk'))
->mimeType($uploadedFieldRelativePath),
'disk' => $field->storageDisk(),
'disk' => $field->storageDisk() ?: sharp()->config()->get('uploads.tmp_disk'),
'filters' => $field->isImageTransformOriginal()
? null
: $value['filters'] ?? null,
]), function ($formatted) use ($field, $value) {
app(SharpUploadManager::class)->queueHandleUploadedFile(
uploadedFileName: $value['name'],
disk: $field->storageDisk(),
filePath: $formatted['file_name'],
shouldOptimizeImage: $field->isImageOptimize(),
transformFilters: $field->isImageTransformOriginal()
? ($value['filters'] ?? null)
: null,
);
if($field->storageDisk()) {
app(SharpUploadManager::class)->queueHandleUploadedFile(
uploadedFileName: $value['name'],
disk: $field->storageDisk(),
filePath: $formatted['file_name'],
shouldOptimizeImage: $field->isImageOptimize(),
transformFilters: $field->isImageTransformOriginal()
? ($value['filters'] ?? null)
: null,
);
}
});
}

Expand Down
14 changes: 10 additions & 4 deletions src/Form/Fields/SharpFormUploadField.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,15 @@

use Closure;
use Code16\Sharp\Form\Fields\Formatters\UploadFormatter;
use Code16\Sharp\Form\Fields\Utils\IsUploadField;
use Code16\Sharp\Utils\Fields\Validation\SharpFileValidation;
use Code16\Sharp\Utils\Fields\Validation\SharpImageValidation;
use Illuminate\Validation\Rules\Dimensions;

class SharpFormUploadField extends SharpFormField implements IsUploadField
class SharpFormUploadField extends SharpFormField
{
const FIELD_TYPE = 'upload';

protected string $storageDisk = 'local';
protected ?string $storageDisk = 'local';
protected string|Closure $storageBasePath = 'data';
protected ?float $maxFileSize = null;
protected ?float $minFileSize = null;
Expand Down Expand Up @@ -138,6 +137,13 @@ public function setStorageDisk(string $storageDisk): self

return $this;
}

public function setStorageTemporary(): self
{
$this->storageDisk = null;

return $this;
}

/**
* @param string|(Closure(): string) $storageBasePath
Expand All @@ -157,7 +163,7 @@ public function setAllowedExtensions(string|array $extensions): self
return $this;
}

public function storageDisk(): string
public function storageDisk(): ?string
{
return $this->storageDisk;
}
Expand Down
36 changes: 0 additions & 36 deletions src/Form/Fields/Utils/IsUploadField.php

This file was deleted.

42 changes: 42 additions & 0 deletions tests/Http/Form/HandlesUploadedFilesInRequestTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,48 @@ public function buildFormFields(FieldsContainer $formFields): void
Queue::assertNotPushed(HandleUploadedFileJob::class);
});

it('does not dispatch HandlePostedFilesJob when temporary', function () {
fakeFormFor('person', new class() extends PersonForm
{
public function buildFormFields(FieldsContainer $formFields): void
{
$formFields
->addField(
SharpFormUploadField::make('file')
->setStorageTemporary()
);
}
});

UploadedFile::fake()
->image('image.jpg')
->storeAs('/tmp', 'image.jpg', ['disk' => 'local']);

$this
->post('/sharp/s-list/person/s-form/person/2', [
'name' => 'Stephen Hawking',
'file' => [
'name' => 'image.jpg',
'uploaded' => true,
],
])
->assertSessionHasNoErrors()
->assertRedirect();

$this
->post('/sharp/s-list/person/s-form/person', [
'name' => 'Marie Curie',
'file' => [
'name' => 'image.jpg',
'uploaded' => true,
],
])
->assertSessionHasNoErrors()
->assertRedirect();

Queue::assertNotPushed(HandleUploadedFileJob::class);
});

it('handles isTransformOriginal to transform the image on a newly uploaded file', function ($transformKeepOriginal) {
fakeFormFor('person', new class($transformKeepOriginal) extends PersonForm
{
Expand Down
24 changes: 24 additions & 0 deletions tests/Unit/Form/Fields/Formatters/UploadFormatterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,3 +122,27 @@
],
]);
});

it('format temporary upload from front', function () {
$formatter = app(UploadFormatter::class);

UploadedFile::fake()
->image('image.jpg')
->storeAs('/tmp', 'image.jpg', ['disk' => 'local']);

$field = SharpFormUploadField::make('upload')->setStorageTemporary();

expect(
$formatter
->fromFront($field, 'attr', [
'name' => 'image.jpg',
'uploaded' => true,
])
)
->toEqual([
'file_name' => 'tmp/image.jpg',
'disk' => 'local',
'mime_type' => 'image/jpeg',
'size' => 695,
]);
});
Loading