Skip to content

Commit 699c5e4

Browse files
committed
feat(metadata): expose a default attribute on parameters
1 parent 325a04c commit 699c5e4

File tree

2 files changed

+38
-4
lines changed

2 files changed

+38
-4
lines changed

src/Metadata/Parameter.php

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ public function __construct(
5656
protected ?bool $castToArray = null,
5757
protected ?bool $castToNativeType = null,
5858
protected mixed $castFn = null,
59+
protected mixed $default = null,
5960
) {
6061
}
6162

@@ -139,7 +140,7 @@ public function getSecurityMessage(): ?string
139140
*/
140141
public function getValue(mixed $default = new ParameterNotFound()): mixed
141142
{
142-
return $this->extraProperties['_api_values'] ?? $default;
143+
return $this->extraProperties['_api_values'] ?? $this->default ?? $default;
143144
}
144145

145146
/**
@@ -370,4 +371,12 @@ public function withCastFn(mixed $castFn): self
370371

371372
return $self;
372373
}
374+
375+
public function withDefault(mixed $default): self
376+
{
377+
$self = clone $this;
378+
$self->default = $default;
379+
380+
return $self;
381+
}
373382
}

src/Metadata/Tests/ParameterTest.php

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,16 +13,41 @@
1313

1414
namespace ApiPlatform\Metadata\Tests;
1515

16+
use ApiPlatform\Metadata\Parameter;
1617
use ApiPlatform\Metadata\QueryParameter;
1718
use ApiPlatform\State\ParameterNotFound;
19+
use PHPUnit\Framework\Attributes\DataProvider;
1820
use PHPUnit\Framework\TestCase;
1921

2022
class ParameterTest extends TestCase
2123
{
2224
public function testDefaultValue(): void
2325
{
24-
$parameter = new QueryParameter();
25-
$this->assertSame('test', $parameter->getValue('test'));
26-
$this->assertInstanceOf(ParameterNotFound::class, $parameter->getValue());
26+
$this->assertInstanceOf(ParameterNotFound::class, (new QueryParameter())->getValue());
27+
}
28+
29+
#[DataProvider('provideDefaultValueCases')]
30+
public function testDefaultValueWithFallbackValue(Parameter $parameter, mixed $fallbackValue, mixed $expectedDefault): void
31+
{
32+
$this->assertSame($expectedDefault, $parameter->getValue($fallbackValue));
33+
}
34+
35+
36+
/** @return iterable<[Parameter, mixed, mixed]> */
37+
public static function provideDefaultValueCases(): iterable
38+
{
39+
$fallbackValue = new ParameterNotFound();
40+
41+
yield 'no default specified' => [
42+
new QueryParameter(), $fallbackValue, $fallbackValue,
43+
];
44+
45+
yield 'with a default specified' => [
46+
new QueryParameter(default: false), $fallbackValue, false,
47+
];
48+
49+
yield 'with null as default' => [
50+
new QueryParameter(default: null), $fallbackValue, $fallbackValue,
51+
];
2752
}
2853
}

0 commit comments

Comments
 (0)