| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197 |
- <?php
-
- namespace App\StorePlan;
-
- use Illuminate\Support\Facades\Validator;
- use Illuminate\Validation\Rule;
- use Illuminate\Validation\ValidationException;
-
- /**
- * Checks that a store plan follows PlanSchema, and strips anything the schema does not know.
- *
- * Every plan passes through here before it is saved, no matter who wrote it.
- * This is what stops a weak or misbehaving AI model from breaking a store.
- */
- final class PlanValidator
- {
- /**
- * Return the cleaned plan, or throw if it is not valid.
- *
- * @param array<mixed> $plan
- * @return array<string, mixed>
- *
- * @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)],
- 'pages' => ['required', 'array', 'min:1', 'max:'.PlanSchema::MAX_PAGES],
- 'pages.*' => ['required', 'array'],
- 'pages.*.id' => ['required', 'string', 'distinct', 'regex:'.PlanSchema::SECTION_ID_PATTERN, Rule::notIn(PlanSchema::RESERVED_PAGE_IDS)],
- 'pages.*.title' => ['required', 'string', 'max:60'],
- 'pages.*.sections' => ['required', 'array', 'min:1', 'max:'.PlanSchema::MAX_SECTIONS],
- 'pages.*.sections.*' => ['required', 'array'],
- 'pages.*.sections.*.id' => ['required', 'string', 'regex:'.PlanSchema::SECTION_ID_PATTERN],
- 'pages.*.sections.*.type' => ['required', Rule::in(array_keys(PlanSchema::pageSections()))],
- 'pages.*.sections.*.content' => ['required', 'array'],
- // The first page is always the home page.
- 'pages.0.id' => ['required', Rule::in([PlanSchema::HOME_PAGE])],
- ];
-
- foreach (PlanSchema::COLORS as $color) {
- $rules['theme.colors.'.$color] = ['required', 'string', 'regex:'.PlanSchema::COLOR_PATTERN];
- }
-
- // The header and footer are shared by every page.
- foreach (['header', 'footer'] as $part) {
- $rules[$part] = ['required', 'array'];
- $rules["$part.content"] = ['required', 'array'];
- $rules += $this->sectionRules($part, $part);
- }
-
- // Each section gets rules that depend on its own type.
- foreach ($this->list($plan, 'pages') as $pageIndex => $page) {
- foreach ($this->list($page, 'sections') as $sectionIndex => $section) {
- $type = is_array($section) ? ($section['type'] ?? null) : null;
-
- if (is_string($type) && isset(PlanSchema::pageSections()[$type])) {
- $rules += $this->sectionRules($type, "pages.$pageIndex.sections.$sectionIndex");
- }
- }
- }
-
- /** @var array<string, mixed> $clean */
- $clean = Validator::make($plan, $rules)->validate();
-
- $this->assertSectionIdsAreUnique($clean);
- $this->assertInternalLinksExist($clean);
-
- return $clean;
- }
-
- /**
- * Whether the plan is valid, without throwing.
- *
- * @param array<mixed> $plan
- */
- public function passes(array $plan): bool
- {
- try {
- $this->validate($plan);
-
- return true;
- } catch (ValidationException) {
- return false;
- }
- }
-
- /**
- * The variant and content rules for one section, placed at the given path in the plan.
- *
- * @return array<string, list<mixed>>
- */
- private function sectionRules(string $type, string $path): array
- {
- $rules = ["$path.variant" => ['required', Rule::in(PlanSchema::SECTIONS[$type])]];
-
- foreach (PlanSchema::contentRules($type) as $field => $fieldRules) {
- $rules["$path.content.$field"] = array_map(
- fn (string $rule) => $this->qualify($rule, "$path.content."),
- $fieldRules,
- );
- }
-
- return $rules;
- }
-
- /**
- * A section id must be unique across the whole plan, so links and chat edits can name one section.
- *
- * @param array<string, mixed> $plan
- *
- * @throws ValidationException
- */
- private function assertSectionIdsAreUnique(array $plan): void
- {
- $seen = [];
-
- foreach ($plan['pages'] as $pageIndex => $page) {
- foreach ($page['sections'] as $sectionIndex => $section) {
- if (isset($seen[$section['id']])) {
- throw ValidationException::withMessages([
- "pages.$pageIndex.sections.$sectionIndex.id" => "The section id [{$section['id']}] is used more than once. Every section id must be unique in the whole plan.",
- ]);
- }
-
- $seen[$section['id']] = true;
- }
- }
- }
-
- /**
- * A link such as "/about" must point to a page of this plan or to one of the store's own pages.
- * This catches a menu link to a page that was never created or was removed.
- *
- * @param array<string, mixed> $plan
- *
- * @throws ValidationException
- */
- private function assertInternalLinksExist(array $plan): void
- {
- $known = [...array_column($plan['pages'], 'id'), ...PlanSchema::BUILT_IN_PATHS];
-
- $check = function (mixed $value, string $path) use (&$check, $known): void {
- if (! is_array($value)) {
- return;
- }
-
- foreach ($value as $key => $item) {
- $itemPath = $path === '' ? (string) $key : $path.'.'.$key;
-
- if ($key === 'href' && is_string($item) && str_starts_with($item, '/') && $item !== '/') {
- $first = explode('/', ltrim(strtok($item, '?#') ?: '', '/'))[0];
-
- if (! in_array($first, $known, true)) {
- throw ValidationException::withMessages([
- $itemPath => "The link [$item] points to a page that does not exist. Use the id of a page in this plan, or /shop.",
- ]);
- }
- }
-
- $check($item, $itemPath);
- }
- };
-
- $check($plan, '');
- }
-
- /**
- * @return array<mixed>
- */
- private function list(mixed $value, string $key): array
- {
- return is_array($value) && is_array($value[$key] ?? null) ? $value[$key] : [];
- }
-
- /**
- * Rules such as "required_with:cta" or "required_if:items.*.kind,custom" name another field.
- * Point them at the full path.
- */
- private function qualify(string $rule, string $prefix): string
- {
- foreach (['required_with:', 'required_if:'] as $name) {
- if (str_starts_with($rule, $name)) {
- return $name.$prefix.substr($rule, strlen($name));
- }
- }
-
- return $rule;
- }
- }
|