$plan * @return array * * @throws ValidationException */ public function validate(array $plan): array { $rules = [ 'version' => ['required', 'integer', Rule::in([PlanSchema::VERSION])], 'theme' => ['required', 'array'], 'theme.colors' => ['required', 'array'], 'theme.fonts' => ['required', 'array'], 'theme.fonts.heading' => ['required', Rule::in(array_keys(PlanSchema::FONTS))], 'theme.fonts.body' => ['required', Rule::in(array_keys(PlanSchema::FONTS))], 'theme.radius' => ['required', Rule::in(PlanSchema::RADII)], 'sections' => ['required', 'array', 'min:1', 'max:'.PlanSchema::MAX_SECTIONS], 'sections.*' => ['required', 'array'], 'sections.*.id' => ['required', 'string', 'distinct', 'regex:'.PlanSchema::SECTION_ID_PATTERN], 'sections.*.type' => ['required', Rule::in(array_keys(PlanSchema::SECTIONS))], 'sections.*.content' => ['required', 'array'], ]; foreach (PlanSchema::COLORS as $color) { $rules['theme.colors.'.$color] = ['required', 'string', 'regex:'.PlanSchema::COLOR_PATTERN]; } // Each section gets rules that depend on its own type. foreach ($this->sections($plan) as $index => $section) { $type = is_array($section) ? ($section['type'] ?? null) : null; if (! is_string($type) || ! isset(PlanSchema::SECTIONS[$type])) { continue; } $rules["sections.$index.variant"] = ['required', Rule::in(PlanSchema::SECTIONS[$type])]; foreach (PlanSchema::contentRules($type) as $field => $fieldRules) { $rules["sections.$index.content.$field"] = array_map( fn (string $rule) => $this->qualify($rule, "sections.$index.content."), $fieldRules, ); } } /** @var array $clean */ $clean = Validator::make($plan, $rules)->validate(); return $clean; } /** * Whether the plan is valid, without throwing. * * @param array $plan */ public function passes(array $plan): bool { try { $this->validate($plan); return true; } catch (ValidationException) { return false; } } /** * @param array $plan * @return array */ private function sections(array $plan): array { return is_array($plan['sections'] ?? null) ? $plan['sections'] : []; } /** * Rules such as "required_with:cta" name another field. Point them at the full path. */ private function qualify(string $rule, string $prefix): string { if (str_starts_with($rule, 'required_with:')) { return 'required_with:'.$prefix.substr($rule, strlen('required_with:')); } return $rule; } }