<?php
namespace App\EventSubscriber;
use App\Utils\ApiUtils;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Contracts\HttpClient\HttpClientInterface;
final class TaxonSubscriber implements EventSubscriberInterface
{
public function __construct(private HttpClientInterface $client)
{
}
public static function getSubscribedEvents()
{
return [
FormEvents::POST_SUBMIT=> 'pushBrandToCentral',
];
}
public function pushBrandToCentral(FormEvent $event): void
{
$taxon = $event->getData();
$method = 'POST';
if ($taxon->getId()) {
$method = 'PUT';
}
$body = [
"code" => $taxon->getCode(),
"enabled" => $taxon->isEnabled(),
"parent" => $taxon->getParent()->getCode() ? '/api/taxons/' . $taxon->getParent()->getCode() : null,
"position" => $taxon->getPosition() ?? 0,
"translations" => [
"en_US" => [
"name" => $taxon->getTranslation('en_US')->getName(),
"slug" => $taxon->getTranslation('en_US')->getSlug(),
"description" => $taxon->getTranslation('en_US')->getDescription() ?? '',
"locale" => "en_US"
],
],
];
$response = $this->client->request(
$method,
ApiUtils::getSudek() . '/api/taxons' . ($method === 'PUT' ? '/' . $taxon->getCode() : ''),
[
'headers' => ['accept' => 'application/ld+json', 'Content-type' => 'application/ld+json', 'Authorization' => sprintf('Bearer %s', ApiUtils::getToken($this->client))],
'body' => json_encode($body)
]
);
}
}