Skip to content

Commit

Permalink
Merge pull request #8 from jakeworrall/move-validation-logic
Browse files Browse the repository at this point in the history
Move required properties check to value class constructor
  • Loading branch information
joshdifabio authored May 3, 2019
2 parents fd656b1 + d0f6ee2 commit cc2a3c7
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 14 deletions.
14 changes: 0 additions & 14 deletions src/BuilderClass/BuildMethodGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,20 +25,6 @@ public function generateMethods(ReflectionMethodCollection $matchedMethods, Prop
$methodBody = <<<THEPHP
return $valueAutoClass::___withTrustedValues(\$this->propertyValues);
THEPHP;
$requiredProperties = $properties
->filter(function (Property $property) { return $property->isRequired(); })
->propertyNames();
if ($requiredProperties) {
$requiredPropertiesExported = \implode(', ', \array_map(function ($property) { return "'$property'"; }, $requiredProperties));
$methodBody = <<<THEPHP
foreach ([$requiredPropertiesExported] as \$property) {
if (!isset(\$this->propertyValues[\$property])) {
throw new \Exception("Required property \$property not initialized.");
}
}
$methodBody
THEPHP;
}
return $methodDefinitions->withAdditionalMethodDefinition(MethodDefinition::of($method, $methodBody));
});
}
Expand Down
20 changes: 20 additions & 0 deletions src/ValueClass/ValueClassGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ public function generateClass(ReflectionClass $baseClass, PropertyCollection $pr
return generateConcreteMethod($methodDefinition->reflection(), $methodDefinition->body());
}));

$requiredProperties = $properties
->filter(function (Property $property) { return $property->isRequired(); })
->propertyNames();

$requiredPropertiesExported = \implode(', ', \array_map(function ($property) { return "'$property'"; }, $requiredProperties));

return <<<THEPHP
namespace {$baseClass->getNamespaceName()};
Expand All @@ -40,12 +46,26 @@ final class AutoValue_{$baseClass->getShortName()} extends {$baseClass->getShort
protected function __construct(array \$propertyValues = [])
{
self::___checkRequiredPropertiesExist(\$propertyValues);
foreach (\$propertyValues as \$property => \$value) {
\$this->\$property = \$value;
}
}
$methodDeclarations
/**
* @internal
*/
public static function ___checkRequiredPropertiesExist(array \$propertyValues): void
{
foreach ([$requiredPropertiesExported] as \$property) {
if (!isset(\$propertyValues[\$property])) {
throw new \Exception("Required property \$property not initialized.");
}
}
}
/**
* @internal
Expand Down

0 comments on commit cc2a3c7

Please sign in to comment.