<?php
namespace App\Serializer\Normalizer;
use App\Entity\CardiovascularScore;
use App\Entity\ScoreRisk;
use App\Entity\Users;
use App\Helper\ConvertUnitMeasures;
use App\Helper\HealthHelper;
use App\Traits\ProfilesTrait;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use App\Entity\CardiometabolicProfiles;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Contracts\Translation\TranslatorInterface;
class CardiometabolicProfileExtendedNormalizer implements NormalizerInterface, CacheableSupportsMethodInterface
{
use ProfilesTrait;
private const ALREADY_CALLED = 'PROFILE_EXTENDED_NORMALIZER_ALREADY_CALLED';
private ?Users $user;
private ?float $unitMeasure;
public function __construct(
#[Autowire(service: ObjectNormalizer::class)]
private NormalizerInterface $normalizer,
private EntityManagerInterface $em,
private TranslatorInterface $translator,
private Security $security
)
{
$this->user = $security->getUser();
if ($this->user instanceof Users) {
$this->unitMeasure = $this->user->getUnitMeasure();
} else {
$this->unitMeasure = null;
}
}
public function normalize($object, string $format = null, array $context = []): array
{
$context[self::ALREADY_CALLED] = true;
$normalized = $this->normalizer->normalize($object, $format, $context);
if (null === $this->unitMeasure) {
$this->unitMeasure = $object->getUser()->getUnitMeasure();
}
if (in_array('profiles:extended', $context['groups'])) {
if ($object->getCvdScoreId() > 0) {
$cvdScore = $this->em->getRepository(CardiovascularScore::class)->find($object->getCvdScoreId());
if ($cvdScore) {
$scoreRisk = $this->em->getRepository(ScoreRisk::class)->find($cvdScore->getScoreRiskId());
}
}
$scoreRisk = HealthHelper::getScoreRisk($object, $scoreRisk ?? null, $this->em);
$normalized['score_risk'] = $this->parseScoreRisk($scoreRisk, $this->user->getLang());
$normalized['cvd_score'] = HealthHelper::parseScoreToArray(HealthHelper::getScore($object, $cvdScore ?? null, $scoreRisk));
}
if ($this->unitMeasure == 2) {
$normalized['weight'] = (float)ConvertUnitMeasures::kgToLbs($normalized['weight']);
$normalized['height'] = (float)ConvertUnitMeasures::cmToInches($normalized['height']);
}
return $normalized;
}
public function supportsNormalization($data, string $format = null, array $context = []): bool
{
// avoid recursion: only call once per object
if (isset($context[self::ALREADY_CALLED])) {
return false;
}
return $data instanceof CardiometabolicProfiles;
}
public function hasCacheableSupportsMethod(): bool
{
return true;
}
}