69 lines
2.0 KiB
PHP
69 lines
2.0 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\State;
|
|
|
|
use ApiPlatform\Metadata\Operation;
|
|
use ApiPlatform\State\ProcessorInterface;
|
|
use App\Entity\Bovine;
|
|
use Malio\EdnotifBundle\Bovin\Api\BovinApiInterface;
|
|
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
|
use Throwable;
|
|
|
|
final class BovineProcessor implements ProcessorInterface
|
|
{
|
|
public function __construct(
|
|
private readonly BovinApiInterface $bovinApi,
|
|
#[Autowire(service: 'api_platform.doctrine.orm.state.persist_processor')]
|
|
private readonly ProcessorInterface $persistProcessor,
|
|
) {}
|
|
|
|
public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed
|
|
{
|
|
if ($data instanceof Bovine && '' !== $data->getNationalNumber()) {
|
|
$this->enrichFromEdnotif($data);
|
|
}
|
|
|
|
return $this->persistProcessor->process($data, $operation, $uriVariables, $context);
|
|
}
|
|
|
|
private function enrichFromEdnotif(Bovine $bovine): void
|
|
{
|
|
try {
|
|
$animalFile = $this->bovinApi->getAnimalFile(
|
|
nationalNumber: $bovine->getNationalNumber(),
|
|
countryCode: 'FR',
|
|
);
|
|
|
|
$identification = $animalFile->identification;
|
|
if (null === $identification) {
|
|
return;
|
|
}
|
|
|
|
$bovine->setWorkNumber($identification->workNumber);
|
|
$bovine->setBirthDate($identification->birthDate?->date);
|
|
$bovine->setBreedCode($this->normalizeBreedCode($identification->breedType));
|
|
} catch (Throwable) {
|
|
// External service unavailable — persist bovine without enrichment.
|
|
}
|
|
}
|
|
|
|
private function normalizeBreedCode(mixed $breedType): ?string
|
|
{
|
|
if (null === $breedType) {
|
|
return null;
|
|
}
|
|
|
|
if (is_numeric($breedType)) {
|
|
return (string) $breedType;
|
|
}
|
|
|
|
if (is_string($breedType) && preg_match('/\d+/', $breedType, $matches)) {
|
|
return $matches[0];
|
|
}
|
|
|
|
return null;
|
|
}
|
|
}
|