path((string) $this->import->filename); $spreadsheet = (new Xlsx)->load($path); $sheet = $spreadsheet->getActiveSheet(); $this->assertHeaders($sheet->rangeToArray('A1:S1', null, true, true, false)[0]); $drawings = $this->drawingsByRow($sheet->getDrawingCollection()); $created = 0; $updated = 0; $errors = 0; for ($row = 2; $row <= $sheet->getHighestDataRow(); $row++) { $article = $this->stringValue($sheet->getCell("C{$row}")->getFormattedValue()); if ($article === null) { continue; } $data = [ 'article' => $article, 'calculator_name' => $this->stringValue($sheet->getCell("D{$row}")->getValue()), 'kind' => $this->stringValue($sheet->getCell("E{$row}")->getValue()), 'dimensions' => $this->stringValue($sheet->getCell("F{$row}")->getValue()), 'fall_height' => $this->numericValue($sheet->getCell("G{$row}")->getCalculatedValue()), 'additional_info' => $this->stringValue($sheet->getCell("H{$row}")->getValue()), 'dimension_unit' => $this->stringValue($sheet->getCell("I{$row}")->getValue()), 'weight' => $this->numericValue($sheet->getCell("J{$row}")->getCalculatedValue()), 'volume' => $this->numericValue($sheet->getCell("K{$row}")->getCalculatedValue()), 'places' => $this->integerValue($sheet->getCell("L{$row}")->getCalculatedValue()), 'composition' => $this->stringValue($sheet->getCell("M{$row}")->getValue()), 'age_group' => $this->stringValue($sheet->getCell("N{$row}")->getFormattedValue()), 'max_users' => $this->integerValue($sheet->getCell("O{$row}")->getCalculatedValue()), 'unit' => $this->stringValue($sheet->getCell("P{$row}")->getValue()), 'series' => $this->stringValue($sheet->getCell("Q{$row}")->getValue()), 'trademark' => $this->stringValue($sheet->getCell("R{$row}")->getValue()), 'note' => $this->stringValue($sheet->getCell("S{$row}")->getValue()), ]; $validator = Validator::make($data, $this->rules()); if ($validator->fails()) { $errors++; $this->import->log( "Строка {$row}: ".implode(' ', $validator->errors()->all()), 'WARNING', ); continue; } $item = CommonCatalogItem::query()->where('article', $article)->first(); if ($item) { $item->update($validator->validated()); $updated++; } else { $item = CommonCatalogItem::query()->create($validator->validated()); $created++; } if (isset($drawings[$row])) { try { $this->replaceImage($item, $drawings[$row]); } catch (Throwable $exception) { $errors++; $this->import->log( "Строка {$row}: изображение не импортировано ({$exception->getMessage()}).", 'WARNING', ); } } } $this->import->log("Создано: {$created}; обновлено: {$updated}; ошибок: {$errors}."); $this->import->status = 'DONE'; $this->import->save(); $spreadsheet->disconnectWorksheets(); return true; } catch (Throwable $exception) { $this->import->log($exception->getMessage(), 'ERROR'); $this->import->status = 'ERROR'; $this->import->save(); throw $exception; } } private function assertHeaders(array $headers): void { $actual = array_map($this->normalizeHeader(...), $headers); $expected = array_map($this->normalizeHeader(...), ExportCommonCatalogService::HEADERS); if ($actual !== $expected) { throw new RuntimeException('Некорректные заголовки файла общего каталога. Используйте утверждённый шаблон.'); } } /** @param iterable $drawings */ private function drawingsByRow(iterable $drawings): array { $result = []; foreach ($drawings as $drawing) { if (preg_match('/^B(\d+)$/i', $drawing->getCoordinates(), $matches) === 1) { $result[(int) $matches[1]] = $drawing; } } return $result; } private function replaceImage(CommonCatalogItem $item, BaseDrawing $drawing): void { [$contents, $mimeType, $extension] = $this->drawingContents($drawing); $relativePath = "common_catalog/items/{$item->id}/image/".Str::uuid().".{$extension}"; Storage::disk('public')->put($relativePath, $contents); $newImage = File::query()->create([ 'user_id' => $this->userId, 'original_name' => "{$item->article}.{$extension}", 'mime_type' => $mimeType, 'path' => $relativePath, 'link' => url('/storage/'.$relativePath), ]); app(FileService::class)->ensureThumbnail($newImage); $oldImage = $item->imageFile; $item->update(['image_file_id' => $newImage->id]); if ($oldImage) { app(FileService::class)->deleteFileWithThumbnail($oldImage); $oldImage->delete(); } } private function drawingContents(BaseDrawing $drawing): array { if ($drawing instanceof MemoryDrawing) { ob_start(); ($drawing->getRenderingFunction())($drawing->getImageResource()); $contents = ob_get_clean(); $mimeType = $drawing->getMimeType(); } elseif ($drawing instanceof Drawing) { $contents = file_get_contents($drawing->getPath()); $mimeType = $this->mimeType($contents ?: ''); } else { throw new RuntimeException('Неподдерживаемый формат изображения.'); } if (! is_string($contents) || $contents === '') { throw new RuntimeException('Пустое изображение.'); } $extension = match ($mimeType) { 'image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp', default => throw new RuntimeException("Неподдерживаемый MIME-тип {$mimeType}"), }; return [$contents, $mimeType, $extension]; } private function mimeType(string $contents): string { $info = new \finfo(FILEINFO_MIME_TYPE); return (string) $info->buffer($contents); } private function normalizeHeader(mixed $value): string { return trim((string) preg_replace('/\s+/u', ' ', (string) $value)); } private function stringValue(mixed $value): ?string { $value = trim((string) $value); return $value === '' ? null : $value; } private function numericValue(mixed $value): int|float|string|null { $value = $this->stringValue($value); if ($value === null) { return null; } return str_replace([' ', ','], ['', '.'], $value); } private function integerValue(mixed $value): int|string|null { $value = $this->numericValue($value); if ($value === null) { return null; } return is_numeric($value) ? (int) $value : (string) $value; } private function rules(): array { return [ 'article' => ['required', 'string', 'max:100'], 'calculator_name' => ['required', 'string'], 'kind' => ['nullable', 'string', 'max:255'], 'dimensions' => ['nullable', 'string'], 'fall_height' => ['nullable', 'numeric', 'min:0'], 'additional_info' => ['nullable', 'string'], 'dimension_unit' => ['nullable', 'string', 'max:50'], 'weight' => ['nullable', 'numeric', 'min:0'], 'volume' => ['nullable', 'numeric', 'min:0'], 'places' => ['nullable', 'integer', 'min:0'], 'composition' => ['nullable', 'string'], 'age_group' => ['nullable', 'string', 'max:100'], 'max_users' => ['nullable', 'integer', 'min:0'], 'unit' => ['nullable', 'string', 'max:50'], 'series' => ['nullable', 'string', 'max:255'], 'trademark' => ['nullable', 'string', 'max:255'], 'note' => ['nullable', 'string'], ]; } }