refactore method addRemoveSomething, and add test for resources

This commit is contained in:
2021-05-13 16:28:03 +02:00
parent 01f35eed04
commit 05798688d0
3 changed files with 202 additions and 54 deletions

View File

@@ -14,6 +14,7 @@ use Chill\PersonBundle\Privacy\AccompanyingPeriodPrivacyEvent;
use Chill\PersonBundle\Entity\Person;
use Chill\ThirdPartyBundle\Entity\ThirdParty;
use Symfony\Component\Serializer\Exception\RuntimeException;
use Chill\PersonBundle\Entity\AccompanyingPeriod\Resource;
class AccompanyingCourseApiController extends ApiController
{
@@ -67,53 +68,9 @@ class AccompanyingCourseApiController extends ApiController
public function resourceApi($id, Request $request, string $_format): Response
{
return $this->addRemoveSomething('resource', $id, $request, $_format, 'resource',
\Chill\PersonBundle\Entity\AccompanyingPeriod\Resource::class);
return $this->addRemoveSomething('resource', $id, $request, $_format, 'resource', Resource::class);
}
public function addRemoveSomething(string $action, $id, Request $request, string $_format, $property, string $postedDataType, $postedDataContext = []): Response
{
$entity = $this->getEntity($action, $id, $request);
$this->checkACL($action, $request, $_format, $entity);
$this->onPostCheckACL($action, $request, $_format, $entity);
try {
$postedData = $this->getSerializer()->deserialize($request->getContent(), $postedDataType, $_format, $postedDataContext);
} catch (\Symfony\Component\Serializer\Exception\UnexpectedValueException $e) {
throw new BadRequestException(sprintf("Unable to deserialize posted ".
"data: %s", $e->getMessage()), 0, $e);
}
switch ($request->getMethod()) {
case Request::METHOD_DELETE:
// oups... how to use property accessor to remove element ?
$entity->{'remove'.\ucfirst($property)}($postedData);
break;
case Request::METHOD_POST:
$entity->{'add'.\ucfirst($property)}($postedData);
break;
default:
throw new BadRequestException("this method is not supported");
}
$errors = $this->validator->validate($entity);
if ($errors->count() > 0) {
// only format accepted
return $this->json($errors, 422);
}
$this->getDoctrine()->getManager()->flush();
switch ($request->getMethod()) {
case Request::METHOD_DELETE:
return $this->json('', 202);
case Request::METHOD_POST:
return $this->json($postedData, 200, [], ['groups' => [ 'read' ]]);
}
}
public function requestorApi($id, Request $request, string $_format): Response
{