You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The `ObjectConstructorSchema` parses an associative array (or compatible input) and constructs an instance of a given class by passing validated fields to its constructor.
Make certain fields optional in the input. If an optional field is missing from the input, it won't be passed to the constructor (so the constructor parameter must be optional).
78
+
79
+
```php
80
+
class User
81
+
{
82
+
public function __construct(
83
+
public readonly string $name,
84
+
public readonly string $nickname = ''
85
+
) {}
86
+
}
87
+
88
+
$schema = $p->objectConstructor([
89
+
'name' => $p->string(),
90
+
'nickname' => $p->string(),
91
+
], User::class)->optional(['nickname']);
92
+
93
+
$schema->parse(['name' => 'John']);
94
+
// Returns: User(name: 'John', nickname: '') - using default value from constructor
thrownew \InvalidArgumentException('Missing fieldToSchema for "'.$classname.'" __construct parameters: "'.implode('", "', $missingFieldToSchema).'"');
67
+
thrownew \InvalidArgumentException(
68
+
'Missing fieldToSchema for "'.$classname.'" __construct parameters: "'
69
+
.implode('", "', $missingFieldToSchema).'"'
70
+
);
57
71
}
58
72
59
73
if ([] !== $fieldToSchema) {
60
-
thrownew \InvalidArgumentException('Additional fieldToSchema for "'.$classname.'" __construct parameters: "'.implode('", "', array_keys($fieldToSchema)).'"');
74
+
thrownew \InvalidArgumentException(
75
+
'Additional fieldToSchema for "'.$classname.'" __construct parameters: "'
76
+
.implode('", "', array_keys($fieldToSchema)).'"'
77
+
);
61
78
}
62
79
63
-
$this->typeErrorPattern = \sprintf('/%s::__construct\(\): Argument #(\d+) \(([^)]+)\) must be of type ([^ ]+), ([^ ]+) given/', preg_quote($this->classname, '/'));
0 commit comments