77 lines
2.7 KiB
PHP
77 lines
2.7 KiB
PHP
<?php declare(strict_types=1);
|
|
|
|
namespace App\Services\DocumentationContent;
|
|
|
|
use App\Dto\Service\Admin\Project\DocumentationContent\Content;
|
|
use App\Dto\Service\Admin\Project\DocumentationContent\Contents;
|
|
use App\Dto\Service\DocumentationContent\StorageDto;
|
|
use App\Exceptions\Services\DocumentationContent\ContentSaveException;
|
|
use App\Exceptions\Services\DocumentationContent\StorageCommandException;
|
|
use App\Models\Documentation;
|
|
use App\Models\DocumentationContent;
|
|
use App\Models\Project;
|
|
|
|
final readonly class ModelSyncCommand
|
|
{
|
|
public function __construct(
|
|
private StorageCommand $storageCommand,
|
|
) { }
|
|
|
|
/**
|
|
* @throws StorageCommandException
|
|
* @throws ContentSaveException
|
|
*/
|
|
public function execute(Project $project, Documentation $documentation, Contents $contents): void
|
|
{
|
|
$storageDto = new StorageDto();
|
|
|
|
$languages = $project->languages;
|
|
$documentationContents = $documentation->contents;
|
|
|
|
$newContents = [];
|
|
$contentsStorageCreated = [];
|
|
$contentLanguages = [];
|
|
foreach ($contents->getContents() as $content) {
|
|
/** @var Content $content */
|
|
$language = $languages->firstWhere('id', $content->getLanguageId());
|
|
if (!$language) {
|
|
throw new ContentSaveException('Language not found: ' . $content->getLanguageId());
|
|
}
|
|
|
|
$model = $documentationContents->firstWhere('language_id', $language->id);
|
|
$data = $this->getData($content);
|
|
if (\is_null($model)) {
|
|
$contentsStorageCreated[$content->getLanguageId()] = $content->getStorages();
|
|
$newContents[] = array_merge(['language_id' => $content->getLanguageId()], $data);
|
|
$contentLanguages[] = $content->getLanguageId();
|
|
continue;
|
|
}
|
|
$storageDto->add($model, $content->getStorages());
|
|
$model->update($data);
|
|
}
|
|
|
|
if (!empty($newContents)) {
|
|
$documentation->contents()->createMany($newContents);
|
|
$contents = $documentation->contents()->whereIn('language_id', $contentLanguages)->get();
|
|
foreach ($contents as $content) {
|
|
/** @var DocumentationContent $content */
|
|
if (!isset($contentsStorageCreated[$content->language_id])) {
|
|
continue;
|
|
}
|
|
|
|
$storageDto->add($content, $contentsStorageCreated[$content->language_id]);
|
|
}
|
|
}
|
|
|
|
$this->storageCommand->execute($storageDto);
|
|
}
|
|
|
|
private function getData(Content $content): array
|
|
{
|
|
return [
|
|
'title' => $content->getTitle(),
|
|
'content' => $content->getContent(),
|
|
];
|
|
}
|
|
}
|