| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- <?php
- declare(strict_types=1);
- // Beispielmigration für ein Projekt mit JSON-Dateien:
- // ergänzt ein neues Feld in allen bestehenden Datensätzen.
- //
- // Idempotent: bereits ergänzte Datensätze bleiben unverändert, damit die
- // Migration nach einem Teilfehler gefahrlos erneut laufen kann.
- return function (array $context): void {
- $file = $context["app_root"] . "/data/products.json";
- if (!is_file($file)) {
- return;
- }
- $data = json_decode((string) file_get_contents($file), true);
- if (!is_array($data)) {
- throw new RuntimeException("products.json ist nicht lesbar oder kein gültiges JSON.");
- }
- $changed = false;
- foreach ($data as $index => $product) {
- if (is_array($product) && !array_key_exists("category_id", $product)) {
- $data[$index]["category_id"] = null;
- $changed = true;
- }
- }
- if (!$changed) {
- return;
- }
- $json = json_encode(
- $data,
- JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
- );
- if ($json === false) {
- throw new RuntimeException("products.json konnte nicht kodiert werden.");
- }
- // Atomar schreiben, damit ein Abbruch keine halbe Datei hinterlässt.
- $tmpFile = $file . ".tmp";
- if (file_put_contents($tmpFile, $json, LOCK_EX) === false || !rename($tmpFile, $file)) {
- @unlink($tmpFile);
- throw new RuntimeException("products.json konnte nicht geschrieben werden.");
- }
- };
|