Skip to content

Commit cb4714f

Browse files
feat: Reflect new default value attribute if it exists
1 parent 08ab1e7 commit cb4714f

2 files changed

Lines changed: 59 additions & 2 deletions

File tree

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?php
2+
3+
namespace Kirby\Reflection\Attributes;
4+
5+
use Attribute;
6+
7+
#[Attribute(Attribute::TARGET_PROPERTY)]
8+
class DefaultValue
9+
{
10+
public function __construct(
11+
protected mixed $value
12+
) {
13+
}
14+
15+
public function value(): mixed
16+
{
17+
return $this->value;
18+
}
19+
}

src/Reflection/Field.php

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,11 @@
33
namespace Kirby\Reflection;
44

55
use Kirby\Form\FieldClass;
6+
use Kirby\Reflection\Attributes\DefaultValue;
67
use ReflectionClass;
8+
use ReflectionParameter;
9+
use ReflectionProperty;
10+
use ReflectionUnionType;
711

812
class Field
913
{
@@ -32,13 +36,47 @@ protected function parentReflection(): static
3236
return new static($this->parentClass()->getName());
3337
}
3438

39+
protected function propDefaultValue(
40+
ReflectionParameter $parameter,
41+
ReflectionProperty|null $property = null
42+
): mixed {
43+
if ($property !== null && $attribute = ($property->getAttributes(DefaultValue::class)[0] ?? null)) {
44+
return $attribute->newInstance()->value();
45+
}
46+
47+
$value = $this->field->{$parameter->getName()}();
48+
49+
return match (true) {
50+
is_object($value) => $value::class,
51+
default => $value
52+
};
53+
}
54+
55+
protected function propType(ReflectionParameter $parameter): string
56+
{
57+
$type = $parameter->getType();
58+
59+
if ($type instanceof ReflectionUnionType) {
60+
return $type;
61+
}
62+
63+
$string = $type->getName();
64+
65+
if ($type->allowsNull() === true) {
66+
$string .= '|null';
67+
}
68+
69+
return $string;
70+
}
71+
3572
/**
3673
* Returns field properties based on the constructor signature.
3774
*/
3875
public function props(): array
3976
{
4077
$props = [];
4178
$ignore = ['model', 'siblings'];
79+
$field = $this->field;
4280

4381
foreach ($this->constructor->getParameters() as $parameter) {
4482
$name = $parameter->getName();
@@ -61,8 +99,8 @@ public function props(): array
6199

62100
$props[$name] = [
63101
'name' => $name,
64-
'type' => (string)$parameter->getType(),
65-
'default' => $parameter->getDefaultValue(),
102+
'type' => $this->propType($parameter),
103+
'default' => $this->propDefaultValue($parameter, $property),
66104
'description' => $comment->description()
67105
];
68106
}

0 commit comments

Comments
 (0)