Skip to content

Commit

Permalink
Set a property as an id to use objects as types
Browse files Browse the repository at this point in the history
  • Loading branch information
uderline committed May 31, 2022
1 parent 1fdcfb1 commit 702e951
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 3 deletions.
23 changes: 23 additions & 0 deletions src/Attributes/IDParam.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,29 @@ public function __construct(

public function setParamType(string $paramType): void
{
// With frameworks' auto wiring, objects are injected as arguments.
// If the object has a Property(Type::STRING, isObjectId: true), use the type of the
// property (string for this example)
if (class_exists($paramType)) {
$reflection = new \ReflectionClass($paramType);
$attributes = $reflection->getAttributes();
$paramType = array_reduce(
$attributes,
function (?string $previous, \ReflectionAttribute $attribute) {
if ($previous) {
return $previous;
}

$instance = $attribute->newInstance();
if ($instance instanceof Property && $instance->isObjectId()) {
return $instance->getType();
}

return null;
}
);
}

$this->schema = match ($paramType) {
'int' => ['type' => 'integer', 'minimum' => 1],
'bool' => ['type' => 'boolean'],
Expand Down
8 changes: 7 additions & 1 deletion src/Attributes/Property.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ public function __construct(
private mixed $example = null,
private ?string $format = null,
private ?array $enum = null,
private ?string $ref = null
private ?string $ref = null,
private bool $isObjectId = false,
) {
if ($this->ref) {
$ref = explode('\\', $this->ref);
Expand All @@ -49,6 +50,11 @@ public function getProperty(): ?string
return $this->property;
}

public function isObjectId(): bool
{
return $this->isObjectId;
}

public function jsonSerialize(): array
{
$type = $this->type;
Expand Down
2 changes: 1 addition & 1 deletion tests/Examples/Dummy/DummyController.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public function post(): void
PUT("/path/{id}", ["Dummy"], "Dummy put"),
Response(204)
]
public function put(#[IDParam] int $id, DummyRequest $dummyRequest): void
public function put(#[IDParam] DummyRefComponent $id, DummyRequest $dummyRequest): void
{
//
}
Expand Down
2 changes: 1 addition & 1 deletion tests/Examples/Dummy/DummyRefComponent.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

#[
Schema(SchemaType::OBJECT),
Property(PropertyType::STRING, "prop1", "Prop1 description", "Value 1"),
Property(PropertyType::STRING, "prop1", "Prop1 description", "Value 1", isObjectId: true),
Property(PropertyType::INT, "prop2", example: "Value2"),
]
class DummyRefComponent
Expand Down

0 comments on commit 702e951

Please sign in to comment.