Skip to content

Beautiful Open-Source Form Builder

2.5 KB
Raw Blame
<?php

namespace App\Http\Requests\Workspace;

use App\Models\Workspace;
use App\Service\CustomDomainOwnershipService;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Request;

class CustomDomainRequest extends FormRequest
{
    public const CUSTOM_DOMAINS_REGEX = CustomDomainOwnershipService::DOMAIN_REGEX;

    public Workspace $workspace;

    public array $customDomains = [];

    public function __construct(Request $request)
    {
        $this->workspace = $request->route('workspace');
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {
        return [
            'custom_domains' => [
                'bail',
                'present',
                'array',
                function ($attribute, $value, $fail) {
                    $domains = collect($value)->map(function ($domain) {
                        return is_string($domain) ? strtolower(trim($domain)) : $domain;
                    })->filter(fn ($domain) => $domain !== '' && $domain !== null)->unique()->values();

                    foreach ($domains as $domain) {
                        if (! is_string($domain) || strlen($domain) > 253 || ! preg_match(self::CUSTOM_DOMAINS_REGEX, $domain)) {
                            $fail('Invalid domain: '.(is_string($domain) ? $domain : 'expected a domain name'));
                            return;
                        }
                    }

                    // Check if domains are already used by other workspaces
                    foreach ($domains as $domain) {
                        $exists = Workspace::withoutGlobalScopes()->where('id', '!=', $this->workspace->id)
                            ->whereJsonContains('custom_domains', $domain)
                            ->exists();

                        if ($exists) {
                            $fail("The domain {$domain} is already in use by another workspace.");
                        }
                    }

                    $limit = $this->workspace->custom_domain_count_limit;
                    if ($limit && $domains->count() > $limit) {
                        $fail('You can only add ' . $limit . ' domain(s).');
                    }

                    $this->customDomains = $domains->toArray();
                },
            ],
        ];
    }

    protected function passedValidation()
    {
        $this->replace(['custom_domains' => $this->customDomains]);
    }
}