33namespace Kirby \Reflection ;
44
55use Kirby \Form \FieldClass ;
6+ use Kirby \Reflection \Attributes \DefaultValue ;
67use ReflectionClass ;
8+ use ReflectionParameter ;
9+ use ReflectionProperty ;
10+ use ReflectionUnionType ;
711
812class 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