<?php
namespace App\Serializer;
use App\Traits\SentryNotifyTrait;
use Doctrine\ORM\EntityManagerInterface;
use Evo\Infrastructure\MappingORM\Product;
use Evo\Infrastructure\MappingORM\Store;
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 StoreNormalizer implements ContextAwareNormalizerInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;
use SentryNotifyTrait;
private const ALREADY_CALLED = 'STORE_NORMALIZER_ALREADY_CALLED';
private EntityManagerInterface $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
/**
* @param Store $object
*
* @throws ExceptionInterface
*/
public function normalize($object, $format = null, array $context = [])
{
$context[self::ALREADY_CALLED] = true;
$normalizedData = $this->normalizer->normalize($object, $format, $context);
try {
if (($object instanceof Store) && is_array($normalizedData)) {
if (null !== $object->getName()) {
$product = $this->em->getRepository(Product::class)->findStoreAdditionForStoreName($object->getName());
if ($product) {
$normalizedData['price'] = $product->getPriceWithoutTax();
}
}
}
} catch (\Exception $e) {
$this->captureSentryException($e);
}
return $normalizedData;
}
public function supportsNormalization($data, $format = null, array $context = []): bool
{
if (isset($context[self::ALREADY_CALLED])) {
return false;
}
return $data instanceof Store;
}
}