Create article-block-helper.php
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
/**
|
||||
* Baut die Blockliste aus den POST-Daten (blocks[i][type], blocks[i][text],
|
||||
* blocks[i][existing_image]) und ggf. hochgeladenen Dateien (blocks[i][image])
|
||||
* zusammen. Läuft bei JEDEM Submit (Zwischen-Schritt "Block hinzufügen/löschen"
|
||||
* UND finales Speichern/Veröffentlichen), damit neu ausgewählte Bilder in jedem
|
||||
* Fall persistiert werden, bevor PHP die temporäre Upload-Datei nach
|
||||
* Request-Ende verwirft.
|
||||
*
|
||||
* Wird sowohl vom createArticle- als auch vom updateArticle-Controller genutzt.
|
||||
*
|
||||
* @param array $postBlocks $_POST['blocks'] ?? []
|
||||
* @param array $fileBlocks $_FILES['blocks'] ?? []
|
||||
* @param string $uploadDir absoluter Pfad zum uploads-Verzeichnis (mit trailing slash)
|
||||
* @return array Liste von ['type' => 'text'|'image', 'value' => string]
|
||||
*/
|
||||
function rebuildBlocksFromPost(array $postBlocks, array $fileBlocks, string $uploadDir): array {
|
||||
$allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
|
||||
|
||||
$keys = array_keys($postBlocks);
|
||||
if (isset($fileBlocks['name']) && is_array($fileBlocks['name'])) {
|
||||
$keys = array_unique(array_merge($keys, array_keys($fileBlocks['name'])));
|
||||
}
|
||||
sort($keys, SORT_NUMERIC);
|
||||
|
||||
$blocks = [];
|
||||
|
||||
foreach ($keys as $key) {
|
||||
$type = $postBlocks[$key]['type'] ?? null;
|
||||
|
||||
if ($type === 'text') {
|
||||
$blocks[] = [
|
||||
'type' => 'text',
|
||||
'value' => $postBlocks[$key]['text'] ?? '',
|
||||
];
|
||||
} elseif ($type === 'image') {
|
||||
// Vorbelegung: bereits vorhandenes Server-Bild (falls Datei nicht ersetzt wird)
|
||||
$value = $postBlocks[$key]['existing_image'] ?? '';
|
||||
|
||||
$hasUpload = isset($fileBlocks['error'][$key]['image'])
|
||||
&& $fileBlocks['error'][$key]['image'] === UPLOAD_ERR_OK;
|
||||
|
||||
if ($hasUpload) {
|
||||
$tmpName = $fileBlocks['tmp_name'][$key]['image'];
|
||||
$originalName = $fileBlocks['name'][$key]['image'];
|
||||
$extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
|
||||
if (!in_array($extension, $allowedExtensions, true)) {
|
||||
$extension = 'jpg';
|
||||
}
|
||||
|
||||
$fileName = 'img_' . uniqid() . '.' . $extension;
|
||||
$destination = $uploadDir . $fileName;
|
||||
|
||||
if (move_uploaded_file($tmpName, $destination)) {
|
||||
$value = 'uploads/' . $fileName;
|
||||
}
|
||||
// Bei Fehler: alter Wert (falls vorhanden) bleibt erhalten, Block wird nicht verworfen
|
||||
}
|
||||
|
||||
$blocks[] = [
|
||||
'type' => 'image',
|
||||
'value' => $value,
|
||||
];
|
||||
}
|
||||
// unbekannter/fehlender type -> Block wird ignoriert
|
||||
}
|
||||
|
||||
return $blocks;
|
||||
}
|
||||
Reference in New Issue
Block a user