<?php
declare(strict_types=1);
namespace VehicleIngestBundle\Controller;
use Pimcore\Controller\FrontendController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Annotation\Route;
use VehicleIngestBundle\Message\IngestAdMessage;
use VehicleIngestBundle\Persistence\VehicleLookup;
use VehicleIngestBundle\Registry\AdIdRegistry;
use VehicleIngestBundle\Service\ErrorResponseFactory;
class AdController extends FrontendController
{
public function __construct(
private AdIdRegistry $registry,
private MessageBusInterface $bus,
private ErrorResponseFactory $errors,
private VehicleLookup $lookup,
) {
}
/**
* @Route("/seller-api/sellers/{sellerId}/ads", name="seller_api_ad_create", methods={"POST"})
*/
public function createAction(Request $request, string $sellerId): Response
{
$raw = $request->getContent();
$data = json_decode($raw, true);
if (!is_array($data)) {
return $this->errors->keyed('body');
}
$requestId = $request->headers->get('X-Mobile-Insertion-Request-Id');
$adId = $this->registry->mint($requestId);
$this->bus->dispatch(new IngestAdMessage('upsert', $adId, $data, $sellerId, $requestId));
return new Response('', Response::HTTP_CREATED, [
'Location' => sprintf('/seller-api/sellers/%s/ads/%s', $sellerId, $adId),
]);
}
/**
* @Route("/seller-api/sellers/{sellerId}/ads/{adId}", name="seller_api_ad_update", methods={"PUT"}, requirements={"adId"="\d+"})
*/
public function updateAction(Request $request, string $sellerId, string $adId): Response
{
if (!$this->registry->exists($adId) && $this->lookup->byAdId($adId) === null) {
return new Response('', Response::HTTP_NOT_FOUND);
}
$data = json_decode($request->getContent(), true);
if (!is_array($data)) {
return $this->errors->keyed('body');
}
$this->bus->dispatch(new IngestAdMessage('upsert', $adId, $data, $sellerId, null));
return new Response('', Response::HTTP_OK);
}
/**
* @Route("/seller-api/sellers/{sellerId}/ads/{adId}", name="seller_api_ad_delete", methods={"DELETE"}, requirements={"adId"="\d+"})
*/
public function deleteAction(string $sellerId, string $adId): Response
{
$this->bus->dispatch(new IngestAdMessage('delete', $adId, null, $sellerId, null));
return new Response('', Response::HTTP_NO_CONTENT);
}
/**
* @Route("/seller-api/sellers/{sellerId}/ads/{adId}", name="seller_api_ad_get", methods={"GET"}, requirements={"adId"="\d+"})
*/
public function getAction(string $adId): Response
{
$exists = $this->registry->exists($adId) || $this->lookup->byAdId($adId) !== null;
return new Response('', $exists ? Response::HTTP_OK : Response::HTTP_NOT_FOUND);
}
}