Skip to content

Commit 702e951

Browse files
committed
Set a property as an id to use objects as types
1 parent 1fdcfb1 commit 702e951

File tree

4 files changed

+32
-3
lines changed

4 files changed

+32
-3
lines changed

src/Attributes/IDParam.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,29 @@ public function __construct(
2424

2525
public function setParamType(string $paramType): void
2626
{
27+
// With frameworks' auto wiring, objects are injected as arguments.
28+
// If the object has a Property(Type::STRING, isObjectId: true), use the type of the
29+
// property (string for this example)
30+
if (class_exists($paramType)) {
31+
$reflection = new \ReflectionClass($paramType);
32+
$attributes = $reflection->getAttributes();
33+
$paramType = array_reduce(
34+
$attributes,
35+
function (?string $previous, \ReflectionAttribute $attribute) {
36+
if ($previous) {
37+
return $previous;
38+
}
39+
40+
$instance = $attribute->newInstance();
41+
if ($instance instanceof Property && $instance->isObjectId()) {
42+
return $instance->getType();
43+
}
44+
45+
return null;
46+
}
47+
);
48+
}
49+
2750
$this->schema = match ($paramType) {
2851
'int' => ['type' => 'integer', 'minimum' => 1],
2952
'bool' => ['type' => 'boolean'],

src/Attributes/Property.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@ public function __construct(
2525
private mixed $example = null,
2626
private ?string $format = null,
2727
private ?array $enum = null,
28-
private ?string $ref = null
28+
private ?string $ref = null,
29+
private bool $isObjectId = false,
2930
) {
3031
if ($this->ref) {
3132
$ref = explode('\\', $this->ref);
@@ -49,6 +50,11 @@ public function getProperty(): ?string
4950
return $this->property;
5051
}
5152

53+
public function isObjectId(): bool
54+
{
55+
return $this->isObjectId;
56+
}
57+
5258
public function jsonSerialize(): array
5359
{
5460
$type = $this->type;

tests/Examples/Dummy/DummyController.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ public function post(): void
8080
PUT("/path/{id}", ["Dummy"], "Dummy put"),
8181
Response(204)
8282
]
83-
public function put(#[IDParam] int $id, DummyRequest $dummyRequest): void
83+
public function put(#[IDParam] DummyRefComponent $id, DummyRequest $dummyRequest): void
8484
{
8585
//
8686
}

tests/Examples/Dummy/DummyRefComponent.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
#[
1313
Schema(SchemaType::OBJECT),
14-
Property(PropertyType::STRING, "prop1", "Prop1 description", "Value 1"),
14+
Property(PropertyType::STRING, "prop1", "Prop1 description", "Value 1", isObjectId: true),
1515
Property(PropertyType::INT, "prop2", example: "Value2"),
1616
]
1717
class DummyRefComponent

0 commit comments

Comments
 (0)