From 13065597f216e4a0d92adc119a6088ae3f0dd1d0 Mon Sep 17 00:00:00 2001 From: Tim Nagel Date: Sun, 19 May 2019 08:11:18 +1000 Subject: [PATCH] Add validation groups callback --- Request/RequestBodyParamConverter.php | 8 ++++++- .../Request/RequestBodyParamConverterTest.php | 24 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/Request/RequestBodyParamConverter.php b/Request/RequestBodyParamConverter.php index 92142c287..67d021d79 100644 --- a/Request/RequestBodyParamConverter.php +++ b/Request/RequestBodyParamConverter.php @@ -108,7 +108,13 @@ public function apply(Request $request, ParamConverter $configuration) if (null !== $this->validator && (!isset($options['validate']) || $options['validate'])) { $validatorOptions = $this->getValidatorOptions($options); - $errors = $this->validator->validate($object, null, $validatorOptions['groups']); + $groups = $validatorOptions['groups']; + if (\is_callable($groups)) { + // If the groups option is callable, resolve it + $groups = $groups($object, $request); + } + + $errors = $this->validator->validate($object, null, $groups); $request->attributes->set( $this->validationErrorsArgument, diff --git a/Tests/Request/RequestBodyParamConverterTest.php b/Tests/Request/RequestBodyParamConverterTest.php index aaec5fef3..a7ef99895 100644 --- a/Tests/Request/RequestBodyParamConverterTest.php +++ b/Tests/Request/RequestBodyParamConverterTest.php @@ -150,6 +150,30 @@ public function testValidatorParameters() $this->assertEquals('fooError', $request->attributes->get('errors')); } + public function testValidatorGroupsCallback() + { + $this->serializer + ->expects($this->once()) + ->method('deserialize') + ->willReturn('Object'); + + $validator = $this->getMockBuilder('Symfony\Component\Validator\Validator\ValidatorInterface')->getMock(); + $validator + ->expects($this->once()) + ->method('validate') + ->with('Object', null, ['Group', 'Object', 'json']); + + $converter = new RequestBodyParamConverter($this->serializer, null, null, $validator, 'errors'); + + $groupsCallback = static function ($object, Request $request) { + return ['Group', $object, $request->getContentType()]; + }; + + $request = $this->createRequest(null, 'application/json'); + $configuration = $this->createConfiguration(null, null, ['validator' => ['groups' => $groupsCallback]]); + $this->launchExecution($converter, $request, $configuration); + } + public function testValidatorSkipping() { $this->serializer