Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Union types are ignored by validation #941

Open
pluma opened this issue Jan 29, 2025 · 1 comment
Open

Union types are ignored by validation #941

pluma opened this issue Jan 29, 2025 · 1 comment

Comments

@pluma
Copy link

pluma commented Jan 29, 2025

✏️ Describe the bug

Given a Data class with a constructor like this:

__construct(
  public string $id,
  public SomeData|OtherData $thing
) {}

I would expect the validation to first try to validate the parameter $thing using SomeData, then fall back to OtherData and for the first matching type to be used for this property when using ::from($jsonString).

But instead the validator will generate rules for $thing based on the type information of SomeData and only that information because it prioritizes having a fully denormalized list of rules even if it means discarding the alternatives.

There does seem to be actual logic around UnionType in this library but the validator doesn't support it for validation and everything else seems to run downstream from that.

↪️ To Reproduce

it('cannot validate union types', function () {
    class ExampleData extends Data
    {
        public function __construct(
          public string $id,
          public SomeData|OtherData $thing
        ) {
        }
    }

    class SomeData extends Data
    {
        public function __construct(
            #[In('SomeThing')]
            public string|Optional $type,
            public string $taste
        ) {
        }
    }

    class OtherData extends Data
    {
        public function __construct(
            #[In('OtherThing')]
            public string $type,
            public int $size
        ) {
        }
    }

    dd(BaseData::validateAndCreate(['id' => 'abc', 'thing' => ['type' => 'OtherThing', 'size' => 23]]));
});

✅ Expected behavior

I would expect the validator to generate rules matching the union type (i.e. either-or) and validation to succeed with the value being of the matching type (i.e. OtherData in this test case).

🖥️ Versions

Laravel: 11.40.0
Laravel Data: 4.13.0
PHP: 8.3.9

@pluma
Copy link
Author

pluma commented Jan 29, 2025

After digging through the discussions, it seems this is a deliberate choice but I'm not seeing an error indicating that the union types are unsupported. This seems like a weird constraint that I'm unsure how to work around given the real-world data format I'm trying to represent.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant