| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- <?php
- declare(strict_types=1);
- // Example migration for a project with JSON files: adds a new field to
- // every existing record.
- //
- // Idempotent: already-updated records stay unchanged, so the migration can
- // safely run again after a partial failure.
- 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 is not readable or not valid 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 could not be encoded.");
- }
- // Write atomically, so an interruption never leaves a half-written file.
- $tmpFile = $file . ".tmp";
- if (file_put_contents($tmpFile, $json, LOCK_EX) === false || !rename($tmpFile, $file)) {
- @unlink($tmpFile);
- throw new RuntimeException("products.json could not be written.");
- }
- };
|