<?php
namespace App\Serializer;
use App\Service\SubscriptionUtils;
use Evo\Infrastructure\MappingORM\Organization;
use Symfony\Component\Serializer\Exception\ExceptionInterface;
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
class OrganizationNormalizer implements ContextAwareNormalizerInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;
private const ALREADY_CALLED = 'ORGANIZATION_NORMALIZER_ALREADY_CALLED';
private SubscriptionUtils $subscriptionUtils;
public function __construct(
SubscriptionUtils $subscriptionUtils
) {
$this->subscriptionUtils = $subscriptionUtils;
}
/**
* @param Organization $object
*
* @throws ExceptionInterface
*/
public function normalize($object, $format = null, array $context = [])
{
$context[self::ALREADY_CALLED] = true;
$normalizedData = $this->normalizer->normalize($object, $format, $context);
if (($object instanceof Organization) && is_array($normalizedData)) {
$packs = [];
foreach ($object->getSubscriptions() as $subscription) {
$packs[] = $this->subscriptionUtils->getPackUniqueKey($subscription);
}
if (isset($context['groups']) && 'read_search' === $context['groups'][0]) {
$normalizedData['pack'] = implode(',', $packs);
}
}
return $normalizedData;
}
public function supportsNormalization($data, $format = null, array $context = []): bool
{
if (isset($context[self::ALREADY_CALLED])) {
return false;
}
return $data instanceof Organization;
}
}