Skip to content

Beautiful Open-Source Form Builder

4.5 KB
Raw Blame
<?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 (is_array($prop) && ($prop['type'] ?? null) === 'payment') {
                $paymentBlockCount++;
            }
        }

        if ($paymentBlockCount > 1) {
            $errors['type'] = 'Only one payment block allowed';
            return $errors;
        }

        // Amount validation - allow numeric value >= 1 or string with mention
        $amount = $property['amount'] ?? null;
        $isValidAmount = false;

        if (is_numeric($amount) && $amount >= 1) {
            $isValidAmount = true;
        } elseif (is_string($amount) && preg_match('/mention[-\w]*=/', $amount)) {
            // Amount contains a mention reference - will be parsed at runtime
            $isValidAmount = true;
        }

        if (!$isValidAmount) {
            $errors['amount'] = 'Amount must be a number of at least 1 or a field reference';
            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 (! is_string($property['currency'] ?? null)
            || ! in_array(strtoupper($property['currency']), self::$stripeCurrencyCodes, true)) {
            $errors['currency'] = 'Currency must be a valid currency';
            return $errors;
        }

        // Stripe account validation
        $stripeAccountId = $property['stripe_account_id'] ?? null;
        if ((! is_string($stripeAccountId) && ! is_int($stripeAccountId)) || $stripeAccountId === '') {
            $errors['stripe_account_id'] = 'Stripe account is required';
            return $errors;
        }

        // Guest form definitions have no workspace security boundary yet. Defer
        // provider lookup until the draft is claimed so validation cannot be
        // used to enumerate OAuth provider IDs from other accounts.
        if ($this->workspace === null) {
            return $errors;
        }

        try {
            $provider = OAuthProvider::find($stripeAccountId);
            if ($provider === null) {
                $errors['stripe_account_id'] = 'Failed to validate Stripe account';
                return $errors;
            }

            if (!$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 (\Throwable $e) {
            Log::error('Failed to validate Stripe account', [
                'error' => $e->getMessage(),
                'account_id' => $stripeAccountId,
            ]);
            $errors['stripe_account_id'] = 'Failed to validate Stripe account';
            return $errors;
        }

        return $errors;
    }
}