Skip to content

Commit cc2a3c7

Browse files
authored
Merge pull request #8 from jakeworrall/move-validation-logic
Move required properties check to value class constructor
2 parents fd656b1 + d0f6ee2 commit cc2a3c7

2 files changed

Lines changed: 20 additions & 14 deletions

File tree

src/BuilderClass/BuildMethodGenerator.php

Lines changed: 0 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -25,20 +25,6 @@ public function generateMethods(ReflectionMethodCollection $matchedMethods, Prop
2525
$methodBody = <<<THEPHP
2626
return $valueAutoClass::___withTrustedValues(\$this->propertyValues);
2727
THEPHP;
28-
$requiredProperties = $properties
29-
->filter(function (Property $property) { return $property->isRequired(); })
30-
->propertyNames();
31-
if ($requiredProperties) {
32-
$requiredPropertiesExported = \implode(', ', \array_map(function ($property) { return "'$property'"; }, $requiredProperties));
33-
$methodBody = <<<THEPHP
34-
foreach ([$requiredPropertiesExported] as \$property) {
35-
if (!isset(\$this->propertyValues[\$property])) {
36-
throw new \Exception("Required property \$property not initialized.");
37-
}
38-
}
39-
$methodBody
40-
THEPHP;
41-
}
4228
return $methodDefinitions->withAdditionalMethodDefinition(MethodDefinition::of($method, $methodBody));
4329
});
4430
}

src/ValueClass/ValueClassGenerator.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,12 @@ public function generateClass(ReflectionClass $baseClass, PropertyCollection $pr
2828
return generateConcreteMethod($methodDefinition->reflection(), $methodDefinition->body());
2929
}));
3030

31+
$requiredProperties = $properties
32+
->filter(function (Property $property) { return $property->isRequired(); })
33+
->propertyNames();
34+
35+
$requiredPropertiesExported = \implode(', ', \array_map(function ($property) { return "'$property'"; }, $requiredProperties));
36+
3137
return <<<THEPHP
3238
namespace {$baseClass->getNamespaceName()};
3339
@@ -40,12 +46,26 @@ final class AutoValue_{$baseClass->getShortName()} extends {$baseClass->getShort
4046
4147
protected function __construct(array \$propertyValues = [])
4248
{
49+
self::___checkRequiredPropertiesExist(\$propertyValues);
50+
4351
foreach (\$propertyValues as \$property => \$value) {
4452
\$this->\$property = \$value;
4553
}
4654
}
4755
4856
$methodDeclarations
57+
58+
/**
59+
* @internal
60+
*/
61+
public static function ___checkRequiredPropertiesExist(array \$propertyValues): void
62+
{
63+
foreach ([$requiredPropertiesExported] as \$property) {
64+
if (!isset(\$propertyValues[\$property])) {
65+
throw new \Exception("Required property \$property not initialized.");
66+
}
67+
}
68+
}
4969
5070
/**
5171
* @internal

0 commit comments

Comments
 (0)