AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

PlanValidator.php 7.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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. // Optional: an old plan without it uses PlanSchema::STYLE_DEFAULTS.
  33. 'theme.style' => ['nullable', 'array'],
  34. 'pages' => ['required', 'array', 'min:1', 'max:'.PlanSchema::MAX_PAGES],
  35. 'pages.*' => ['required', 'array'],
  36. 'pages.*.id' => ['required', 'string', 'distinct', 'regex:'.PlanSchema::SECTION_ID_PATTERN, Rule::notIn(PlanSchema::RESERVED_PAGE_IDS)],
  37. 'pages.*.title' => ['required', 'string', 'max:60'],
  38. 'pages.*.sections' => ['required', 'array', 'min:1', 'max:'.PlanSchema::MAX_SECTIONS],
  39. 'pages.*.sections.*' => ['required', 'array'],
  40. 'pages.*.sections.*.id' => ['required', 'string', 'regex:'.PlanSchema::SECTION_ID_PATTERN],
  41. 'pages.*.sections.*.type' => ['required', Rule::in(array_keys(PlanSchema::pageSections()))],
  42. 'pages.*.sections.*.content' => ['required', 'array'],
  43. // The first page is always the home page.
  44. 'pages.0.id' => ['required', Rule::in([PlanSchema::HOME_PAGE])],
  45. ];
  46. // A heading-only font (all capitals or handwriting) would make paragraphs hard to read.
  47. $rules['theme.fonts.body'][] = Rule::notIn(PlanSchema::HEADING_ONLY_FONTS);
  48. foreach (PlanSchema::STYLE_OPTIONS as $option => $values) {
  49. $rules['theme.style.'.$option] = ['nullable', Rule::in($values)];
  50. }
  51. foreach (PlanSchema::COLORS as $color) {
  52. $rules['theme.colors.'.$color] = ['required', 'string', 'regex:'.PlanSchema::COLOR_PATTERN];
  53. }
  54. // The header and footer are shared by every page.
  55. foreach (['header', 'footer'] as $part) {
  56. $rules[$part] = ['required', 'array'];
  57. $rules["$part.content"] = ['required', 'array'];
  58. $rules += $this->sectionRules($part, $part);
  59. }
  60. // Each section gets rules that depend on its own type.
  61. foreach ($this->list($plan, 'pages') as $pageIndex => $page) {
  62. foreach ($this->list($page, 'sections') as $sectionIndex => $section) {
  63. $type = is_array($section) ? ($section['type'] ?? null) : null;
  64. if (is_string($type) && isset(PlanSchema::pageSections()[$type])) {
  65. $rules += $this->sectionRules($type, "pages.$pageIndex.sections.$sectionIndex");
  66. }
  67. }
  68. }
  69. /** @var array<string, mixed> $clean */
  70. $clean = Validator::make($plan, $rules)->validate();
  71. $this->assertSectionIdsAreUnique($clean);
  72. $this->assertInternalLinksExist($clean);
  73. return $clean;
  74. }
  75. /**
  76. * Whether the plan is valid, without throwing.
  77. *
  78. * @param array<mixed> $plan
  79. */
  80. public function passes(array $plan): bool
  81. {
  82. try {
  83. $this->validate($plan);
  84. return true;
  85. } catch (ValidationException) {
  86. return false;
  87. }
  88. }
  89. /**
  90. * The variant and content rules for one section, placed at the given path in the plan.
  91. *
  92. * @return array<string, list<mixed>>
  93. */
  94. private function sectionRules(string $type, string $path): array
  95. {
  96. $rules = ["$path.variant" => ['required', Rule::in(PlanSchema::SECTIONS[$type])]];
  97. foreach (PlanSchema::contentRules($type) as $field => $fieldRules) {
  98. $rules["$path.content.$field"] = array_map(
  99. fn (string $rule) => $this->qualify($rule, "$path.content."),
  100. $fieldRules,
  101. );
  102. }
  103. return $rules;
  104. }
  105. /**
  106. * A section id must be unique across the whole plan, so links and chat edits can name one section.
  107. *
  108. * @param array<string, mixed> $plan
  109. *
  110. * @throws ValidationException
  111. */
  112. private function assertSectionIdsAreUnique(array $plan): void
  113. {
  114. $seen = [];
  115. foreach ($plan['pages'] as $pageIndex => $page) {
  116. foreach ($page['sections'] as $sectionIndex => $section) {
  117. if (isset($seen[$section['id']])) {
  118. throw ValidationException::withMessages([
  119. "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.",
  120. ]);
  121. }
  122. $seen[$section['id']] = true;
  123. }
  124. }
  125. }
  126. /**
  127. * A link such as "/about" must point to a page of this plan or to one of the store's own pages.
  128. * This catches a menu link to a page that was never created or was removed.
  129. *
  130. * @param array<string, mixed> $plan
  131. *
  132. * @throws ValidationException
  133. */
  134. private function assertInternalLinksExist(array $plan): void
  135. {
  136. $known = [...array_column($plan['pages'], 'id'), ...PlanSchema::BUILT_IN_PATHS];
  137. $check = function (mixed $value, string $path) use (&$check, $known): void {
  138. if (! is_array($value)) {
  139. return;
  140. }
  141. foreach ($value as $key => $item) {
  142. $itemPath = $path === '' ? (string) $key : $path.'.'.$key;
  143. if ($key === 'href' && is_string($item) && str_starts_with($item, '/') && $item !== '/') {
  144. $first = explode('/', ltrim(strtok($item, '?#') ?: '', '/'))[0];
  145. if (! in_array($first, $known, true)) {
  146. throw ValidationException::withMessages([
  147. $itemPath => "The link [$item] points to a page that does not exist. Use the id of a page in this plan, or /shop.",
  148. ]);
  149. }
  150. }
  151. $check($item, $itemPath);
  152. }
  153. };
  154. $check($plan, '');
  155. }
  156. /**
  157. * @return array<mixed>
  158. */
  159. private function list(mixed $value, string $key): array
  160. {
  161. return is_array($value) && is_array($value[$key] ?? null) ? $value[$key] : [];
  162. }
  163. /**
  164. * Rules such as "required_with:cta" or "required_if:items.*.kind,custom" name another field.
  165. * Point them at the full path.
  166. */
  167. private function qualify(string $rule, string $prefix): string
  168. {
  169. foreach (['required_with:', 'required_if:'] as $name) {
  170. if (str_starts_with($rule, $name)) {
  171. return $name.$prefix.substr($rule, strlen($name));
  172. }
  173. }
  174. return $rule;
  175. }
  176. }