GraphQL Validate Enum with rule in Lighthouse

In Lighthouse I have an Enum like this

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><?php
namespace AppEnums;
use GraphQLTypeDefinitionDescription;
#[Description(description: 'Size')]
enum Size: string
{
case S = 's';
case M = 'm';
case L = 'l';
case XL = 'xl';
}
</code>
<code><?php namespace AppEnums; use GraphQLTypeDefinitionDescription; #[Description(description: 'Size')] enum Size: string { case S = 's'; case M = 'm'; case L = 'l'; case XL = 'xl'; } </code>
<?php

namespace AppEnums;

use GraphQLTypeDefinitionDescription;

#[Description(description: 'Size')]

enum Size: string
{
    case S = 's';
    case M = 'm';
    case L = 'l';
    case XL = 'xl';
}

In a service provider I register it like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> $typeRegistry->register(new PhpEnumType(Size::class));
</code>
<code> $typeRegistry->register(new PhpEnumType(Size::class)); </code>
    $typeRegistry->register(new PhpEnumType(Size::class));

This works all fine.

Now, for some input I want to validate it so that only L and XL are valid for mySize

I was thinking something like this

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>input SomeInput {
mySize: Size @rules(apply: ["in:L,XL"])
}
</code>
<code>input SomeInput { mySize: Size @rules(apply: ["in:L,XL"]) } </code>
input SomeInput {
    mySize: Size @rules(apply: ["in:L,XL"])
}

But this throws an error

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>"statusCode": 500,
"debugMessage": "Object of class App\Enums\Size could not be converted to string",
"file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Validation/Concerns/ValidatesAttributes.php",
</code>
<code>"statusCode": 500, "debugMessage": "Object of class App\Enums\Size could not be converted to string", "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Validation/Concerns/ValidatesAttributes.php", </code>
"statusCode": 500,
"debugMessage": "Object of class App\Enums\Size could not be converted to string",
"file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Validation/Concerns/ValidatesAttributes.php",

Is there a way to accomplish this without creating my own custom rule?

Since there doesn’t seem to be any way check using just what Lighthouse provides I eneded up creating my own custom rule:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><?php
declare(strict_types=1);
namespace AppRules;
use BackedEnum;
use Closure;
use Exception;
use IlluminateContractsValidationValidationRule;
use IlluminateSupportArr;
use IlluminateSupportFacadesValidator;
use IlluminateValidationValidator as ValidationValidator;
use ReflectionClass;
class InEnum implements ValidationRule
{
public static function register(): void
{
Validator::extend('in_enum', self::class . '@passes');
Validator::replacer('in_enum', function ($message, $attribute, $rule, $parameters, $validator) {
$data = $validator->getData();
$value = Arr::get($data, $attribute);
return (new self)->message($value, $parameters);
});
}
/**
* @var array<int,string> $parameters
*/
private array $parameters;
/**
* @param array<int,string> $parameters
*/
public function __construct(array $parameters = [])
{
$this->parameters = $parameters;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message(BackedEnum $value, array $parameters): string
{
return __('general.validation.in_enum', ['enumClass' => (new ReflectionClass($value))->getShortName(), 'enumValue' => strtoupper($value->value), 'validValues' => implode(', ', $parameters)]);
}
/**
* Check if the rule passes based on the given arguments.
* @param string $attribute
* @param BackedEnum | null $value If $value is `null` the rule passes. To prevent this add a "required" rule as well.
* @param array<int,string> $parameters
* @return bool
*/
public function passes(string $attribute, BackedEnum|null $value, array $parameters, ValidationValidator|null $validator = null): bool
{
return ($value == null) || in_array(strtoupper($value->value), $parameters);
}
/**
* Run the validation rule.
* @param string $attribute
* @param mixed $value
* @param Closure(string): PotentiallyTranslatedString $fail
* @return void
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
throw new Exception('This functionality has not been implemented yet!');
}
}
</code>
<code><?php declare(strict_types=1); namespace AppRules; use BackedEnum; use Closure; use Exception; use IlluminateContractsValidationValidationRule; use IlluminateSupportArr; use IlluminateSupportFacadesValidator; use IlluminateValidationValidator as ValidationValidator; use ReflectionClass; class InEnum implements ValidationRule { public static function register(): void { Validator::extend('in_enum', self::class . '@passes'); Validator::replacer('in_enum', function ($message, $attribute, $rule, $parameters, $validator) { $data = $validator->getData(); $value = Arr::get($data, $attribute); return (new self)->message($value, $parameters); }); } /** * @var array<int,string> $parameters */ private array $parameters; /** * @param array<int,string> $parameters */ public function __construct(array $parameters = []) { $this->parameters = $parameters; } /** * Get the validation error message. * * @return string */ public function message(BackedEnum $value, array $parameters): string { return __('general.validation.in_enum', ['enumClass' => (new ReflectionClass($value))->getShortName(), 'enumValue' => strtoupper($value->value), 'validValues' => implode(', ', $parameters)]); } /** * Check if the rule passes based on the given arguments. * @param string $attribute * @param BackedEnum | null $value If $value is `null` the rule passes. To prevent this add a "required" rule as well. * @param array<int,string> $parameters * @return bool */ public function passes(string $attribute, BackedEnum|null $value, array $parameters, ValidationValidator|null $validator = null): bool { return ($value == null) || in_array(strtoupper($value->value), $parameters); } /** * Run the validation rule. * @param string $attribute * @param mixed $value * @param Closure(string): PotentiallyTranslatedString $fail * @return void */ public function validate(string $attribute, mixed $value, Closure $fail): void { throw new Exception('This functionality has not been implemented yet!'); } } </code>
<?php

declare(strict_types=1);

namespace AppRules;

use BackedEnum;
use Closure;
use Exception;
use IlluminateContractsValidationValidationRule;
use IlluminateSupportArr;
use IlluminateSupportFacadesValidator;
use IlluminateValidationValidator as ValidationValidator;
use ReflectionClass;

class InEnum implements ValidationRule
{

    public static function register(): void
    {
        Validator::extend('in_enum', self::class . '@passes');
        Validator::replacer('in_enum', function ($message, $attribute, $rule, $parameters, $validator) {
            $data = $validator->getData();
            $value = Arr::get($data, $attribute);
            return (new self)->message($value, $parameters);
        });
    }

    /**
     * @var array<int,string> $parameters
     */
    private array $parameters;

    /**
     * @param array<int,string> $parameters
     */
    public function __construct(array $parameters = [])
    {
        $this->parameters = $parameters;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message(BackedEnum $value, array $parameters): string
    {
        return __('general.validation.in_enum', ['enumClass' => (new ReflectionClass($value))->getShortName(), 'enumValue' => strtoupper($value->value), 'validValues' => implode(', ', $parameters)]);
    }

    /**
     * Check if the rule passes based on the given arguments.
     * @param string $attribute
     * @param BackedEnum | null $value If $value is `null` the rule passes. To prevent this add a "required" rule as well.
     * @param array<int,string> $parameters
     * @return bool
     */
    public function passes(string $attribute, BackedEnum|null $value, array $parameters, ValidationValidator|null $validator = null): bool
    {
        return ($value == null) || in_array(strtoupper($value->value), $parameters);
    }

    /**
     * Run the validation rule.
     * @param string $attribute
     * @param mixed $value
     * @param Closure(string): PotentiallyTranslatedString $fail
     * @return void
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        throw new Exception('This functionality has not been implemented yet!');
    }
}

It can be registered in the boot of the AppServiceProvider like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> /**
* Bootstrap any application services.
*/
public function boot(): void
{
InEnum::register();
}
</code>
<code> /** * Bootstrap any application services. */ public function boot(): void { InEnum::register(); } </code>
    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        InEnum::register();
    }

..and used like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>input SomeInput {
mySize: Size @rules(apply: ["in_enum:L,XL"])
}
</code>
<code>input SomeInput { mySize: Size @rules(apply: ["in_enum:L,XL"]) } </code>
input SomeInput {
    mySize: Size @rules(apply: ["in_enum:L,XL"])
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật