From 99d6a858cb963cf4face96297b5fa685bbca8ccb Mon Sep 17 00:00:00 2001 From: alexvenga Date: Sat, 8 Apr 2023 15:32:19 +0300 Subject: [PATCH] INIT --- composer.json | 18 ++--------- src/{ => Fields}/MediaLibrary.php | 50 +++++++++++++++++-------------- 2 files changed, 31 insertions(+), 37 deletions(-) rename src/{ => Fields}/MediaLibrary.php (53%) diff --git a/composer.json b/composer.json index 7f34fb5..fd292d6 100644 --- a/composer.json +++ b/composer.json @@ -26,13 +26,11 @@ } ], "require": { - "php": "^8.0|^8.1|^8.2", - "lee-to/moonshine": "@dev", - "laravel/framework": "^9.0|^10.0" + "php": "^8.0|^8.1|^8.2" }, "autoload": { "psr-4": { - "VI\\MoonShine\\Fields\\Spatie\\MediaLibrary\\": "src" + "VI\\MoonShineSpatieMediaLibrary\\": "src" }, "files": [ ] @@ -46,15 +44,5 @@ } }, "minimum-stability": "dev", - "prefer-stable": true, - - "repositories": [ - { - "type": "path", - "url": "/usr/local/var/www/visual-ideas/moonshine", - "options": { - "symlink": true - } - } - ] + "prefer-stable": true } diff --git a/src/MediaLibrary.php b/src/Fields/MediaLibrary.php similarity index 53% rename from src/MediaLibrary.php rename to src/Fields/MediaLibrary.php index 5cb68e5..480c017 100644 --- a/src/MediaLibrary.php +++ b/src/Fields/MediaLibrary.php @@ -1,19 +1,16 @@ isCanSave() && $this->requestValue()) { - if ($this->isMultiple()) { - $item->clearMediaCollection($this->field()); + if ($this->isCanSave()) { + $requestValue = $this->requestValue(); - foreach ($this->requestValue() as $file) { - $item->addMedia($file) - ->preservingOriginal() - ->toMediaCollection($this->field()); + if ($this->isMultiple()) { + $oldValues = collect(request("hidden_{$this->field()}", [])); + + if ($oldValues->count() < $item->getMedia($this->field())->count()) { + foreach ($item->getMedia($this->field()) as $media) { + if (!$oldValues->contains($media->getUrl())) { + $media->delete(); + } + } + } + if ($requestValue) { + foreach ($requestValue as $file) { + $item->addMedia($file) + ->preservingOriginal() + ->toMediaCollection($this->field()); + } } } else { - if ($media = $item->getFirstMedia($this->field())) { - $media->delete(); + if ($requestValue) { + $item->addMedia($requestValue) + ->preservingOriginal() + ->toMediaCollection($this->field()); } - - $item->addMedia($this->requestValue()) - ->preservingOriginal() - ->toMediaCollection($this->field()); } } } @@ -63,11 +69,11 @@ public function indexViewValue(Model $item, bool $container = true): string ])->render(); } - public function formViewValue(Model $item): mixed + public function formViewValue(Model $item): Collection|string { if ($this->isMultiple()) { return $item->getMedia($this->field()) - ->map(fn ($value) => $value->getUrl())->toArray(); + ->map(fn($value) => $value->getUrl()); } return $item->getFirstMediaUrl($this->field());