Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

правило валидации для Attachment, загруженных ранее полями Upload, Cr… #2745

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
"Orchid\\Filters\\": "src/Filters/",
"Orchid\\Metrics\\": "src/Metrics/",
"Orchid\\Platform\\": "src/Platform/",
"Orchid\\Rule\\": "src/Rule/",
"Orchid\\Screen\\": "src/Screen/",
"Orchid\\Support\\": "src/Support/"
},
Expand Down
108 changes: 108 additions & 0 deletions src/Rule/AttachmentRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
<?php

namespace Orchid\Rule;

use Closure;
use Illuminate\Contracts\Filesystem\Cloud;
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Database\Eloquent\Collection;
use Orchid\Attachment\Models\Attachment;
use Storage;
use Symfony\Component\HttpFoundation\File\File as FileSymfony;

class AttachmentRule implements ValidationRule
{
/** @var Collection<Attachment>} */
protected Collection $attachment;

/**
* @param mixed $rules правила валидации файлов Attachment см. документацию по валидации файлов.
* Например: File::image()->dimensions(Rule::dimensions()->maxWidth(960)->maxHeight(639)) или
* то-же самое 'image|dimensions:min_width=960,min_height=639'
* @param bool $removeFailed удалять или нет файлы, не прошедшие валидацию
*/
public function __construct(protected mixed $rules, protected bool $removeFailed = true)
{
}

/**
* Получение Attachment для валидации
* @param mixed $ids
* @return void
*/
protected function setAttachment(mixed $ids): void
{
$this->attachment = is_array($ids)
? Attachment::whereIn('id', $ids)->get()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нужно использовать модель не напрямую, так как разработчик может её изменить, что бы поддерживать это, достаточно:

$model = Dashboard::model(Attachment::class);

: Attachment::where('id', $ids)->get();

$this->attachment = $this->attachment->mapWithKeys(fn(Attachment $attachment) => ["_{$attachment->id}" => $attachment]);
}

/**
* Получение объекта типа \Symfony\Component\HttpFoundation\File\File из AttachmentModel
*
* @param Attachment $attachment
* @return FileSymfony|null
*/
protected function getFileObjectFromAttachment(Attachment $attachment): ?FileSymfony
{
if ($attachment->exists) {
/** @var Filesystem|Cloud $disk */
$disk = Storage::disk($attachment->disk);
return new FileSymfony($disk->path($attachment->physicalPath()));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это будет работать только с файлами которые находятся на локальной машине, всякие ftp/s3 и т.п. уже вызовут ошибку. Возможно имеет смысл либо скачивать, либо к проверке добавить, что файл доступен.

}

return null;
}

/**
* Генерация валидатора
*
* @return Validator
*/
protected function getValidator(): Validator
{
$data = $this->attachment->mapWithKeys(fn(Attachment $attachment, $key) => [$key => $this->getFileObjectFromAttachment($attachment)])->filter(fn($item) => !empty($item))->toArray();
$rules = $this->attachment->mapWithKeys(fn(Attachment $attachment, $key) => [$key => $this->rules])->toArray();
$attributes = $this->attachment->mapWithKeys(fn(Attachment $attachment, $key) => [$key => $attachment->original_name])->toArray();

return validator(data: $data, rules: $rules, attributes: $attributes);
}

/**
* @param \Illuminate\Support\Collection $errors
* @return void
*/
protected function removeFiles(\Illuminate\Support\Collection $errors): void
{
$errors->each(function ($message, $key) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Думаю, что можем в том же стили как в начале:

$errors->filter(fn($message, $key) => $this->attachment->has($key))
    ->each(fn($message, $key) => $this->attachment->get($key)->delete());

if ($this->attachment->has($key)) {
$this->attachment[$key]->delete();
}
});
}

/**
* Run the validation rule.
*
* @param \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
$this->setAttachment($value);
$validator = $this->getValidator();

if ($validator->fails()) {
$errors = collect($validator->errors()->toArray());

if ($this->removeFailed) {
$this->removeFiles($errors);
}

$fail($errors->flatten()->implode(' '));
}
}
}