AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

PlanValidator.php 6.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. <?php
  2. namespace App\StorePlan;
  3. use Illuminate\Support\Facades\Validator;
  4. use Illuminate\Validation\Rule;
  5. use Illuminate\Validation\ValidationException;
  6. /**
  7. * Checks that a store plan follows PlanSchema, and strips anything the schema does not know.
  8. *
  9. * Every plan passes through here before it is saved, no matter who wrote it.
  10. * This is what stops a weak or misbehaving AI model from breaking a store.
  11. */
  12. final class PlanValidator
  13. {
  14. /**
  15. * Return the cleaned plan, or throw if it is not valid.
  16. *
  17. * @param array<mixed> $plan
  18. * @return array<string, mixed>
  19. *
  20. * @throws ValidationException
  21. */
  22. public function validate(array $plan): array
  23. {
  24. $rules = [
  25. 'version' => ['required', 'integer', Rule::in([PlanSchema::VERSION])],
  26. 'theme' => ['required', 'array'],
  27. 'theme.colors' => ['required', 'array'],
  28. 'theme.fonts' => ['required', 'array'],
  29. 'theme.fonts.heading' => ['required', Rule::in(array_keys(PlanSchema::FONTS))],
  30. 'theme.fonts.body' => ['required', Rule::in(array_keys(PlanSchema::FONTS))],
  31. 'theme.radius' => ['required', Rule::in(PlanSchema::RADII)],
  32. 'pages' => ['required', 'array', 'min:1', 'max:'.PlanSchema::MAX_PAGES],
  33. 'pages.*' => ['required', 'array'],
  34. 'pages.*.id' => ['required', 'string', 'distinct', 'regex:'.PlanSchema::SECTION_ID_PATTERN, Rule::notIn(PlanSchema::RESERVED_PAGE_IDS)],
  35. 'pages.*.title' => ['required', 'string', 'max:60'],
  36. 'pages.*.sections' => ['required', 'array', 'min:1', 'max:'.PlanSchema::MAX_SECTIONS],
  37. 'pages.*.sections.*' => ['required', 'array'],
  38. 'pages.*.sections.*.id' => ['required', 'string', 'regex:'.PlanSchema::SECTION_ID_PATTERN],
  39. 'pages.*.sections.*.type' => ['required', Rule::in(array_keys(PlanSchema::pageSections()))],
  40. 'pages.*.sections.*.content' => ['required', 'array'],
  41. // The first page is always the home page.
  42. 'pages.0.id' => ['required', Rule::in([PlanSchema::HOME_PAGE])],
  43. ];
  44. foreach (PlanSchema::COLORS as $color) {
  45. $rules['theme.colors.'.$color] = ['required', 'string', 'regex:'.PlanSchema::COLOR_PATTERN];
  46. }
  47. // The header and footer are shared by every page.
  48. foreach (['header', 'footer'] as $part) {
  49. $rules[$part] = ['required', 'array'];
  50. $rules["$part.content"] = ['required', 'array'];
  51. $rules += $this->sectionRules($part, $part);
  52. }
  53. // Each section gets rules that depend on its own type.
  54. foreach ($this->list($plan, 'pages') as $pageIndex => $page) {
  55. foreach ($this->list($page, 'sections') as $sectionIndex => $section) {
  56. $type = is_array($section) ? ($section['type'] ?? null) : null;
  57. if (is_string($type) && isset(PlanSchema::pageSections()[$type])) {
  58. $rules += $this->sectionRules($type, "pages.$pageIndex.sections.$sectionIndex");
  59. }
  60. }
  61. }
  62. /** @var array<string, mixed> $clean */
  63. $clean = Validator::make($plan, $rules)->validate();
  64. $this->assertSectionIdsAreUnique($clean);
  65. $this->assertInternalLinksExist($clean);
  66. return $clean;
  67. }
  68. /**
  69. * Whether the plan is valid, without throwing.
  70. *
  71. * @param array<mixed> $plan
  72. */
  73. public function passes(array $plan): bool
  74. {
  75. try {
  76. $this->validate($plan);
  77. return true;
  78. } catch (ValidationException) {
  79. return false;
  80. }
  81. }
  82. /**
  83. * The variant and content rules for one section, placed at the given path in the plan.
  84. *
  85. * @return array<string, list<mixed>>
  86. */
  87. private function sectionRules(string $type, string $path): array
  88. {
  89. $rules = ["$path.variant" => ['required', Rule::in(PlanSchema::SECTIONS[$type])]];
  90. foreach (PlanSchema::contentRules($type) as $field => $fieldRules) {
  91. $rules["$path.content.$field"] = array_map(
  92. fn (string $rule) => $this->qualify($rule, "$path.content."),
  93. $fieldRules,
  94. );
  95. }
  96. return $rules;
  97. }
  98. /**
  99. * A section id must be unique across the whole plan, so links and chat edits can name one section.
  100. *
  101. * @param array<string, mixed> $plan
  102. *
  103. * @throws ValidationException
  104. */
  105. private function assertSectionIdsAreUnique(array $plan): void
  106. {
  107. $seen = [];
  108. foreach ($plan['pages'] as $pageIndex => $page) {
  109. foreach ($page['sections'] as $sectionIndex => $section) {
  110. if (isset($seen[$section['id']])) {
  111. throw ValidationException::withMessages([
  112. "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.",
  113. ]);
  114. }
  115. $seen[$section['id']] = true;
  116. }
  117. }
  118. }
  119. /**
  120. * A link such as "/about" must point to a page of this plan or to one of the store's own pages.
  121. * This catches a menu link to a page that was never created or was removed.
  122. *
  123. * @param array<string, mixed> $plan
  124. *
  125. * @throws ValidationException
  126. */
  127. private function assertInternalLinksExist(array $plan): void
  128. {
  129. $known = [...array_column($plan['pages'], 'id'), ...PlanSchema::BUILT_IN_PATHS];
  130. $check = function (mixed $value, string $path) use (&$check, $known): void {
  131. if (! is_array($value)) {
  132. return;
  133. }
  134. foreach ($value as $key => $item) {
  135. $itemPath = $path === '' ? (string) $key : $path.'.'.$key;
  136. if ($key === 'href' && is_string($item) && str_starts_with($item, '/') && $item !== '/') {
  137. $first = explode('/', ltrim(strtok($item, '?#') ?: '', '/'))[0];
  138. if (! in_array($first, $known, true)) {
  139. throw ValidationException::withMessages([
  140. $itemPath => "The link [$item] points to a page that does not exist. Use the id of a page in this plan, or /shop.",
  141. ]);
  142. }
  143. }
  144. $check($item, $itemPath);
  145. }
  146. };
  147. $check($plan, '');
  148. }
  149. /**
  150. * @return array<mixed>
  151. */
  152. private function list(mixed $value, string $key): array
  153. {
  154. return is_array($value) && is_array($value[$key] ?? null) ? $value[$key] : [];
  155. }
  156. /**
  157. * Rules such as "required_with:cta" name another field. Point them at the full path.
  158. */
  159. private function qualify(string $rule, string $prefix): string
  160. {
  161. if (str_starts_with($rule, 'required_with:')) {
  162. return 'required_with:'.$prefix.substr($rule, strlen('required_with:'));
  163. }
  164. return $rule;
  165. }
  166. }