Skip to content

Beautiful Open-Source Form Builder

Refactor UserFormRequest for improved validation performance

Julien Nahumdd835c3185a1
diff --git a/api/app/Http/Requests/UserFormRequest.php b/api/app/Http/Requests/UserFormRequest.php
index 33ef97acb..3e6e18d6f 100644
--- a/api/app/Http/Requests/UserFormRequest.php
+++ b/api/app/Http/Requests/UserFormRequest.php
@@ -5,8 +5,7 @@ namespace App\Http\Requests;
use App\Http\Requests\Workspace\CustomDomainRequest;
use App\Models\Forms\Form;
use App\Rules\CustomSlugRule;
-use App\Rules\FormPropertyLogicRule;
-use App\Rules\PaymentBlockConfigurationRule;
+use App\Rules\FormPropertiesRule;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
use Illuminate\Contracts\Validation\Validator;
@@ -157,72 +156,9 @@ abstract class UserFormRequest extends \Illuminate\Foundation\Http\FormRequest
'enable_partial_submissions' => 'boolean',
'enable_ip_tracking' => 'boolean',
- // Properties
- 'properties' => 'required|array',
- 'properties.*.id' => 'required',
- 'properties.*.name' => 'required',
- 'properties.*.type' => ['required', new PaymentBlockConfigurationRule($this->properties, $workspace)],
- 'properties.*.placeholder' => 'sometimes|nullable',
- 'properties.*.prefill' => 'sometimes|nullable',
- 'properties.*.help' => 'sometimes|nullable',
- 'properties.*.help_position' => ['sometimes', Rule::in(['below_input', 'above_input'])],
- 'properties.*.hidden' => 'boolean|nullable',
- 'properties.*.required' => 'boolean|nullable',
- 'properties.*.multiple' => 'boolean|nullable',
- 'properties.*.timezone' => 'sometimes|nullable',
- 'properties.*.width' => ['sometimes', Rule::in(['full', '1/2', '1/3', '2/3', '1/3', '3/4', '1/4'])],
- 'properties.*.align' => ['sometimes', Rule::in(['left', 'center', 'right', 'justify'])],
- 'properties.*.allowed_file_types' => 'sometimes|nullable',
- 'properties.*.use_toggle_switch' => 'boolean|nullable',
-
- // Media (Focused mode only)
- 'properties.*.image' => 'sometimes|nullable|array',
- 'properties.*.image.url' => 'sometimes|nullable|url',
- 'properties.*.image.alt' => 'sometimes|nullable|string|max:125',
- 'properties.*.image.layout' => ['sometimes', 'nullable', Rule::in([
- 'between',
- 'left-small',
- 'right-small',
- 'left-split',
- 'right-split',
- 'background'
- ])],
- 'properties.*.image.focal_point' => 'sometimes|nullable|array',
- 'properties.*.image.focal_point.x' => 'sometimes|nullable|numeric|min:0|max:100',
- 'properties.*.image.focal_point.y' => 'sometimes|nullable|numeric|min:0|max:100',
- 'properties.*.image.brightness' => 'sometimes|nullable|integer|min:-100|max:100',
-
- // Logic
- 'properties.*.logic' => ['array', 'nullable', new FormPropertyLogicRule()],
-
- // Form blocks
- 'properties.*.content' => 'sometimes|nullable',
-
- // Text field
- 'properties.*.multi_lines' => 'boolean|nullable',
- 'properties.*.max_char_limit' => 'integer|nullable|min:1',
- 'properties.*.show_char_limit ' => 'boolean|nullable',
- 'properties.*.secret_input' => 'boolean|nullable',
-
- // Date field
- 'properties.*.with_time' => 'boolean|nullable',
- 'properties.*.date_range' => 'boolean|nullable',
- 'properties.*.prefill_today' => 'boolean|nullable',
- 'properties.*.disable_past_dates' => 'boolean|nullable',
- 'properties.*.disable_future_dates' => 'boolean|nullable',
-
- // Select / Multi Select field
- 'properties.*.allow_creation' => 'boolean|nullable',
- 'properties.*.without_dropdown' => 'boolean|nullable',
- 'properties.*.min_selection' => 'integer|nullable|min:0',
- 'properties.*.max_selection' => 'integer|nullable|min:1',
-
- // Advanced Options
- 'properties.*.generates_uuid' => 'boolean|nullable',
- 'properties.*.generates_auto_increment_id' => 'boolean|nullable',
-
- // For file (min and max)
- 'properties.*.max_file_size' => 'min:1|numeric',
+ // Properties - Single-pass validation for performance
+ // Replaces ~35 wildcard rules (properties.*) with one efficient rule
+ 'properties' => ['required', 'array', new FormPropertiesRule($workspace)],
// Security & Privacy
'can_be_indexed' => 'boolean',
@@ -248,10 +184,8 @@ abstract class UserFormRequest extends \Illuminate\Foundation\Http\FormRequest
*/
public function messages()
{
- return [
- 'properties.*.name.required' => 'The form block number :position is missing a name.',
- 'properties.*.type.required' => 'The form block number :position is missing a type.',
- 'properties.*.max_char_limit.min' => 'The form block number :position max character limit must be at least 1 OR Empty'
- ];
+ // Note: Property-specific messages are now handled by FormPropertiesRule
+ // for better performance (single-pass validation)
+ return [];
}
}
diff --git a/api/app/Rules/FormPropertiesRule.php b/api/app/Rules/FormPropertiesRule.php
new file mode 100644
index 000000000..e73ed8dbb
--- /dev/null
+++ b/api/app/Rules/FormPropertiesRule.php
@@ -0,0 +1,122 @@
+<?php
+
+namespace App\Rules;
+
+use App\Models\Workspace;
+use App\Rules\PropertyValidators\CorePropertyValidator;
+use App\Rules\PropertyValidators\LogicPropertyValidator;
+use App\Rules\PropertyValidators\PaymentPropertyValidator;
+use App\Rules\PropertyValidators\PropertyValidatorInterface;
+use App\Rules\PropertyValidators\TypePropertyValidator;
+use Closure;
+use Illuminate\Contracts\Validation\DataAwareRule;
+use Illuminate\Contracts\Validation\ValidationRule;
+use Illuminate\Contracts\Validation\ValidatorAwareRule;
+use Illuminate\Validation\Validator;
+
+/**
+ * Single-pass validation rule for form properties.
+ * Replaces Laravel's wildcard validation (properties.*) with a more efficient
+ * single loop that validates all properties at once.
+ *
+ * This dramatically improves performance for forms with many properties
+ * by avoiding Laravel's validation framework overhead per property.
+ */
+class FormPropertiesRule implements ValidationRule, ValidatorAwareRule, DataAwareRule
+{
+ /**
+ * @var PropertyValidatorInterface[]
+ */
+ private array $validators = [];
+
+ private ?Workspace $workspace;
+
+ private ?Validator $validator = null;
+
+ private array $data = [];
+
+ public function __construct(?Workspace $workspace = null)
+ {
+ $this->workspace = $workspace;
+
+ // Register validators in order of execution
+ $this->validators = [
+ new CorePropertyValidator(),
+ new TypePropertyValidator(),
+ new PaymentPropertyValidator($workspace),
+ new LogicPropertyValidator(),
+ ];
+ }
+
+ /**
+ * Set the current validator.
+ */
+ public function setValidator(Validator $validator): static
+ {
+ $this->validator = $validator;
+ return $this;
+ }
+
+ /**
+ * Set the data under validation.
+ */
+ public function setData(array $data): static
+ {
+ $this->data = $data;
+ return $this;
+ }
+
+ /**
+ * Run the validation rule.
+ *
+ * @param \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail
+ */
+ public function validate(string $attribute, mixed $value, Closure $fail): void
+ {
+ if (!is_array($value)) {
+ $fail('Properties must be an array.');
+ return;
+ }
+
+ $allErrors = [];
+ $context = [
+ 'properties' => $value,
+ 'workspace' => $this->workspace,
+ ];
+
+ // Single pass through all properties
+ foreach ($value as $index => $property) {
+ if (!is_array($property)) {
+ $allErrors["properties.{$index}"] = ["Property at index {$index} must be an array."];
+ continue;
+ }
+
+ // Run each validator on this property
+ foreach ($this->validators as $validator) {
+ $propertyErrors = $validator->validate($property, $index, $context);
+
+ // Collect errors with proper attribute keys
+ foreach ($propertyErrors as $field => $message) {
+ $errorKey = "properties.{$index}.{$field}";
+ if (!isset($allErrors[$errorKey])) {
+ $allErrors[$errorKey] = [];
+ }
+ $allErrors[$errorKey][] = $message;
+ }
+ }
+ }
+
+ // Add errors directly to the validator's message bag
+ // This ensures proper error format matching Laravel's wildcard validation
+ if ($this->validator && !empty($allErrors)) {
+ foreach ($allErrors as $errorKey => $messages) {
+ foreach ($messages as $message) {
+ $this->validator->errors()->add($errorKey, $message);
+ }
+ }
+ // Trigger a generic fail to mark validation as failed
+ // The actual errors are already in the message bag
+ $fail('One or more properties have validation errors.');
+ }
+ }
+}
diff --git a/api/app/Rules/IntegrationLogicRule.php b/api/app/Rules/IntegrationLogicRule.php
index be0a12127..9e6a03375 100644
--- a/api/app/Rules/IntegrationLogicRule.php
+++ b/api/app/Rules/IntegrationLogicRule.php
@@ -2,6 +2,7 @@
namespace App\Rules;
+use App\Rules\PropertyValidators\LogicPropertyValidator;
use Closure;
use Illuminate\Contracts\Validation\DataAwareRule;
use Illuminate\Contracts\Validation\ValidationRule;
@@ -51,7 +52,7 @@ class IntegrationLogicRule implements DataAwareRule, ValidationRule
$operator = $condition['value']['operator'];
// If operator has no format and no expected_type, it means it doesn't need input
- if (!isset(FormPropertyLogicRule::getConditionMapping()[$typeField]['comparators'][$operator]['expected_type'])) {
+ if (!isset(LogicPropertyValidator::getConditionMapping()[$typeField]['comparators'][$operator]['expected_type'])) {
return;
}
@@ -64,21 +65,21 @@ class IntegrationLogicRule implements DataAwareRule, ValidationRule
$value = $condition['value']['value'];
- if (!isset(FormPropertyLogicRule::getConditionMapping()[$typeField])) {
+ if (!isset(LogicPropertyValidator::getConditionMapping()[$typeField])) {
$this->isConditionCorrect = false;
$this->conditionErrors[] = 'configuration not found for condition type';
return;
}
- if (!isset(FormPropertyLogicRule::getConditionMapping()[$typeField]['comparators'][$operator])) {
+ if (!isset(LogicPropertyValidator::getConditionMapping()[$typeField]['comparators'][$operator])) {
$this->isConditionCorrect = false;
$this->conditionErrors[] = 'configuration not found for condition operator';
return;
}
- $type = FormPropertyLogicRule::getConditionMapping()[$typeField]['comparators'][$operator]['expected_type'];
+ $type = LogicPropertyValidator::getConditionMapping()[$typeField]['comparators'][$operator]['expected_type'];
if (is_array($type)) {
$foundCorrectType = false;
diff --git a/api/app/Rules/PaymentBlockConfigurationRule.php b/api/app/Rules/PaymentBlockConfigurationRule.php
deleted file mode 100644
index f485649b3..000000000
--- a/api/app/Rules/PaymentBlockConfigurationRule.php
+++ /dev/null
@@ -1,103 +0,0 @@
-<?php
-
-namespace App\Rules;
-
-use App\Models\OAuthProvider;
-use App\Models\Workspace;
-use Closure;
-use Illuminate\Support\Facades\Log;
-use Illuminate\Contracts\Validation\ValidationRule;
-
-class PaymentBlockConfigurationRule implements ValidationRule
-{
- protected array $properties;
- protected array $field;
- protected ?Workspace $workspace;
-
- /**
- * Cached stripe currency codes (static to persist across instances)
- */
- protected static ?array $stripeCurrencyCodes = null;
-
- public function __construct(array $properties, ?Workspace $workspace = null)
- {
- $this->properties = $properties;
- $this->workspace = $workspace;
- }
-
- public function validate(string $attribute, mixed $value, Closure $fail): void
- {
- // Early bail - $value is the type, skip all processing for non-payment blocks
- if ($value !== 'payment') {
- return;
- }
-
- // Set the field only for payment blocks
- $fieldIndex = explode('.', $attribute)[1];
- $this->field = $this->properties[$fieldIndex];
-
- // Payment block not allowed if self hosted
- if (config('app.self_hosted')) {
- $fail('Payment block is not allowed on self hosted. Please use our hosted version.');
- return;
- }
-
- // Only one payment block allowed
- $paymentBlocks = collect($this->properties)
- ->filter(fn ($prop) => $prop['type'] === 'payment')
- ->count();
-
- if ($paymentBlocks > 1) {
- $fail('Only one payment block allowed');
- return;
- }
-
- // Amount validation
- if (!isset($this->field['amount']) || !is_numeric($this->field['amount']) || $this->field['amount'] < 1) {
- $fail('Amount must be a number greater than 1');
- return;
- }
-
- // Currency validation (lazy-load and cache currency codes)
- if (self::$stripeCurrencyCodes === null) {
- $stripeCurrencies = json_decode(file_get_contents(resource_path('data/stripe_currencies.json')), true);
- self::$stripeCurrencyCodes = array_column($stripeCurrencies, 'code');
- }
-
- if (!isset($this->field['currency']) || !in_array(strtoupper($this->field['currency']), self::$stripeCurrencyCodes)) {
- $fail('Currency must be a valid currency');
- return;
- }
-
- // Stripe account validation
- if (!isset($this->field['stripe_account_id']) || empty($this->field['stripe_account_id'])) {
- $fail('Stripe account is required');
- return;
- }
- try {
- $provider = OAuthProvider::find($this->field['stripe_account_id']);
- if ($provider === null) {
- $fail('Failed to validate Stripe account');
- return;
- }
-
- // Check if the provider is associated with the workspace (if workspace is provided)
- if ($this->workspace && !$this->workspace->hasProvider($provider->id)) {
- Log::error('Attempted to use Stripe account not associated with the workspace', [
- 'stripe_account_id' => $this->field['stripe_account_id'],
- 'provider_id' => $provider->id,
- 'workspace_id' => $this->workspace->id,
- ]);
- $fail('The configured Stripe account is not associated with this workspace');
- return;
- }
- } catch (\Exception $e) {
- Log::error('Failed to validate Stripe account', [
- 'error' => $e->getMessage(),
- 'account_id' => $this->field['stripe_account_id']
- ]);
- $fail('Failed to validate Stripe account');
- return;
- }
- }
-}
diff --git a/api/app/Rules/PropertyValidators/CorePropertyValidator.php b/api/app/Rules/PropertyValidators/CorePropertyValidator.php
new file mode 100644
index 000000000..e38f52eae
--- /dev/null
+++ b/api/app/Rules/PropertyValidators/CorePropertyValidator.php
@@ -0,0 +1,114 @@
+<?php
+
+namespace App\Rules\PropertyValidators;
+
+/**
+ * Validates core property fields that are common to ALL property types.
+ */
+class CorePropertyValidator implements PropertyValidatorInterface
+{
+ /**
+ * Valid values for enumerated fields
+ */
+ private const VALID_HELP_POSITIONS = ['below_input', 'above_input'];
+ private const VALID_WIDTHS = ['full', '1/2', '1/3', '2/3', '3/4', '1/4'];
+ private const VALID_ALIGNS = ['left', 'center', 'right', 'justify'];
+ private const VALID_IMAGE_LAYOUTS = ['between', 'left-small', 'right-small', 'left-split', 'right-split', 'background'];
+
+ public function validate(array $property, int $index, array $context): array
+ {
+ $errors = [];
+ $position = $index + 1; // 1-based for user-friendly messages
+
+ // Required fields
+ if (!isset($property['id']) || $property['id'] === '' || $property['id'] === null) {
+ $errors['id'] = "The form block number {$position} is missing an id.";
+ }
+
+ if (!isset($property['name']) || $property['name'] === '' || $property['name'] === null) {
+ $errors['name'] = "The form block number {$position} is missing a name.";
+ }
+
+ if (!isset($property['type']) || $property['type'] === '' || $property['type'] === null) {
+ $errors['type'] = "The form block number {$position} is missing a type.";
+ }
+
+ // Boolean fields (nullable)
+ $booleanFields = ['hidden', 'required', 'multiple', 'use_toggle_switch'];
+ foreach ($booleanFields as $field) {
+ if (isset($property[$field]) && $property[$field] !== null && !is_bool($property[$field])) {
+ // Allow 0, 1, "0", "1" as boolean
+ if (!in_array($property[$field], [0, 1, '0', '1', true, false], true)) {
+ $errors[$field] = "The {$field} field must be a boolean.";
+ }
+ }
+ }
+
+ // Enum validations (only if value is set and not null)
+ if (isset($property['help_position']) && $property['help_position'] !== null) {
+ if (!in_array($property['help_position'], self::VALID_HELP_POSITIONS, true)) {
+ $errors['help_position'] = "The help_position must be one of: " . implode(', ', self::VALID_HELP_POSITIONS);
+ }
+ }
+
+ if (isset($property['width']) && $property['width'] !== null) {
+ if (!in_array($property['width'], self::VALID_WIDTHS, true)) {
+ $errors['width'] = "The width must be one of: " . implode(', ', self::VALID_WIDTHS);
+ }
+ }
+
+ if (isset($property['align']) && $property['align'] !== null) {
+ if (!in_array($property['align'], self::VALID_ALIGNS, true)) {
+ $errors['align'] = "The align must be one of: " . implode(', ', self::VALID_ALIGNS);
+ }
+ }
+
+ // Image validation (nested object)
+ if (isset($property['image']) && is_array($property['image'])) {
+ $image = $property['image'];
+
+ if (isset($image['url']) && $image['url'] !== null && !filter_var($image['url'], FILTER_VALIDATE_URL)) {
+ $errors['image.url'] = "The image URL must be a valid URL.";
+ }
+
+ if (isset($image['alt']) && $image['alt'] !== null) {
+ if (!is_string($image['alt']) || strlen($image['alt']) > 125) {
+ $errors['image.alt'] = "The image alt text must be a string with max 125 characters.";
+ }
+ }
+
+ if (isset($image['layout']) && $image['layout'] !== null) {
+ if (!in_array($image['layout'], self::VALID_IMAGE_LAYOUTS, true)) {
+ $errors['image.layout'] = "The image layout must be one of: " . implode(', ', self::VALID_IMAGE_LAYOUTS);
+ }
+ }
+
+ // Focal point validation
+ if (isset($image['focal_point']) && is_array($image['focal_point'])) {
+ $focalPoint = $image['focal_point'];
+
+ if (isset($focalPoint['x']) && $focalPoint['x'] !== null) {
+ if (!is_numeric($focalPoint['x']) || $focalPoint['x'] < 0 || $focalPoint['x'] > 100) {
+ $errors['image.focal_point.x'] = "The focal point x must be a number between 0 and 100.";
+ }
+ }
+
+ if (isset($focalPoint['y']) && $focalPoint['y'] !== null) {
+ if (!is_numeric($focalPoint['y']) || $focalPoint['y'] < 0 || $focalPoint['y'] > 100) {
+ $errors['image.focal_point.y'] = "The focal point y must be a number between 0 and 100.";
+ }
+ }
+ }
+
+ if (isset($image['brightness']) && $image['brightness'] !== null) {
+ if (!is_int($image['brightness']) && !ctype_digit(strval($image['brightness'])) && !preg_match('/^-?\d+$/', strval($image['brightness']))) {
+ $errors['image.brightness'] = "The image brightness must be an integer.";
+ } elseif ((int)$image['brightness'] < -100 || (int)$image['brightness'] > 100) {
+ $errors['image.brightness'] = "The image brightness must be between -100 and 100.";
+ }
+ }
+ }
+
+ return $errors;
+ }
+}
diff --git a/api/app/Rules/FormPropertyLogicRule.php b/api/app/Rules/PropertyValidators/LogicPropertyValidator.php
similarity index 60%
rename from api/app/Rules/FormPropertyLogicRule.php
rename to api/app/Rules/PropertyValidators/LogicPropertyValidator.php
index 492ff857f..decc6a5c7 100644
--- a/api/app/Rules/FormPropertyLogicRule.php
+++ b/api/app/Rules/PropertyValidators/LogicPropertyValidator.php
@@ -1,13 +1,12 @@
<?php
-namespace App\Rules;
+namespace App\Rules\PropertyValidators;
-use Closure;
-use Illuminate\Contracts\Validation\DataAwareRule;
-use Illuminate\Contracts\Validation\ValidationRule;
-use Illuminate\Support\Str;
-
-class FormPropertyLogicRule implements DataAwareRule, ValidationRule
+/**
+ * Validates logic configuration for form properties.
+ * Checks that conditions and actions are properly configured.
+ */
+class LogicPropertyValidator implements PropertyValidatorInterface
{
public const ACTIONS_VALUES = [
'show-block',
@@ -20,6 +19,12 @@ class FormPropertyLogicRule implements DataAwareRule, ValidationRule
private static ?array $conditionMappingData = null;
+ private bool $isConditionCorrect = true;
+ private bool $isActionCorrect = true;
+ private array $conditionErrors = [];
+ private array $field = [];
+ private string $operator = '';
+
public static function getConditionMapping(): array
{
if (self::$conditionMappingData === null) {
@@ -29,19 +34,49 @@ class FormPropertyLogicRule implements DataAwareRule, ValidationRule
return self::$conditionMappingData;
}
- private $isConditionCorrect = true;
+ public function validate(array $property, int $index, array $context): array
+ {
+ $errors = [];
+
+ // Reset state for this validation
+ $this->isConditionCorrect = true;
+ $this->isActionCorrect = true;
+ $this->conditionErrors = [];
+ $this->field = $property;
+
+ $logic = $property['logic'] ?? null;
- private $isActionCorrect = true;
+ // Early bail for empty/null logic
+ if (empty($logic) || !is_array($logic)) {
+ return $errors;
+ }
- private $conditionErrors = [];
+ // Validate logic is an array (nullable)
+ if (!is_array($logic)) {
+ $errors['logic'] = 'The logic field must be an array.';
+ return $errors;
+ }
- private $field = [];
+ // If no conditions, logic is valid (empty logic)
+ if (!isset($logic['conditions'])) {
+ return $errors;
+ }
- private $data = [];
+ // Check conditions
+ $this->checkConditions($logic['conditions']);
- private $operator = '';
+ // Check actions
+ $this->checkActions($logic['actions'] ?? null);
- private function checkBaseCondition($condition)
+ // Build error message if validation failed
+ if (!$this->isConditionCorrect || !$this->isActionCorrect) {
+ $errors['logic'] = $this->buildErrorMessage($property['name'] ?? 'Unknown');
+ }
+
+ return $errors;
+ }
+
+ private function checkBaseCondition(array $condition): void
{
if (!isset($condition['value'])) {
$this->isConditionCorrect = false;
@@ -119,11 +154,12 @@ class FormPropertyLogicRule implements DataAwareRule, ValidationRule
}
}
- private function valueHasCorrectType($type, $value)
+ private function valueHasCorrectType(?string $type, mixed $value): bool
{
if ($type === 'string') {
$mapping = self::getConditionMapping();
- $format = $mapping[$this->field['type']]['comparators'][$this->operator]['format'] ?? null;
+ $fieldType = $this->field['type'] ?? null;
+ $format = $mapping[$fieldType]['comparators'][$this->operator]['format'] ?? null;
if ($format && ($format['type'] ?? null) === 'regex') {
try {
preg_match('/' . $value . '/', '');
@@ -147,31 +183,34 @@ class FormPropertyLogicRule implements DataAwareRule, ValidationRule
return true;
}
- private function checkConditions($conditions)
+ private function checkConditions(mixed $conditions): void
{
+ if (!is_array($conditions)) {
+ $this->isConditionCorrect = false;
+ $this->conditionErrors[] = 'conditions must be an array';
+ return;
+ }
+
if (array_key_exists('operatorIdentifier', $conditions)) {
if (($conditions['operatorIdentifier'] !== 'and') && ($conditions['operatorIdentifier'] !== 'or')) {
$this->conditionErrors[] = 'missing operator';
$this->isConditionCorrect = false;
-
return;
}
if (isset($conditions['operatorIdentifier']['children'])) {
$this->conditionErrors[] = 'extra condition';
$this->isConditionCorrect = false;
-
return;
}
- if (!is_array($conditions['children'])) {
+ if (!isset($conditions['children']) || !is_array($conditions['children'])) {
$this->conditionErrors[] = 'wrong sub-condition type';
$this->isConditionCorrect = false;
-
return;
}
- foreach ($conditions['children'] as &$child) {
+ foreach ($conditions['children'] as $child) {
$this->checkConditions($child);
}
} elseif (isset($conditions['identifier'])) {
@@ -179,91 +218,47 @@ class FormPropertyLogicRule implements DataAwareRule, ValidationRule
}
}
- private function checkActions($actions)
+ private function checkActions(mixed $actions): void
{
- if (is_array($actions) && count($actions) > 0) {
- foreach ($actions as $val) {
- if (
- !in_array($val, static::ACTIONS_VALUES) ||
- (in_array($this->field['type'], ['nf-text', 'nf-code', 'nf-page-break', 'nf-divider', 'nf-image', 'nf-video']) && !in_array($val, ['hide-block', 'show-block'])) ||
- (isset($this->field['hidden']) && $this->field['hidden'] && !in_array($val, ['show-block', 'require-answer'])) ||
- (isset($this->field['required']) && $this->field['required'] && !in_array($val, ['make-it-optional', 'hide-block', 'disable-block'])) ||
- (isset($this->field['disabled']) && $this->field['disabled'] && !in_array($val, ['enable-block', 'require-answer', 'make-it-optional']))
- ) {
- $this->isActionCorrect = false;
- break;
- }
- }
- } else {
+ if (!is_array($actions) || count($actions) === 0) {
$this->isActionCorrect = false;
+ return;
}
- }
- /**
- * Determine if the validation rule passes.
- *
- * @param string $attribute
- * @param mixed $value
- * @return bool
- */
- public function passes($attribute, $value)
- {
- // Early bail for empty/null logic
- if (empty($value) || !isset($value['conditions'])) {
- return true;
+ $layoutBlocks = ['nf-text', 'nf-code', 'nf-page-break', 'nf-divider', 'nf-image', 'nf-video'];
+ $fieldType = $this->field['type'] ?? null;
+ $isHidden = $this->field['hidden'] ?? false;
+ $isRequired = $this->field['required'] ?? false;
+ $isDisabled = $this->field['disabled'] ?? false;
+
+ foreach ($actions as $action) {
+ if (
+ !in_array($action, self::ACTIONS_VALUES) ||
+ (in_array($fieldType, $layoutBlocks) && !in_array($action, ['hide-block', 'show-block'])) ||
+ ($isHidden && !in_array($action, ['show-block', 'require-answer'])) ||
+ ($isRequired && !in_array($action, ['make-it-optional', 'hide-block', 'disable-block'])) ||
+ ($isDisabled && !in_array($action, ['enable-block', 'require-answer', 'make-it-optional']))
+ ) {
+ $this->isActionCorrect = false;
+ break;
+ }
}
-
- $this->setProperty($attribute);
- $this->checkConditions($value['conditions']);
- $this->checkActions($value['actions'] ?? null);
-
- return $this->isConditionCorrect && $this->isActionCorrect;
}
- public function validate(string $attribute, mixed $value, Closure $fail): void
+ private function buildErrorMessage(string $fieldName): string
{
- if (!$this->passes($attribute, $value)) {
- $fail($this->message());
- }
- }
+ $message = '';
- /**
- * Get the validation error message.
- */
- public function message()
- {
- $message = null;
if (!$this->isConditionCorrect) {
- $message = 'The logic conditions for ' . $this->field['name'] . ' are not complete.';
+ $message = "The logic conditions for {$fieldName} are not complete.";
} elseif (!$this->isActionCorrect) {
- $message = 'The logic actions for ' . $this->field['name'] . ' are not valid.';
+ $message = "The logic actions for {$fieldName} are not valid.";
}
+
if (count($this->conditionErrors) > 0) {
- return $message . ' Error detail(s): ' . implode(', ', $this->conditionErrors);
+ $message .= ' Error detail(s): ' . implode(', ', $this->conditionErrors);
}
return $message;
}
-
- /**
- * Set the data under validation.
- *
- * @param array $data
- * @return $this
- */
- public function setData($data)
- {
- $this->data = $data;
- $this->isConditionCorrect = true;
- $this->isActionCorrect = true;
- $this->conditionErrors = [];
-
- return $this;
- }
-
- private function setProperty(string $attributeKey)
- {
- $attributeKey = Str::of($attributeKey)->replace('.logic', '')->toString();
- $this->field = \Arr::get($this->data, $attributeKey);
- }
}
diff --git a/api/app/Rules/PropertyValidators/PaymentPropertyValidator.php b/api/app/Rules/PropertyValidators/PaymentPropertyValidator.php
new file mode 100644
index 000000000..c625bebbd
--- /dev/null
+++ b/api/app/Rules/PropertyValidators/PaymentPropertyValidator.php
@@ -0,0 +1,108 @@
+<?php
+
+namespace App\Rules\PropertyValidators;
+
+use App\Models\OAuthProvider;
+use App\Models\Workspace;
+use Illuminate\Support\Facades\Log;
+
+/**
+ * Validates payment block properties.
+ * Only runs validation for properties with type === 'payment'.
+ */
+class PaymentPropertyValidator implements PropertyValidatorInterface
+{
+ private ?Workspace $workspace;
+
+ /**
+ * Cached stripe currency codes (static to persist across requests)
+ */
+ private static ?array $stripeCurrencyCodes = null;
+
+ public function __construct(?Workspace $workspace = null)
+ {
+ $this->workspace = $workspace;
+ }
+
+ public function validate(array $property, int $index, array $context): array
+ {
+ $errors = [];
+ $type = $property['type'] ?? null;
+
+ // Early bail - skip all processing for non-payment blocks
+ if ($type !== 'payment') {
+ return $errors;
+ }
+
+ // Payment block not allowed if self hosted
+ if (config('app.self_hosted')) {
+ $errors['type'] = 'Payment block is not allowed on self hosted. Please use our hosted version.';
+ return $errors;
+ }
+
+ // Only one payment block allowed (check against all properties)
+ $properties = $context['properties'] ?? [];
+ $paymentBlockCount = 0;
+ foreach ($properties as $prop) {
+ if (($prop['type'] ?? null) === 'payment') {
+ $paymentBlockCount++;
+ }
+ }
+
+ if ($paymentBlockCount > 1) {
+ $errors['type'] = 'Only one payment block allowed';
+ return $errors;
+ }
+
+ // Amount validation
+ if (!isset($property['amount']) || !is_numeric($property['amount']) || $property['amount'] < 1) {
+ $errors['amount'] = 'Amount must be a number greater than 1';
+ return $errors;
+ }
+
+ // Currency validation (lazy-load and cache currency codes)
+ if (self::$stripeCurrencyCodes === null) {
+ $stripeCurrencies = json_decode(file_get_contents(resource_path('data/stripe_currencies.json')), true);
+ self::$stripeCurrencyCodes = array_column($stripeCurrencies, 'code');
+ }
+
+ if (!isset($property['currency']) || !in_array(strtoupper($property['currency']), self::$stripeCurrencyCodes)) {
+ $errors['currency'] = 'Currency must be a valid currency';
+ return $errors;
+ }
+
+ // Stripe account validation
+ if (!isset($property['stripe_account_id']) || empty($property['stripe_account_id'])) {
+ $errors['stripe_account_id'] = 'Stripe account is required';
+ return $errors;
+ }
+
+ try {
+ $provider = OAuthProvider::find($property['stripe_account_id']);
+ if ($provider === null) {
+ $errors['stripe_account_id'] = 'Failed to validate Stripe account';
+ return $errors;
+ }
+
+ // Check if the provider is associated with the workspace (if workspace is provided)
+ if ($this->workspace && !$this->workspace->hasProvider($provider->id)) {
+ Log::error('Attempted to use Stripe account not associated with the workspace', [
+ 'stripe_account_id' => $property['stripe_account_id'],
+ 'provider_id' => $provider->id,
+ 'workspace_id' => $this->workspace->id,
+ ]);
+ $errors['stripe_account_id'] = 'The configured Stripe account is not associated with this workspace';
+ return $errors;
+ }
+ } catch (\Exception $e) {
+ Log::error('Failed to validate Stripe account', [
+ 'error' => $e->getMessage(),
+ 'account_id' => $property['stripe_account_id']
+ ]);
+ $errors['stripe_account_id'] = 'Failed to validate Stripe account';
+ return $errors;
+ }
+
+ return $errors;
+ }
+}
diff --git a/api/app/Rules/PropertyValidators/PropertyValidatorInterface.php b/api/app/Rules/PropertyValidators/PropertyValidatorInterface.php
new file mode 100644
index 000000000..c19bc273e
--- /dev/null
+++ b/api/app/Rules/PropertyValidators/PropertyValidatorInterface.php
@@ -0,0 +1,20 @@
+<?php
+
+namespace App\Rules\PropertyValidators;
+
+/**
+ * Interface for property validators used in single-pass form validation.
+ * Each validator handles a specific aspect of property validation.
+ */
+interface PropertyValidatorInterface
+{
+ /**
+ * Validate a single property.
+ *
+ * @param array $property The property data to validate
+ * @param int $index The index of the property in the properties array
+ * @param array $context Additional context (properties array, workspace, etc.)
+ * @return array<string, string> Field => error message pairs (empty if valid)
+ */
+ public function validate(array $property, int $index, array $context): array;
+}
diff --git a/api/app/Rules/PropertyValidators/TypePropertyValidator.php b/api/app/Rules/PropertyValidators/TypePropertyValidator.php
new file mode 100644
index 000000000..ac37de56d
--- /dev/null
+++ b/api/app/Rules/PropertyValidators/TypePropertyValidator.php
@@ -0,0 +1,180 @@
+<?php
+
+namespace App\Rules\PropertyValidators;
+
+/**
+ * Validates type-specific property fields based on the property type.
+ * Only validates fields that are relevant to each specific type.
+ */
+class TypePropertyValidator implements PropertyValidatorInterface
+{
+ /**
+ * Type-specific validation rules.
+ * Key = property type, Value = array of field => validation config
+ */
+ private const TYPE_RULES = [
+ // Text field rules
+ 'text' => [
+ 'multi_lines' => ['type' => 'boolean'],
+ 'max_char_limit' => ['type' => 'integer', 'min' => 1],
+ 'show_char_limit' => ['type' => 'boolean'],
+ 'secret_input' => ['type' => 'boolean'],
+ ],
+
+ // Date field rules
+ 'date' => [
+ 'with_time' => ['type' => 'boolean'],
+ 'date_range' => ['type' => 'boolean'],
+ 'prefill_today' => ['type' => 'boolean'],
+ 'disable_past_dates' => ['type' => 'boolean'],
+ 'disable_future_dates' => ['type' => 'boolean'],
+ ],
+
+ // Select / Multi-select field rules
+ 'select' => [
+ 'allow_creation' => ['type' => 'boolean'],
+ 'without_dropdown' => ['type' => 'boolean'],
+ 'min_selection' => ['type' => 'integer', 'min' => 0],
+ 'max_selection' => ['type' => 'integer', 'min' => 1],
+ ],
+ 'multi_select' => [
+ 'allow_creation' => ['type' => 'boolean'],
+ 'without_dropdown' => ['type' => 'boolean'],
+ 'min_selection' => ['type' => 'integer', 'min' => 0],
+ 'max_selection' => ['type' => 'integer', 'min' => 1],
+ ],
+
+ // File upload rules
+ 'files' => [
+ 'max_file_size' => ['type' => 'numeric', 'min' => 1],
+ 'allowed_file_types' => ['type' => 'nullable'],
+ ],
+
+ // Checkbox rules
+ 'checkbox' => [
+ 'use_toggle_switch' => ['type' => 'boolean'],
+ ],
+
+ // Advanced options (can apply to multiple types)
+ 'text' => [
+ 'multi_lines' => ['type' => 'boolean'],
+ 'max_char_limit' => ['type' => 'integer', 'min' => 1],
+ 'show_char_limit' => ['type' => 'boolean'],
+ 'secret_input' => ['type' => 'boolean'],
+ 'generates_uuid' => ['type' => 'boolean'],
+ 'generates_auto_increment_id' => ['type' => 'boolean'],
+ ],
+ ];
+
+ /**
+ * Fields that can appear on any input type (not layout blocks)
+ */
+ private const COMMON_INPUT_RULES = [
+ 'generates_uuid' => ['type' => 'boolean'],
+ 'generates_auto_increment_id' => ['type' => 'boolean'],
+ ];
+
+ public function validate(array $property, int $index, array $context): array
+ {
+ $errors = [];
+ $type = $property['type'] ?? null;
+
+ if (!$type) {
+ return $errors; // Type validation handled by CorePropertyValidator
+ }
+
+ // Skip layout blocks (nf-*) - they have no type-specific rules
+ if (str_starts_with($type, 'nf-')) {
+ return $errors;
+ }
+
+ // Get rules for this type
+ $typeRules = self::TYPE_RULES[$type] ?? [];
+
+ // Add common input rules for non-layout blocks
+ $allRules = array_merge($typeRules, self::COMMON_INPUT_RULES);
+
+ foreach ($allRules as $field => $config) {
+ if (!isset($property[$field]) || $property[$field] === null) {
+ continue; // Field not present or null, skip validation
+ }
+
+ $value = $property[$field];
+ $fieldError = $this->validateField($field, $value, $config);
+
+ if ($fieldError !== null) {
+ $errors[$field] = $fieldError;
+ }
+ }
+
+ return $errors;
+ }
+
+ /**
+ * Validate a single field against its configuration.
+ */
+ private function validateField(string $field, mixed $value, array $config): ?string
+ {
+ $type = $config['type'] ?? null;
+
+ switch ($type) {
+ case 'boolean':
+ if (!$this->isBoolean($value)) {
+ return "The {$field} field must be a boolean.";
+ }
+ break;
+
+ case 'integer':
+ if (!$this->isInteger($value)) {
+ return "The {$field} field must be an integer.";
+ }
+ if (isset($config['min']) && (int)$value < $config['min']) {
+ return "The {$field} field must be at least {$config['min']}.";
+ }
+ if (isset($config['max']) && (int)$value > $config['max']) {
+ return "The {$field} field must not be greater than {$config['max']}.";
+ }
+ break;
+
+ case 'numeric':
+ if (!is_numeric($value)) {
+ return "The {$field} field must be a number.";
+ }
+ if (isset($config['min']) && (float)$value < $config['min']) {
+ return "The {$field} field must be at least {$config['min']}.";
+ }
+ if (isset($config['max']) && (float)$value > $config['max']) {
+ return "The {$field} field must not be greater than {$config['max']}.";
+ }
+ break;
+
+ case 'nullable':
+ // No validation needed - field can be anything
+ break;
+ }
+
+ return null;
+ }
+
+ /**
+ * Check if a value is boolean or can be interpreted as boolean.
+ */
+ private function isBoolean(mixed $value): bool
+ {
+ return is_bool($value) || in_array($value, [0, 1, '0', '1'], true);
+ }
+
+ /**
+ * Check if a value is an integer or can be interpreted as integer.
+ */
+ private function isInteger(mixed $value): bool
+ {
+ if (is_int($value)) {
+ return true;
+ }
+ if (is_string($value) && preg_match('/^-?\d+$/', $value)) {
+ return true;
+ }
+ return false;
+ }
+}
diff --git a/api/tests/Feature/Forms/FormPropertyLogicTest.php b/api/tests/Feature/Forms/FormPropertyLogicTest.php
deleted file mode 100644
index 04f7755df..000000000
--- a/api/tests/Feature/Forms/FormPropertyLogicTest.php
+++ /dev/null
@@ -1,255 +0,0 @@
-<?php
-
-use App\Rules\FormPropertyLogicRule;
-
-it('can validate form logic rules for actions', function () {
- $rules = [
- 'properties.*.logic' => ['array', 'nullable', new FormPropertyLogicRule()],
- ];
-
- $data = [
- 'properties' => [
- [
- 'id' => 'title',
- 'name' => 'Name',
- 'type' => 'title',
- 'hidden' => false,
- 'required' => false,
- 'logic' => [
- 'conditions' => null,
- 'actions' => [],
- ],
- ],
- ],
- ];
- $validatorObj = $this->app['validator']->make($data, $rules);
- $this->assertTrue($validatorObj->passes());
-
- $data = [
- 'properties' => [
- [
- 'id' => 'title',
- 'name' => 'Name',
- 'type' => 'title',
- 'hidden' => true,
- 'required' => false,
- 'logic' => [
- 'conditions' => [
- 'operatorIdentifier' => 'and',
- 'children' => [
- [
- 'identifier' => 'title',
- 'value' => [
- 'operator' => 'equals',
- 'property_meta' => [
- 'id' => 'title',
- 'type' => 'text',
- ],
- 'value' => 'TEST',
- ],
- ],
- ],
- ],
- 'actions' => ['hide-block'],
- ],
- ],
- ],
- ];
- $validatorObj = $this->app['validator']->make($data, $rules);
- $this->assertFalse($validatorObj->passes());
- expect($validatorObj->errors()->messages()['properties.0.logic'][0])->toBe('The logic actions for Name are not valid.');
-
- $data = [
- 'properties' => [
- [
- 'id' => 'text',
- 'name' => 'Custom Test',
- 'type' => 'nf-text',
- 'logic' => [
- 'conditions' => [
- 'operatorIdentifier' => 'and',
- 'children' => [
- [
- 'identifier' => 'title',
- 'value' => [
- 'operator' => 'equals',
- 'property_meta' => [
- 'id' => 'title',
- 'type' => 'text',
- ],
- 'value' => 'TEST',
- ],
- ],
- ],
- ],
- 'actions' => ['require-answer'],
- ],
- ],
- ],
- ];
- $validatorObj = $this->app['validator']->make($data, $rules);
- $this->assertFalse($validatorObj->passes());
- expect($validatorObj->errors()->messages()['properties.0.logic'][0])->toBe('The logic actions for Custom Test are not valid.');
-});
-
-it('can validate form logic rules for conditions', function () {
- $rules = [
- 'properties.*.logic' => ['array', 'nullable', new FormPropertyLogicRule()],
- ];
-
- $data = [
- 'properties' => [
- [
- 'id' => 'title',
- 'name' => 'Name',
- 'type' => 'text',
- 'hidden' => false,
- 'required' => false,
- 'logic' => [
- 'conditions' => [
- 'operatorIdentifier' => 'and',
- 'children' => [
- [
- 'identifier' => 'title',
- 'value' => [
- 'operator' => 'equals',
- 'property_meta' => [
- 'id' => 'title',
- 'type' => 'text',
- ],
- 'value' => 'TEST',
- ],
- ],
- ],
- ],
- 'actions' => ['hide-block'],
- ],
- ],
- ],
- ];
-
- $validatorObj = $this->app['validator']->make($data, $rules);
- $this->assertTrue($validatorObj->passes());
-
- $data = [
- 'properties' => [
- [
- 'id' => 'title',
- 'name' => 'Name',
- 'type' => 'text',
- 'hidden' => false,
- 'required' => false,
- 'logic' => [
- 'conditions' => [
- 'operatorIdentifier' => 'and',
- 'children' => [
- [
- 'identifier' => 'title',
- 'value' => [
- 'operator' => 'starts_with',
- 'property_meta' => [
- 'id' => 'title',
- 'type' => 'text',
- ],
- ],
- ],
- ],
- ],
- 'actions' => ['hide-block'],
- ],
- ],
- ],
- ];
-
- $validatorObj = $this->app['validator']->make($data, $rules);
- $this->assertFalse($validatorObj->passes());
- expect($validatorObj->errors()->messages()['properties.0.logic'][0])->toBe('The logic conditions for Name are not complete. Error detail(s): missing condition value');
-
- $data = [
- 'properties' => [
- [
- 'id' => 'title',
- 'name' => 'Name',
- 'type' => 'text',
- 'hidden' => false,
- 'required' => false,
- 'logic' => [
- 'conditions' => [
- 'operatorIdentifier' => null,
- 'children' => [
- [
- 'identifier' => 'title',
- 'value' => [
- 'operator' => 'starts_with',
- 'property_meta' => [
- 'id' => 'title',
- 'type' => 'text',
- ],
- ],
- ],
- ],
- ],
- 'actions' => ['hide-block'],
- ],
- ],
- ],
- ];
-
- $validatorObj = $this->app['validator']->make($data, $rules);
- $this->assertFalse($validatorObj->passes());
- expect($validatorObj->errors()->messages()['properties.0.logic'][0])->toBe('The logic conditions for Name are not complete. Error detail(s): missing operator');
-});
-
-it('can validate form logic rules for operators without values', function () {
- $rules = [
- 'properties.*.logic' => ['array', 'nullable', new FormPropertyLogicRule()],
- ];
-
- // Test checkbox is_checked without value
- $data = [
- 'properties' => [
- [
- 'id' => 'checkbox1',
- 'name' => 'Checkbox Field',
- 'type' => 'checkbox',
- 'logic' => [
- 'conditions' => [
- 'operatorIdentifier' => 'and',
- 'children' => [
- [
- 'identifier' => 'test-id',
- 'value' => [
- 'operator' => 'is_checked',
- 'property_meta' => [
- 'id' => 'test-id',
- 'type' => 'checkbox'
- ]
- ]
- ]
- ]
- ],
- 'actions' => ['show-block']
- ]
- ]
- ]
- ];
- $validatorObj = $this->app['validator']->make($data, $rules);
- $this->assertTrue($validatorObj->passes());
-
- // Test checkbox is_checked with value (should still pass for backward compatibility)
- $data['properties'][0]['logic']['conditions']['children'][0]['value']['value'] = true;
- $validatorObj = $this->app['validator']->make($data, $rules);
- $this->assertTrue($validatorObj->passes());
-
- // Test checkbox is_not_checked without value
- $data['properties'][0]['logic']['conditions']['children'][0]['value']['operator'] = 'is_not_checked';
- unset($data['properties'][0]['logic']['conditions']['children'][0]['value']['value']);
- $validatorObj = $this->app['validator']->make($data, $rules);
- $this->assertTrue($validatorObj->passes());
-
- // Test checkbox with operator that doesn't exist
- $data['properties'][0]['logic']['conditions']['children'][0]['value']['operator'] = 'invalid_operator';
- $validatorObj = $this->app['validator']->make($data, $rules);
- $this->assertFalse($validatorObj->passes());
- expect($validatorObj->errors()->messages()['properties.0.logic'][0])->toBe('The logic conditions for Checkbox Field are not complete. Error detail(s): configuration not found for condition operator');
-});
diff --git a/api/tests/Unit/Rules/LogicPropertyValidatorTest.php b/api/tests/Unit/Rules/LogicPropertyValidatorTest.php
new file mode 100644
index 000000000..cc862e22b
--- /dev/null
+++ b/api/tests/Unit/Rules/LogicPropertyValidatorTest.php
@@ -0,0 +1,317 @@
+<?php
+
+use App\Rules\PropertyValidators\LogicPropertyValidator;
+use Tests\TestCase;
+
+uses(TestCase::class);
+
+describe('LogicPropertyValidator action validation', function () {
+ it('passes with empty logic', function () {
+ $validator = new LogicPropertyValidator();
+ $context = ['properties' => []];
+ $property = [
+ 'id' => 'title',
+ 'name' => 'Name',
+ 'type' => 'title',
+ 'hidden' => false,
+ 'required' => false,
+ 'logic' => [
+ 'conditions' => null,
+ 'actions' => [],
+ ],
+ ];
+ $errors = $validator->validate($property, 0, $context);
+ expect($errors)->toBeEmpty();
+ });
+
+ it('fails when hidden block has hide-block action', function () {
+ $validator = new LogicPropertyValidator();
+ $context = ['properties' => []];
+ $property = [
+ 'id' => 'title',
+ 'name' => 'Name',
+ 'type' => 'title',
+ 'hidden' => true,
+ 'required' => false,
+ 'logic' => [
+ 'conditions' => [
+ 'operatorIdentifier' => 'and',
+ 'children' => [
+ [
+ 'identifier' => 'title',
+ 'value' => [
+ 'operator' => 'equals',
+ 'property_meta' => [
+ 'id' => 'title',
+ 'type' => 'text',
+ ],
+ 'value' => 'TEST',
+ ],
+ ],
+ ],
+ ],
+ 'actions' => ['hide-block'],
+ ],
+ ];
+ $errors = $validator->validate($property, 0, $context);
+ expect($errors)->toHaveKey('logic');
+ expect($errors['logic'])->toContain('The logic actions for Name are not valid.');
+ });
+
+ it('fails when nf-text block has require-answer action', function () {
+ $validator = new LogicPropertyValidator();
+ $context = ['properties' => []];
+ $property = [
+ 'id' => 'text',
+ 'name' => 'Custom Test',
+ 'type' => 'nf-text',
+ 'logic' => [
+ 'conditions' => [
+ 'operatorIdentifier' => 'and',
+ 'children' => [
+ [
+ 'identifier' => 'title',
+ 'value' => [
+ 'operator' => 'equals',
+ 'property_meta' => [
+ 'id' => 'title',
+ 'type' => 'text',
+ ],
+ 'value' => 'TEST',
+ ],
+ ],
+ ],
+ ],
+ 'actions' => ['require-answer'],
+ ],
+ ];
+ $errors = $validator->validate($property, 0, $context);
+ expect($errors)->toHaveKey('logic');
+ expect($errors['logic'])->toContain('The logic actions for Custom Test are not valid.');
+ });
+});
+
+describe('LogicPropertyValidator condition validation', function () {
+ it('passes with valid conditions', function () {
+ $validator = new LogicPropertyValidator();
+ $context = ['properties' => []];
+ $property = [
+ 'id' => 'title',
+ 'name' => 'Name',
+ 'type' => 'text',
+ 'hidden' => false,
+ 'required' => false,
+ 'logic' => [
+ 'conditions' => [
+ 'operatorIdentifier' => 'and',
+ 'children' => [
+ [
+ 'identifier' => 'title',
+ 'value' => [
+ 'operator' => 'equals',
+ 'property_meta' => [
+ 'id' => 'title',
+ 'type' => 'text',
+ ],
+ 'value' => 'TEST',
+ ],
+ ],
+ ],
+ ],
+ 'actions' => ['hide-block'],
+ ],
+ ];
+ $errors = $validator->validate($property, 0, $context);
+ expect($errors)->toBeEmpty();
+ });
+
+ it('fails when condition value is missing', function () {
+ $validator = new LogicPropertyValidator();
+ $context = ['properties' => []];
+ $property = [
+ 'id' => 'title',
+ 'name' => 'Name',
+ 'type' => 'text',
+ 'hidden' => false,
+ 'required' => false,
+ 'logic' => [
+ 'conditions' => [
+ 'operatorIdentifier' => 'and',
+ 'children' => [
+ [
+ 'identifier' => 'title',
+ 'value' => [
+ 'operator' => 'starts_with',
+ 'property_meta' => [
+ 'id' => 'title',
+ 'type' => 'text',
+ ],
+ ],
+ ],
+ ],
+ ],
+ 'actions' => ['hide-block'],
+ ],
+ ];
+ $errors = $validator->validate($property, 0, $context);
+ expect($errors)->toHaveKey('logic');
+ expect($errors['logic'])->toBe('The logic conditions for Name are not complete. Error detail(s): missing condition value');
+ });
+
+ it('fails when operator is missing', function () {
+ $validator = new LogicPropertyValidator();
+ $context = ['properties' => []];
+ $property = [
+ 'id' => 'title',
+ 'name' => 'Name',
+ 'type' => 'text',
+ 'hidden' => false,
+ 'required' => false,
+ 'logic' => [
+ 'conditions' => [
+ 'operatorIdentifier' => null,
+ 'children' => [
+ [
+ 'identifier' => 'title',
+ 'value' => [
+ 'operator' => 'starts_with',
+ 'property_meta' => [
+ 'id' => 'title',
+ 'type' => 'text',
+ ],
+ ],
+ ],
+ ],
+ ],
+ 'actions' => ['hide-block'],
+ ],
+ ];
+ $errors = $validator->validate($property, 0, $context);
+ expect($errors)->toHaveKey('logic');
+ expect($errors['logic'])->toBe('The logic conditions for Name are not complete. Error detail(s): missing operator');
+ });
+});
+
+describe('LogicPropertyValidator operators without values', function () {
+ it('passes for checkbox is_checked without value', function () {
+ $validator = new LogicPropertyValidator();
+ $context = ['properties' => []];
+ $property = [
+ 'id' => 'checkbox1',
+ 'name' => 'Checkbox Field',
+ 'type' => 'checkbox',
+ 'logic' => [
+ 'conditions' => [
+ 'operatorIdentifier' => 'and',
+ 'children' => [
+ [
+ 'identifier' => 'test-id',
+ 'value' => [
+ 'operator' => 'is_checked',
+ 'property_meta' => [
+ 'id' => 'test-id',
+ 'type' => 'checkbox'
+ ]
+ ]
+ ]
+ ]
+ ],
+ 'actions' => ['show-block']
+ ]
+ ];
+ $errors = $validator->validate($property, 0, $context);
+ expect($errors)->toBeEmpty();
+ });
+
+ it('passes for checkbox is_checked with value for backward compatibility', function () {
+ $validator = new LogicPropertyValidator();
+ $context = ['properties' => []];
+ $property = [
+ 'id' => 'checkbox1',
+ 'name' => 'Checkbox Field',
+ 'type' => 'checkbox',
+ 'logic' => [
+ 'conditions' => [
+ 'operatorIdentifier' => 'and',
+ 'children' => [
+ [
+ 'identifier' => 'test-id',
+ 'value' => [
+ 'operator' => 'is_checked',
+ 'property_meta' => [
+ 'id' => 'test-id',
+ 'type' => 'checkbox'
+ ],
+ 'value' => true
+ ]
+ ]
+ ]
+ ],
+ 'actions' => ['show-block']
+ ]
+ ];
+ $errors = $validator->validate($property, 0, $context);
+ expect($errors)->toBeEmpty();
+ });
+
+ it('passes for checkbox is_not_checked without value', function () {
+ $validator = new LogicPropertyValidator();
+ $context = ['properties' => []];
+ $property = [
+ 'id' => 'checkbox1',
+ 'name' => 'Checkbox Field',
+ 'type' => 'checkbox',
+ 'logic' => [
+ 'conditions' => [
+ 'operatorIdentifier' => 'and',
+ 'children' => [
+ [
+ 'identifier' => 'test-id',
+ 'value' => [
+ 'operator' => 'is_not_checked',
+ 'property_meta' => [
+ 'id' => 'test-id',
+ 'type' => 'checkbox'
+ ]
+ ]
+ ]
+ ]
+ ],
+ 'actions' => ['show-block']
+ ]
+ ];
+ $errors = $validator->validate($property, 0, $context);
+ expect($errors)->toBeEmpty();
+ });
+
+ it('fails for invalid operator', function () {
+ $validator = new LogicPropertyValidator();
+ $context = ['properties' => []];
+ $property = [
+ 'id' => 'checkbox1',
+ 'name' => 'Checkbox Field',
+ 'type' => 'checkbox',
+ 'logic' => [
+ 'conditions' => [
+ 'operatorIdentifier' => 'and',
+ 'children' => [
+ [
+ 'identifier' => 'test-id',
+ 'value' => [
+ 'operator' => 'invalid_operator',
+ 'property_meta' => [
+ 'id' => 'test-id',
+ 'type' => 'checkbox'
+ ]
+ ]
+ ]
+ ]
+ ],
+ 'actions' => ['show-block']
+ ]
+ ];
+ $errors = $validator->validate($property, 0, $context);
+ expect($errors)->toHaveKey('logic');
+ expect($errors['logic'])->toBe('The logic conditions for Checkbox Field are not complete. Error detail(s): configuration not found for condition operator');
+ });
+});