Skip to content

Instantly share code, notes, and snippets.

@kix
Last active August 12, 2024 08:14
Show Gist options
  • Save kix/efa9f095b8c9765f74b8 to your computer and use it in GitHub Desktop.
Save kix/efa9f095b8c9765f74b8 to your computer and use it in GitHub Desktop.
<?php
abstract class AbstractRestController
{
/**
* @var \Symfony\Component\Form\FormFactoryInterface
*/
protected $formFactory;
/**
* @var string
*/
protected $formType;
/**
* @var string
*/
protected $entityClass;
/**
* @var SecurityContextInterface
*/
protected $securityContext;
/**
* @var RegistryInterface
*/
protected $doctrine;
/**
* @var LoggerInterface
*/
protected $logger;
/**
* @var bool
*/
protected $isSecure;
/**
* @param FormFactoryInterface $formFactory
* @param RegistryInterface $doctrine
* @param SecurityContextInterface $securityContext
* @param LoggerInterface $logger
*/
public function __construct(
FormFactoryInterface $formFactory,
RegistryInterface $doctrine,
SecurityContextInterface $securityContext,
LoggerInterface $logger,
$secure = false
)
{
$this->formFactory = $formFactory;
$this->doctrine = $doctrine;
$this->securityContext = $securityContext;
$this->logger = $logger;
}
/**
* @param string $formType
*/
public function setFormType($formType)
{
$this->formType = $formType;
}
/**
* @param string $entityClass
*/
public function setEntityClass($entityClass)
{
$this->entityClass = $entityClass;
}
/**
* @param null $data
* @param array $options
*
* @return \Symfony\Component\Form\FormInterface
*/
public function createForm($data = null, $options = array())
{
return $this->formFactory->create(new $this->formType(), $data, $options);
}
/**
* @return RegistryInterface
*/
public function getDoctrine()
{
return $this->doctrine;
}
/**
* @return ObjectRepository
*/
public function getRepository()
{
return $this->doctrine->getRepository($this->entityClass);
}
/**
* @ApiDoc(
* resource=true,
* description="List objects",
* headers={
* {"name"="Range", "dataType"="integer", "required"=false}
* }
* )
*
* @param Request $request
*
* @return array
*
* @View(serializerGroups={"list"}, serializerEnableMaxDepthChecks=true)
*/
public function cgetAction(Request $request)
{
$this->logger->log('DEBUG', 'CGET ' . $this->entityClass);
$offset = null;
$limit = null;
if ($range = $request->headers->get('Range')) {
list($offset, $limit) = explode(',', $range);
}
return $this->getRepository()->findBy(
[],
null,
$limit,
$offset
);
}
/**
* @ApiDoc(
* resource=true,
* description="Retrieve an object by its ID",
* parameters={
* {"name"="id", "dataType"="integer", "required"=true, "description"="Object ID"}
* }
* )
*
* @param int $id
*
* @return object
*
* @View(serializerGroups={"show"}, serializerEnableMaxDepthChecks=true)
*/
public function getAction($id)
{
$this->logger->log('DEBUG', 'GET ' . $this->entityClass);
$object = $this->getRepository()->find($id);
if (!$object) {
throw new NotFoundHttpException(sprintf('%s#%s not found', $this->entityClass, $id));
}
return $object;
}
/**
* @ApiDoc(
* input="\MyNamespace\APIBundle\Form\AbstractApiType",
* description="Create an object"
* )
*
* @param Request $request
*
* @return \Symfony\Component\Form\Form|\Symfony\Component\Form\FormInterface
*
* @View()
*/
public function postAction(Request $request)
{
$this->logger->log('DEBUG', 'POST ' . $this->entityClass);
$object = new $this->entityClass();
$form = $this->createForm($object);
$form->submit($request);
if ($form->isValid()) {
$this->doctrine->getManager()->persist($object);
$this->doctrine->getManager()->flush($object);
return $object;
}
return $form;
}
/**
* @ApiDoc(
* input="\MyNamespace\APIBundle\Form\AbstractApiType",
* parameters={
* {"name"="id", "dataType"="integer", "required"=true, "description"="Object ID"}
* },
* description="Update given object"
* )
*
* @param Request $request
* @param int $id
*
* @return \Symfony\Component\Form\FormInterface
*
* @View()
*/
public function putAction(Request $request, $id)
{
$this->logger->log('DEBUG', 'PUT ' . $this->entityClass);
$object = $this->getRepository()->find($id);
if (!$object) {
throw new NotFoundHttpException(sprintf('%s#%s not found', $this->entityClass, $id));
}
$form = $this->createForm($object);
$form->submit($request);
if ($form->isValid()) {
$this->doctrine->getManager()->persist($object);
$this->doctrine->getManager()->flush($object);
return $object;
}
return $form;
}
/**
* @ApiDoc(
* parameters={
* {"name"="id", "dataType"="integer", "required"=true, "description"="Object ID"}
* },
* description="Delete given object ID"
* )
*
* @param int $id
*
* @return array
*
* @View()
*/
public function deleteAction($id)
{
$this->logger->log('DEBUG', 'DELETE ' . $this->entityClass);
$object = $this->getRepository()->find($id);
if (!$object) {
throw new NotFoundHttpException(sprintf('%s#%s not found', $this->entityClass, $id));
}
$this->doctrine->getManager()->remove($object);
$this->doctrine->getManager()->flush($object);
return ['success' => true];
}
}
<?php
class CarController extends AbstractRestController implements ClassResourceInterface
{
/**
* Car lookup.
*
* @ApiDoc(
* description="Car lookup",
* section="Cars",
* parameters={
* {"name"="term", "dataType"="string", "required"=true, "description"="Search term"}
* }
* )
*
* @param Request $request
*
* @View(serializerGroups={"list"})
*
* @return mixed
*/
public function searchAction(Request $request)
{
$term = $request->query->get('term');
/** @var \Doctrine\ORM\EntityRepository $repo */
$repo = $this->getRepository();
$qb = $repo->createQueryBuilder('c');
$orX = $qb->expr()->orX(
$qb->expr()->like('c.vendor', ':term'),
$qb->expr()->like('c.title', ':term')
);
$qb->where($orX);
return $qb->getQuery()->execute([
'term' => "%$term%"
]);
}
/**
* @param Request $request
*
* @ApiDoc(
* description="Car creation",
* section="Cars",
* input="\MyNamespace\APIBundle\Form\CarType",
* output="\MyNamespace\MainBundle\Entity\Car"
* )
* {@inheritdoc}
* @View()
*
* @return \MyNamespace\APIBundle\Form\CarType
*/
public function postAction(Request $request)
{
return parent::postAction($request);
}
/**
* @param Request $request
*
* @ApiDoc(
* section="Cars",
* output="\MyNamespace\MainBundle\Entity\Car[]",
* description="List all cars"
* )
* {@inheritdoc}
* @View()
*
* @return array|\MyNamespace\MainBundle\Entity\InsuranceProduct[]
*/
public function cgetAction(Request $request)
{
return parent::cgetAction($request);
}
/**
* @param int $id
*
* @ApiDoc(
* section="Cars",
* output="\MyNamespace\MainBundle\Entity\Car",
* description="Get one car"
* )
* @View()
*
* @return \MyNamespace\MainBundle\Entity\Car[]
*/
public function getAction($id)
{
return parent::getAction($id);
}
/**
* @param Request $request
* @param int $id
*
* @ApiDoc(
* section="Cars",
* input="\MyNamespace\APIBundle\Form\CarType",
* output="\MyNamespace\MainBundle\Entity\Car",
* description="Update a car"
* )
* @View()
*
* @return \Symfony\Component\Form\FormInterface
*/
public function putAction(Request $request, $id)
{
return parent::putAction($request, $id);
}
/**
* Returns {success: true|false}
*
* @param int $id
*
* @ApiDoc(
* section="Cars",
* description="Delete a car",
* output="success: true|false"
* )
* {@inheritdoc}
* @View()
*
* @return array
*/
public function deleteAction($id)
{
return parent::deleteAction($id);
}
}
services:
my_api.abstract_controller:
class: AbstractRestController
abstract: true
arguments:
- @form.factory
- @doctrine
- @security.context
- @logger
my_api.cars.controller:
class: CarController
parent: artsofte_skecrm_api.abstract_controller
calls:
- [ setEntityClass, [ %my_api.car.class% ] ]
- [ setFormType, [ %my_api.cars.form.class% ] ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment