| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- <?php
-
- namespace App\StorePlan\Ai;
-
- /**
- * Applies the small "what to change" answer of a chat edit to an existing plan.
- *
- * The result is not trusted here. PlanWriter runs it through PlanValidator afterwards,
- * so a bad change is rejected instead of saved.
- */
- final class PlanChanges
- {
- /**
- * @param array<string, mixed> $plan
- * @param array<string, mixed> $changes
- * @return array<string, mixed>
- */
- public static function apply(array $plan, array $changes): array
- {
- $sections = array_values(array_filter($plan['sections'] ?? [], 'is_array'));
-
- // Theme: merge only the parts that were given.
- if (is_array($changes['theme'] ?? null) && is_array($plan['theme'] ?? null)) {
- $plan['theme'] = array_replace_recursive($plan['theme'], $changes['theme']);
- }
-
- // Update: change the variant and/or some content fields of existing sections.
- foreach (self::list($changes, 'update') as $update) {
- if (! is_array($update)) {
- continue;
- }
-
- foreach ($sections as $index => $section) {
- if (($section['id'] ?? null) !== ($update['id'] ?? null)) {
- continue;
- }
-
- if (is_string($update['variant'] ?? null)) {
- $sections[$index]['variant'] = $update['variant'];
- }
-
- if (is_array($update['content'] ?? null)) {
- $sections[$index]['content'] = array_replace($section['content'] ?? [], $update['content']);
- }
- }
- }
-
- // Remove.
- $remove = array_filter(self::list($changes, 'remove'), 'is_string');
-
- if ($remove !== []) {
- $sections = array_values(array_filter(
- $sections,
- fn (array $section) => ! in_array($section['id'] ?? null, $remove, true),
- ));
- }
-
- // Add: after a named section, or at the end.
- foreach (self::list($changes, 'add') as $addition) {
- $section = is_array($addition) ? ($addition['section'] ?? null) : null;
-
- if (! is_array($section)) {
- continue;
- }
-
- $position = count($sections);
-
- foreach ($sections as $index => $existing) {
- if (($existing['id'] ?? null) === ($addition['after'] ?? null)) {
- $position = $index + 1;
- }
- }
-
- array_splice($sections, $position, 0, [$section]);
- }
-
- // Order: only used when it names every section exactly once.
- $order = array_values(array_filter(self::list($changes, 'order'), 'is_string'));
- $ids = array_column($sections, 'id');
-
- if ($order !== [] && count($order) === count($ids) && array_diff($ids, $order) === [] && array_diff($order, $ids) === []) {
- $byId = array_column($sections, null, 'id');
- $sections = array_map(fn (string $id) => $byId[$id], $order);
- }
-
- $plan['sections'] = $sections;
-
- return $plan;
- }
-
- /**
- * @param array<string, mixed> $changes
- * @return array<mixed>
- */
- private static function list(array $changes, string $key): array
- {
- return is_array($changes[$key] ?? null) ? $changes[$key] : [];
- }
- }
|