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

Parameters check bug #882

Open
nsvetozarevic opened this issue Oct 10, 2024 · 1 comment · May be fixed by #884
Open

Parameters check bug #882

nsvetozarevic opened this issue Oct 10, 2024 · 1 comment · May be fixed by #884

Comments

@nsvetozarevic
Copy link

nsvetozarevic commented Oct 10, 2024

✏️ Describe the bug
I encountered a rare edge case, which took me quite some time to debug, so I thought it might be useful for every one.
If you need to do any kind of operation in the class's constructor, and something throws ArgumentCountError exception, the package will show the exception message that does not point to the real problem.

↪️ To Reproduce

it('bug-test', function () {
    class ExampleTestData extends Data
    {
        public function __construct(
            public int $id,
            public string $name,
        ) {
            // Method that throws the `ArgumentCountError` exception
            array_key_exists('test');
        }
    }

    $test = ExampleTestData::from(['id' => 1, 'name' => 'test']);
});

✅ Expected behavior
So the error message was something like: Could not create ExampleTestData: the constructor requires 2 parameters, 2 given. Parameters given: id, name. Parameters missing: .

If you guys are interested, I could try to submit a PR to fix it?
I made it to work with the changes to DataFromArrayResolver. Instead of checking for ArgumentCountError exception, I added a method to check if all the parameters are supplied. That way, If an ArgumentCountError is thrown it would point to the direct issue.

    if (! $this->allParametersSupplied($dataClass, array_keys($parameters))) {
        throw CannotCreateData::constructorMissingParameters(
            $dataClass,
            $parameters
        );
     }

    protected function allParametersSupplied(DataClass $dataClass, array $parameters): bool
    {
        $dataClassConstructorParameters = $dataClass->constructorMethod->parameters->pluck('name')->toArray();
        
        return count(array_diff($dataClassConstructorParameters, $parameters)) === 0;
    }

CannotCreateData::constructorMissingParameters() would have to be updated as well as there would be no $previous Throwable.

🖥️ Versions

Laravel: 11.27.2
Laravel Data: 4.10.1
PHP: 8.3.3

@rubenvanassche
Copy link
Member

Hmm good catch, you're certainly welcome to send in a PR!

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