Skip to content

Commit

Permalink
tmp aaah, what did they doo
Browse files Browse the repository at this point in the history
  • Loading branch information
BacLuc committed Jan 5, 2025
1 parent 5989dd6 commit 57de945
Show file tree
Hide file tree
Showing 5 changed files with 69 additions and 25 deletions.
1 change: 1 addition & 0 deletions api/config/packages/api_platform.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ api_platform:
error_formats:
jsonproblem: [ 'application/problem+json' ]
jsonld: [ 'application/ld+json' ]
jsonhal: [ 'application/hal+json' ]
swagger:
versions: [3]
defaults:
Expand Down
22 changes: 19 additions & 3 deletions api/config/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,27 @@ services:

App\Serializer\Normalizer\CollectionItemsNormalizer:
decorates: 'api_platform.hal.normalizer.collection'

App\Serializer\Normalizer\TranslationConstraintViolationListNormalizer:
decorates: 'api_platform.normalizer.constraint_violation_list'
arguments:
- '@api_platform.hydra.normalizer.constraint_violation_list'
- '@api_platform.problem.normalizer.constraint_violation_list'
- '@.inner'

# api_platform.state.error_provider:
# class: 'App\State\ErrorProvider'
# decorates: 'api_platform.state.error_provider'
# arguments:
# - '@.inner'
# - '@api_platform.hydra.normalizer.constraint_violation_list'
# - '@api_platform.problem.normalizer.constraint_violation_list'


# App\State\ErrorProvider:
# decorates: 'api_platform.validator.state.error_provider'
# arguments:
# - '@.inner'
# - '@api_platform.hydra.normalizer.constraint_violation_list'
# - '@api_platform.problem.normalizer.constraint_violation_list'

App\Serializer\SerializerContextBuilder:
decorates: 'api_platform.serializer.context_builder'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
namespace App\Serializer\Normalizer;

use ApiPlatform\Serializer\AbstractConstraintViolationListNormalizer;
use ApiPlatform\Serializer\ConstraintViolationListNormalizer;
use ApiPlatform\Validator\Exception\ValidationException;
use App\Serializer\Normalizer\Error\TranslationInfoOfConstraintViolation;
use App\Service\TranslateToAllLocalesService;
use Doctrine\Common\Collections\ArrayCollection;
Expand All @@ -16,27 +18,30 @@
* replace with https://api-platform.com/docs/core/errors/#control-your-exceptions
*/
class TranslationConstraintViolationListNormalizer implements NormalizerInterface {
const SUPPORTED_TYPES = ['json', 'jsonld', 'jsonProblem', 'jsonhal'];

public function __construct(
private readonly AbstractConstraintViolationListNormalizer $hydraNormalizer,
private readonly AbstractConstraintViolationListNormalizer $problemNormalizer,
private readonly ConstraintViolationListNormalizer $constraintViolationNormalizer,
private readonly TranslationInfoOfConstraintViolation $translationInfoOfConstraintViolation,
private readonly TranslateToAllLocalesService $translateToAllLocalesService
) {}

public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool {
return $this->getNormalizerCollection()->exists(fn ($_, $elem) => $elem->supportsNormalization($data, $format, $context));
return in_array($format, self::SUPPORTED_TYPES);
}

public function normalize(mixed $data, ?string $format = null, array $context = []): null|array|\ArrayObject|bool|float|int|string {
$normalizer = $this->getNormalizerCollection()->filter(fn ($elem) => $elem->supportsNormalization($data, $format, $context))->first();
if (false === $normalizer) {
throw new \RuntimeException("Did not find a normalizer to normalize response to format {$format}");
$violationList = $data;
if ($data instanceof ValidationException) {
$violationList = $data->getConstraintViolationList();
}
$result = $normalizer->normalize($data, $format, $context);
$violations = $this->constraintViolationNormalizer->normalize($violationList, $format, $context);



/** @var ConstraintViolationList $data */
foreach ($data as $violation) {
foreach ($result['violations'] as &$resultItem) {
foreach ($violationList as $violation) {
foreach ($violations as &$resultItem) {
$code = $resultItem['code'] ?? null;
$propertyPath = $resultItem['propertyPath'];
$message = $resultItem['message'] ?? null;
Expand Down Expand Up @@ -70,19 +75,10 @@ public function normalize(mixed $data, ?string $format = null, array $context =
}
}

return $result;
return $violations;
}

public function getSupportedTypes(?string $format): array {
return $this->getNormalizerCollection()
->map(function (AbstractConstraintViolationListNormalizer $normalizer) use ($format) {
return $normalizer->getSupportedTypes($format);
})
->reduce(fn (?array $left, array $right) => array_merge($left ?? [], $right), [])
;
}

private function getNormalizerCollection(): ArrayCollection {
return new ArrayCollection([$this->hydraNormalizer, $this->problemNormalizer]);
return $this->supportsNormalization([], $format) ? [ConstraintViolationList::class => false, ValidationException::class => false] : [];
}
}
31 changes: 31 additions & 0 deletions api/src/State/ErrorProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace App\State;

use ApiPlatform\Metadata\HttpOperation;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Serializer\AbstractConstraintViolationListNormalizer;
use ApiPlatform\State\ApiResource\Error;
use ApiPlatform\State\ProviderInterface;
use App\Serializer\Normalizer\Error\TranslationInfoOfConstraintViolation;
use App\Service\TranslateToAllLocalesService;

abstract class ErrorProvider implements ProviderInterface
{
public function __construct(
private readonly ProviderInterface $decorated,
private readonly AbstractConstraintViolationListNormalizer $hydraNormalizer,
private readonly AbstractConstraintViolationListNormalizer $problemNormalizer,
private readonly TranslationInfoOfConstraintViolation $translationInfoOfConstraintViolation,
private readonly TranslateToAllLocalesService $translateToAllLocalesService
) {}

public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
{
$error = $this->decorated->provide($operation, $uriVariables, $context);



return $error;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ public function testCreateCampCollaborationInCampPrototypeIsDeniedForUnrelatedUs
}

public function testCreateCampCollaborationValidatesIfInviteEmailIsBlank() {
$response = static::createClientWithCredentials()->request('POST', '/camp_collaborations', ['json' => $this->getExampleWritePayload([
$response = static::createClientWithCredentials(headers: ['Accept' => 'application/json'])->request('POST', '/camp_collaborations', ['json' => $this->getExampleWritePayload([
'inviteEmail' => '',
], ['user'])]);

Expand Down Expand Up @@ -379,7 +379,7 @@ public function testCreateCampCollaborationValidatesMissingUserAndInviteEmail()
}

public function testCreateCampCollaborationValidatesMissingUserAndInviteEmailAndIncludesTranslationInfo() {
static::createClientWithCredentials()->request('POST', '/camp_collaborations', ['json' => $this->getExampleWritePayload([], ['user'])]);
$response = static::createClientWithCredentials()->request('POST', '/camp_collaborations', ['json' => $this->getExampleWritePayload([], ['user'])]);

$this->assertResponseStatusCodeSame(422);
$this->assertJsonContains([
Expand Down

0 comments on commit 57de945

Please sign in to comment.