Otherwise phpstorm doesn't understand the paths correctly. He thinks that this is not a complete application, but a package. And when creating a class, the namespace indicates “app” with a small letter, but should be “App”.
73 lines
2.8 KiB
PHP
73 lines
2.8 KiB
PHP
<?php declare(strict_types=1);
|
|
|
|
namespace App\Services\Storage;
|
|
|
|
use App\Dto\Service\Storage\Storage;
|
|
use App\Dto\Service\Storage\Storages;
|
|
use App\Enums\Morph;
|
|
use App\Contracts\Models\Storage as ModelStorageContract;
|
|
use App\Repositories\StorageRepository;
|
|
use App\ServiceResults\ServiceResultError;
|
|
use App\ServiceResults\Storage\SaveDeleteStorageResult;
|
|
use App\Services\Service;
|
|
|
|
class StorageService extends Service
|
|
{
|
|
public function __construct(
|
|
private readonly StorageRepository $storageRepository,
|
|
private readonly ValidationService $storageValidation,
|
|
private readonly StorageCommandHandler $storageCommandHandler,
|
|
) { }
|
|
|
|
public function getStoragesAndValidate(Storages $storages, Morph $morph, ?int $modelId = null): ServiceResultError | SaveDeleteStorageResult
|
|
{
|
|
$storageModels = $this->storageRepository->getStoregsByIds($storages->getAllStorageIds())->all();
|
|
$result = new SaveDeleteStorageResult();
|
|
|
|
foreach ($storages->getAllStorages() as $storage) {
|
|
/** @var Storage $storage */
|
|
if ($storage->isDelete()) {
|
|
$result->addDelete($storage);
|
|
continue;
|
|
}
|
|
if (!$storage->isFile()) {
|
|
continue;
|
|
}
|
|
|
|
$storageModel = $storageModels->firstWhere('id', $storage->getFile()->getId());
|
|
if (\is_null($storageModel)) {
|
|
return $this->errValidate(__('storage.File_not_found'));
|
|
}
|
|
$validate = $this->storageValidation->execute($storageModel, $morph, $storage->getStorageType(), $modelId);
|
|
if (!$validate->isSuccess()) {
|
|
return $this->errValidate($validate->getMessage());
|
|
}
|
|
|
|
$result->addSave($storageModel, $storage);
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
public function saveAndDelete(ModelStorageContract $model, SaveDeleteStorageResult $storageResult): void
|
|
{
|
|
foreach ($storageResult->getStoragesForDelete() as $dataStorage) {
|
|
$type = $dataStorage['type'];
|
|
if ($dataStorage['isDeleteType']) {
|
|
$this->storageCommandHandler->handleDestroyByModel($model, $type);
|
|
}
|
|
if ($dataStorage['isDeleteType'] || empty($dataStorage['ids'])) {
|
|
continue;
|
|
}
|
|
$this->storageCommandHandler->handleDestroyByModelStorageIds($model, $dataStorage['ids'], $type);
|
|
}
|
|
foreach ($storageResult->getStoragesForSave() as $dataStorage) {
|
|
$storage = $dataStorage['storage'];
|
|
if ($dataStorage['isMany'] !== true && $storage->morph_id !== $model->id) {
|
|
$this->storageCommandHandler->handleDestroyByModel($model, $storage->type);
|
|
}
|
|
$this->storageCommandHandler->handleStorageAttachModel($storage, $model);
|
|
}
|
|
}
|
|
}
|