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

Point to the right problem on ArgumentCountError exception #884

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions src/Exceptions/CannotCreateData.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ public static function noNormalizerFound(string $dataClass, mixed $value): self
public static function constructorMissingParameters(
DataClass $dataClass,
array $parameters,
Throwable $previous,
): self {
$parameters = collect($parameters);

Expand All @@ -42,6 +41,6 @@ public static function constructorMissingParameters(
->map(fn (DataProperty|DataParameter $parameter) => $parameter->name)
->join(', ')}.";

return new self($message, previous: $previous);
return new self($message);
}
}
17 changes: 13 additions & 4 deletions src/Resolvers/DataFromArrayResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -91,14 +91,23 @@ protected function createData(
}
}

try {
return new $dataClass->name(...$parameters);
} catch (ArgumentCountError $error) {
if ($this->isAnyParameterMissing($dataClass, array_keys($parameters))) {
Copy link
Contributor

@Tofandel Tofandel Oct 20, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if ($this->isAnyParameterMissing($dataClass, array_keys($parameters))) {
try {
return new $dataClass->name(...$parameters);
} catch (ArgumentCountError $error) {
$trace = current($error->getTrace());
if ($trace && $trace['function'] === '__construct' && $trace['class'] === (new \ReflectionMethod($dataClass->name, '__construct'))->getDeclaringClass()->getName()) {
throw CannotCreateData::constructorMissingParameters(
$dataClass,
$parameters,
$error
);
} else {
throw $error;
}
}

throw CannotCreateData::constructorMissingParameters(
$dataClass,
$parameters,
$error
);
}

return new $dataClass->name(...$parameters);
}

protected function isAnyParameterMissing(DataClass $dataClass, array $parameters): bool
{
return $dataClass
->constructorMethod
->parameters
->pluck('name')
Copy link
Contributor

@Tofandel Tofandel Oct 25, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
->pluck('name')
->filter(fn (\Spatie\LaravelData\Support\DataParameter $p) => !$parameter->hasDefaultValue)
->pluck('name')

Copy link
Contributor

@Tofandel Tofandel Oct 25, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't this filter out required parameters as well, which do not have a default value?

It would keep only parameters without default values aka required ones, though there is one obscure area, is if you have a default value before a required param (which normally emits a warning)

Which is why filtering on is optional would provide the perfect solution, as it would work with variadic parameters, but it would need to be added to the DataParameter class and factory..
Or a new Reflection needs to be made on the spot

->diff($parameters)
->isNotEmpty();
}
}
13 changes: 13 additions & 0 deletions tests/CreationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use Illuminate\Support\Facades\Route;
use Illuminate\Validation\ValidationException;

use Spatie\LaravelData\Tests\Fakes\DataWithArgumentCountErrorException;
use function Pest\Laravel\postJson;

use Spatie\LaravelData\Attributes\Computed;
Expand Down Expand Up @@ -751,6 +752,18 @@ public function __construct(
yield 'one param' => [['first' => 'First'], 'Could not create `Spatie\LaravelData\Tests\Fakes\MultiData`: the constructor requires 2 parameters, 1 given. Parameters given: first. Parameters missing: second.'],
]);

it('throws a readable exception message when the ArgumentCountError exception is thrown in the constructor', function () {
try {
DataWithArgumentCountErrorException::from(['string' => 'string']);
} catch (ArgumentCountError $e) {
expect($e->getMessage())->toBe('This function expects exactly 2 arguments, 1 given.');
expect($e->getFile())->toContain('/tests/Fakes/DataWithArgumentCountErrorException.php');
expect($e->getLine())->toBe(13);

return;
}
});

it('throws a readable exception message when the constructor of a nested data object fails', function () {
expect(fn () => NestedData::from([
'simple' => [],
Expand Down
15 changes: 15 additions & 0 deletions tests/Fakes/DataWithArgumentCountErrorException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace Spatie\LaravelData\Tests\Fakes;

use ArgumentCountError;
use Spatie\LaravelData\Data;

class DataWithArgumentCountErrorException extends Data
{
public function __construct(
public string $string,
) {
throw new ArgumentCountError('This function expects exactly 2 arguments, 1 given.');
}
}