$plan * @param array $changes * @return array */ public static function apply(array $plan, array $changes): 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']); } // Header and footer: a new variant and/or some content fields. foreach (['header', 'footer'] as $part) { if (is_array($changes[$part] ?? null) && is_array($plan[$part] ?? null)) { $plan[$part] = self::merge($plan[$part], $changes[$part]); } } $pages = array_values(array_filter($plan['pages'] ?? [], 'is_array')); $remove = array_filter(self::list($changes, 'remove'), 'is_string'); $order = array_values(array_filter(self::list($changes, 'order'), 'is_string')); foreach ($pages as $pageIndex => $page) { $sections = array_values(array_filter($page['sections'] ?? [], 'is_array')); // Update: change the variant and/or some content fields of existing sections. foreach (self::list($changes, 'update') as $update) { foreach ($sections as $index => $section) { if (is_array($update) && ($section['id'] ?? null) === ($update['id'] ?? null)) { $sections[$index] = self::merge($section, $update); } } } // 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 of the named page (the home page if none is named). foreach (self::list($changes, 'add') as $addition) { $section = is_array($addition) ? ($addition['section'] ?? null) : null; if (! is_array($section) || ($addition['page'] ?? PlanSchema::HOME_PAGE) !== ($page['id'] ?? null)) { 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 on the page whose sections it names exactly once each. $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); } $pages[$pageIndex]['sections'] = $sections; } $plan['pages'] = $pages; return $plan; } /** * Take a new variant and replace only the content fields that were given. * * @param array $section * @param array $update * @return array */ private static function merge(array $section, array $update): array { if (is_string($update['variant'] ?? null)) { $section['variant'] = $update['variant']; } if (is_array($update['content'] ?? null)) { $section['content'] = array_replace($section['content'] ?? [], $update['content']); } return $section; } /** * @param array $changes * @return array */ private static function list(array $changes, string $key): array { return is_array($changes[$key] ?? null) ? $changes[$key] : []; } }