Skip to content

Commit

Permalink
#10: Ajout de l'Api Rest via le bundle fosrest
Browse files Browse the repository at this point in the history
  • Loading branch information
obounjerte committed Jul 26, 2021
1 parent 5f616e9 commit ca70067
Show file tree
Hide file tree
Showing 7 changed files with 439 additions and 3 deletions.
228 changes: 228 additions & 0 deletions Controller/SQLIRestApiController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
<?php

namespace SQLI\EzToolboxBundle\Controller;

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use EzSystems\EzPlatformAdminUi\Notification\FlashBagNotificationHandler;
use EzSystems\EzPlatformRest\Input\Handler\Json;
use FOS\RestBundle\Controller\AbstractFOSRestController;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\View\ViewHandler;
use FOS\RestBundle\View\View;
use SQLI\EzToolboxBundle\Form\EntityManager\EditElementType;
use SQLI\EzToolboxBundle\Services\EntityHelper;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use ReflectionException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\Serializer\SerializerInterface;

use function Sodium\add;

class SQLIRestApiController extends AbstractFOSRestController
{
/** @var FlashBagNotificationHandler */
protected $flashBagNotificationHandler;
/** @var EntityManagerInterface */
protected $entityManager;
/** @var EntityHelper */
protected $entityHelper;
/** @var TranslatorInterface */
protected $translator;

/**
* RestApiController constructor.
* @param FlashBagNotificationHandler $flashBagNotificationHandler
* @param EntityManagerInterface $entityManager
* @param EntityHelper $entityHelper
* @param TranslatorInterface $translator
*/
public function __construct(
FlashBagNotificationHandler $flashBagNotificationHandler,
EntityManagerInterface $entityManager,
EntityHelper $entityHelper,
TranslatorInterface $translator
) {
$this->flashBagNotificationHandler = $flashBagNotificationHandler;
$this->entityManager = $entityManager;
$this->entityHelper = $entityHelper;
$this->translator = $translator;
}

/**
* @param string $fqcn
* @param EntityHelper $entityHelper
* @return Response
* @throws ReflectionException
* @Rest\Route("/{fqcn}/", methods={"GET"})
*/
public function getJsonEntity(string $fqcn, EntityHelper $entityHelper): Response
{
$entity = $entityHelper->getEntity($fqcn, true);
$response = new JsonResponse($entity);
$response->setEncodingOptions($response->getEncodingOptions() | JSON_PRETTY_PRINT);
return $response;
}

/**
* @param string $fqcn
* @param string $compound_id
* @param EntityHelper $entityHelper
* @param SerializerInterface $serializer
* @return Response
* @Rest\Route("/{fqcn}/{compound_id}", methods={"GET"})
*/
public function getJsonElement(
string $fqcn,
string $compound_id,
EntityHelper $entityHelper,
SerializerInterface $serializer
): Response {
$element = $this->findEntityById($fqcn, $compound_id, $entityHelper);

$elementArray = $serializer->normalize($element);
$response = new JsonResponse($elementArray);
$response->setEncodingOptions($response->getEncodingOptions() | JSON_PRETTY_PRINT);
return $response;
}

/**
* @param Request $request
* @param string $fqcn
* @param EntityHelper $entityHelper
* @param SerializerInterface $serializer
* @return FormInterface|JsonResponse
* @throws ReflectionException
* @Rest\Route("/{fqcn}", methods={"POST"})
*/
public function postJsonElement(
Request $request,
string $fqcn,
EntityHelper $entityHelper,
SerializerInterface $serializer
) {
$entity = $entityHelper->getEntity($fqcn, false);
$element = new $fqcn();
$form = $this->createForm(EditElementType::class, $element, ['entity' => $entity, 'csrf_protection' => false]);

$form->submit($request->request->all());
if (false === $form->isValid()) {
return $form;
}

$this->entityManager->persist($form->getData());
$this->entityManager->flush();

return new JsonResponse(
[
["message" => "Resource " . $fqcn . " CREATED"],
],
JsonResponse::HTTP_CREATED
);
}

/**
* @param string $fqcn
* @param string $compound_id
* @param EntityHelper $entityHelper
* @return JsonResponse
* @Rest\Route("/{fqcn}/{compound_id}", methods={"DELETE"})
*/
public function deleteJsonElement(string $fqcn, string $compound_id, EntityHelper $entityHelper): JsonResponse
{
$element = $this->findEntityById($fqcn, $compound_id, $entityHelper);

$this->entityManager->remove($element);
$this->entityManager->flush();
return new JsonResponse(
["message" => "Resource " . $fqcn . "DELETED"],
JsonResponse::HTTP_OK
);
}

/**
* @param string $fqcn
* @param string $compound_id
* @param EntityHelper $entityHelper
* @param Request $request
* @return object|FormInterface
* @Rest\Route("/{fqcn}/{compound_id}", methods={"PUT"})
* @throws ReflectionException
*/
public function updateJsonElement(string $fqcn, string $compound_id, EntityHelper $entityHelper, Request $request)
{
$entity = $entityHelper->getEntity($fqcn, false);
$element = $this->findEntityById($fqcn, $compound_id, $entityHelper);

$form = $this->createForm(
EditElementType::class,
$element,
['entity' => $entity, 'csrf_protection' => false]
);

$data = $request->request->all();
$compound_id = json_decode($compound_id, true);
$data = array_merge($compound_id, $data);
$form->submit($data);

if (false === $form->isValid()) {
return $form;
}

$this->entityManager->flush();
return $element;
}

/**
* @param string $fqcn
* @param string $compound_id
* @param EntityHelper $entityHelper
* @param Request $request
* @Rest\Route("/{fqcn}/{compound_id}", methods={"PATCH"})
* @return object|FormInterface
* @throws ReflectionException
*/
public function patchJsonElement(string $fqcn, string $compound_id, EntityHelper $entityHelper, Request $request)
{
$entity = $entityHelper->getEntity($fqcn, false);
$element = $this->findEntityById($fqcn, $compound_id, $entityHelper);

$form = $this->createForm(
EditElementType::class,
$element,
['entity' => $entity, 'csrf_protection' => false]
);

$form->submit($request->request->all(), false);

if (false === $form->isValid()) {
return $form;
}

$this->entityManager->flush();
return $element;

}

/**
* @param string $fqcn
* @param string $compound_id
* @param EntityHelper $entityHelper
* @return object
*/
private function findEntityById(string $fqcn, string $compound_id, EntityHelper $entityHelper): object
{
$compound_id = json_decode($compound_id, true);
if (!empty($compound_id)) {
$element = $entityHelper->findOneBy($fqcn, $compound_id);
if (empty($element)) {
throw new NotFoundHttpException();
}
return $element;
}
}
}
23 changes: 22 additions & 1 deletion DependencyInjection/SQLIEzToolboxExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,17 @@

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\Yaml\Yaml;

/**
* This is the class that loads and manages your bundle configuration.
*
* @link http://symfony.com/doc/current/cookbook/bundles/extension.html
*/
class SQLIEzToolboxExtension extends Extension
class SQLIEzToolboxExtension extends Extension implements PrependExtensionInterface
{
/**
* {@inheritdoc}
Expand Down Expand Up @@ -54,4 +56,23 @@ public function load(array $configs, ContainerBuilder $container)
);
}
}

/**
* {@inheritdoc}
*/
public function prepend(ContainerBuilder $container): void
{
$this->prependFieldType($container);
}

/**
* @param ContainerBuilder $container
*/
private function prependFieldType(ContainerBuilder $container): void
{
$config = Yaml::parseFile(
__DIR__ . '/../Resources/config/fos_rest.yaml'
);
$container->prependExtensionConfig('fos_rest', $config);
}
}
3 changes: 3 additions & 0 deletions Resources/config/api_routes.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
api_rest:
resource: SQLI\EzToolboxBundle\Controller\RestApiController
type: annotation
17 changes: 17 additions & 0 deletions Resources/config/fos_rest.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
serializer:
serialize_null: true
body_listener:
enabled: true
throw_exception_on_unsupported_content_type: true
decoders:
json: fos_rest.decoder.json
format_listener:
rules:
- { path: '^/api', priorities: ['json'], fallback_format: json, prefer_extension: false }
param_fetcher_listener: force
view:
view_response_listener: 'force'
formats:
json: true
allowed_methods_listener: true

5 changes: 5 additions & 0 deletions Resources/config/routing.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ sqli_eztoolbox_entitymanager_entity_homepage_reset_filter:
path: /sqli-admin/entity/{fqcn}/reset
controller: SQLI\EzToolboxBundle\Controller\EntitiesController::resetFilter

# FosRestBundle used for api rest
api:
resource: api_routes.yaml
prefix: /api/

# Keep this route at end
sqli_eztoolbox_entitymanager_entity_homepage:
path: /sqli-admin/entity/{fqcn}/{sort_column}/{sort_order}
Expand Down
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@
"require": {
"ibexa/oss": "^3.3",
"netgen/tagsbundle": "^4.0",
"ext-json": "*"
"ext-json": "*",
"friendsofsymfony/rest-bundle": "^3.0"
},
"suggest": {
"tanoconsulting/ezmigrationbundle2": "main"
Expand Down
Loading

0 comments on commit ca70067

Please sign in to comment.