We're developing an API on top of Symfony 5 using Doctrine ODM and MongoDB as well as API Platform. Problem is trying to support PUT operations.
What we find is that if we PUT a JSON document with some fields not included, the object (eg $data) seems to have those fields filled in from the original document in the database.
In some cases, this means that the document passed in via the PUT request will pass validations such as NotBlank() when the document coming n over the wire is missing a required field, but the $data object being validated has that field filled in from the database prior to validation.
As an example, if the original JSON document in Mongo is
{
projectID: "ABCD",
projectName: "My Project",
cost: 100
}
And assuming projectName is a required field and we PUT the following document to our endpoint /v1/example-endpoint/ABCD
{
cost: 100
}
then in out custom data persister we have the following:
public function persist($data, array $context = [])
{
...do something here...
}
The $data object passed in to the persister will include the previous projectName "My Project" from the database.
Is this expected behavior and/or is there a way around this to validate the data sent over the wire as-is?
FWIW, we tried created a new Object of the class and setting the data from the PUT content, then creating a validator and validating the new object, but ran in to an issue where custom validation methods that had constructors were not being autowired when calling the validator manually. If we could successfully validate the new object that would work too.
$putData = json_decode($this->requestStack->getCurrentRequest()->getContent(), true);
$newProject = (new Project());
foreach ($putData as $property => $value) {
$newProject->setProperty($property, $value);
}
$validator = Validation::createValidatorBuilder()
->addMethodMapping('loadValidatorMetadata')
->getValidator();
$errors = $validator->validate($newProject);