-
Notifications
You must be signed in to change notification settings - Fork 232
Open
Description
В конец главы Внедрение зависимостей
Да, код не выглядит столь чистым как в ООП-варианте, но его конфигурация и реализация весьма просты. Для загрузки картинок этот вариант явно оптимальнее, но в других случаях с более сложной конфигурацией или оркестрацией, ООП-вариант будет предпочтительнее.
- Создаём Enum
enum ImageUploadType: string
{
case Avatar = 'avatars';
case Gallery = 'gallery';
public function configKey(): string
{
return 'image.' . $this->value;
}
public function folder(): string
{
return config($this->configKey() . '.folder');
}
public function shouldCheck(): bool
{
return config($this->configKey() . '.check', true);
}
public function isWeak(): bool
{
return config($this->configKey() . '.weak', false);
}
public function shouldBan(): bool
{
return config($this->configKey() . '.ban', true);
}
public function disk(): string
{
return config($this->configKey() . '.disk', config('image.disk'));
}
}- Обновляем ImageUploader::upload():
public function upload(
UploadedFile $file,
User $uploadedBy,
ImageUploadType $type
) {
$fileContent = $file->getContents();
if ($type->shouldCheck()) {
if (!$this->imageGuard->check($fileContent, $type->isWeak())) {
if ($type->shouldBan()) {
$this->listener->handle($uploadedBy);
}
return false;
}
}
$fileName = $type->folder() . 'some_unique_file_name.jpg';
$this->fileSystemManager
->disk($type->disk())
->put($fileName, $fileContent);
return $fileName;
}- Используем
$imageUploader->upload($file, $user, ImageUploadType::Gallery);Что имеем:
- Типобезопасность. Нельзя передать произвольную строку, только enum
- IDE подсказки
- Логика конфигурации находится внутри enum, делая ImageUploader чище
- Можно добавить другие параметры или даже объекты-конфигурации не меняя вызов метода
Metadata
Metadata
Assignees
Labels
No labels