BookStack/app/Exports/ZipExports/ZipExportValidator.php

60 lines
1.8 KiB
PHP
Raw Normal View History

2024-10-30 21:13:41 +08:00
<?php
namespace BookStack\Exports\ZipExports;
use BookStack\Exceptions\ZipExportException;
use BookStack\Exports\ZipExports\Models\ZipExportBook;
use BookStack\Exports\ZipExports\Models\ZipExportChapter;
use BookStack\Exports\ZipExports\Models\ZipExportPage;
2024-10-30 21:13:41 +08:00
class ZipExportValidator
{
public function __construct(
protected string $zipPath,
) {
}
public function validate(): array
2024-10-30 21:13:41 +08:00
{
$reader = new ZipExportReader($this->zipPath);
try {
$importData = $reader->readData();
} catch (ZipExportException $exception) {
return ['format' => $exception->getMessage()];
2024-10-30 21:13:41 +08:00
}
$helper = new ZipValidationHelper($reader);
2024-10-30 21:13:41 +08:00
if (isset($importData['book'])) {
$modelErrors = ZipExportBook::validate($helper, $importData['book']);
$keyPrefix = 'book';
2024-10-30 21:13:41 +08:00
} else if (isset($importData['chapter'])) {
$modelErrors = ZipExportChapter::validate($helper, $importData['chapter']);
$keyPrefix = 'chapter';
2024-10-30 21:13:41 +08:00
} else if (isset($importData['page'])) {
$modelErrors = ZipExportPage::validate($helper, $importData['page']);
$keyPrefix = 'page';
2024-10-30 21:13:41 +08:00
} else {
return ['format' => trans('errors.import_zip_no_data')];
2024-10-30 21:13:41 +08:00
}
return $this->flattenModelErrors($modelErrors, $keyPrefix);
2024-10-30 21:13:41 +08:00
}
protected function flattenModelErrors(array $errors, string $keyPrefix): array
2024-10-30 21:13:41 +08:00
{
$flattened = [];
foreach ($errors as $key => $error) {
if (is_array($error)) {
$flattened = array_merge($flattened, $this->flattenModelErrors($error, $keyPrefix . '.' . $key));
} else {
$flattened[$keyPrefix . '.' . $key] = $error;
}
}
return $flattened;
2024-10-30 21:13:41 +08:00
}
}