<?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 BrandSubscriber implements EventSubscriberInterface
{
public function __construct(private HttpClientInterface $client)
{
}
public static function getSubscribedEvents()
{
return [
FormEvents::POST_SUBMIT=> 'pushBrandToCentral',
];
}
public function pushBrandToCentral(FormEvent $event): void
{
$brand = $event->getData();
$method = 'POST';
if ($brand->getId()) {
$method = 'PUT';
}
$body = [
"name" => $brand->getName(),
"code" => $brand->getCode(),
"plateDefault" => $brand->getPlateDefault(),
"platePerColor" => $brand->getPlatePerColor(),
"productionTime" => $brand->getProductionTime(),
"setupDefault" => $brand->getSetupDefault(),
"url" => $brand->getUrl(),
"freight" => $brand->getFreight()
];
if($method === 'PUT') {
$body["code"] = $brand->getCode();
}
$response = $this->client->request(
$method,
ApiUtils::getSudek() . '/api/brands'. ($method === 'PUT' ? '/' . $brand->getCode() : ''),
[
'headers' => ['accept' => 'application/ld+json', 'Content-Type' => 'application/ld+json', 'Authorization' => sprintf('Bearer %s', ApiUtils::getToken($this->client))],
'body' => json_encode($body)
]
);
}
}