PHP code example of wizzaq / rest-bundle

1. Go to this page and download the library: Download wizzaq/rest-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

wizzaq / rest-bundle example snippets




namespace App\Controller;

use App\Form\Filter\MyEntityFilterType;
use App\Form\Dto\Filter\MyEntityFilter;
use App\Repository\MyEntityRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Wizzaq\RestBundle\Attribute\ProcessForm;

class MyEntityController extends AbstractController
{
   #[Route('/my-entity', methods: 'GET')]
   public function list(
       #[ProcessForm(MyEntityFilterType::class, mapEntity: false, throwOnNotValid: false)] ?MyEntityFilter $filter = null,
       MyEntityRepository $repository
   ): Response {
       return $this->json(['list' => $repository->list($filter ?? new MyEntityFilter())]);
   }

   #[Route('/my-entity', methods: 'POST')]
   #[Route('/my-entity/{id}', methods: 'PUT')]
   public function edit(
       #[ProcessForm(MyEntityType::class)] MyEntity $entity,
       EntityManagerInterface $em
   ): Response {
       // $entity is processed by form and validated
       // Wizzaq\RestBundle\Exception\FormValidationException will be thrown if validation failed
       $em->persist($entity);
       $em->flush();

       return new JsonResponse(['id' => $entity->getId()]);
   }

}

> #[Route('/my-entity/{id}', methods: 'PUT')]
> public function edit(
>    #[ProcessForm(form: MyEntityType::class)] MyEntity $entity,
>    EntityManagerInterface $em
> ): Response {
>    // $entity is processed by form and validated
>    // Wizzaq\RestBundle\Exception\FormValidationException will be thrown if validation failed
>    $em->persist($entity);
>    $em->flush();
>
>    return new JsonResponse(['id' => $entity->getId()]);
> }
> 

> #[Route('/my-entity/{id}', methods: 'PUT')]
> public function edit(
>    #[ProcessForm(form: MyEntityType::class, mapEntity: true)] MyEntity $entity,
>    EntityManagerInterface $em
> ): Response {
>    // $entity is processed by form and validated
>    // Wizzaq\RestBundle\Exception\FormValidationException will be thrown if validation failed
>    $em->persist($entity);
>    $em->flush();
>
>    return new JsonResponse(['id' => $entity->getId()]);
> }
> 

> #[Route('/my-entity', methods: 'GET')]
> public function list(
>     #[ProcessForm(MyEntityFilterType::class, submit: true)] ?MyEntityFilter $filter = null,
>     MyEntityRepository $repository
> ): Response {
>     return $this->json(['list' => $repository->list($filter ?? new MyEntityFilter())]);
> }
> 

> \Wizzaq\RestBundle\Config\RestConfig::processedForm($request)
> 

> ...
> use Wizzaq\RestBundle\Config\RestConfig;
> ...
>
> #[Route('/my-entity/{id}', methods: ['GET', 'POST'])]
> public function edit(
>    #[ProcessForm(form: MyEntityType::class, throwOnNotValid: false)] ?MyEntity $entity = null,
>    Request $request,
>    RestConfig $restConfig,
>    EntityManagerInterface $em
> ): Response {
>    if (null === $entity) {
>        $this->addFlash(
>            'error',
>            'Entity not found!'
>        );
>
>        return new RedirectResponse('/my-entity');
>    }
>
>    $form = $restConfig->processedForm($request);
>
>    if ($form->isSubmitted() && $form->isValid()) {
>        // do some stuff here
>        $em->persist($entity);
>        $em->flush();
>
>        return new RedirectResponse('/my-entity');
>    }
>
>    return $this->render('my_entity/edit.html.twig', [
>        'form' => $form,
>    ]);
> }
>
> 

public function onRequest(RequestEvent $event): void
{
    $request = $event->getRequest();

    if ('' === $request->getContent()) {
        return;
    }

    if ('json' !== $request->getContentTypeFormat()) {
        return;
    }

    try {
        $request->request->replace($request->toArray());
    } catch (JsonException $e) {
        throw new BadRequestHttpException('Unable to parse request.', $e);
    }
}

    

    namespace App\Controller;

    use App\Form\Filter\MyEntityFilterType;
    use App\Form\Dto\Filter\MyEntityFilter;
    use App\Repository\MyEntityRepository;
    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    use Symfony\Bridge\Twig\Attribute\Template;
    use Symfony\Component\HttpFoundation\JsonResponse;
    use Symfony\Component\HttpFoundation\Response;
    use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
    use Symfony\Component\Routing\Attribute\Route;
    use Wizzaq\RestBundle\Attribute\ProcessForm;
    use Wizzaq\RestBundle\Attribute\Rest;
    use Wizzaq\RestBundle\Exception\FormValidationException;

    class MyEntityController extends AbstractController
    {
        #[Route('/my-entity', methods: 'GET')]
        #[Rest(responseSerializationGroups: 'default')]
        public function list(
            #[ProcessForm(form: MyEntityFilterType::class, throwOnNotValid: false)] ?MyEntityFilter $filter = null,
            MyEntityRepository $repository
        ): array {
            return ['list' => $repository->list($filter ?? new MyEntityFilter())];
        }

        #[Route('/my-entity/{id}', name: 'app.my_entity.get_or_update', methods: ['GET', 'POST'])]
        #[Route('/api/my-entity/{id}', name: 'api.my_entity.get_or_update', methods: ['GET', 'POST'])]
        #[Rest(routes: 'api.my_entity.get_or_update', responseSection: 'entity', responseSerializationGroups: ['with_related', 'default'])]
        #[Template('my_entity/edit.html.twig')]
        public function edit(
            #[ProcessForm(MyEntityType::class, throwOnNotValid: false)] MyEntity $entity,
            Request $request,
            RestConfig $restConfig,
            EntityManagerInterface $em
        ): array {
            $form = $restConfig->processedForm($request);

            if ($form->isSubmitted() && $form->isValid()) {
                // do some stuff here
                $em->persist($entity);
                $em->flush();

                return $restConfig->isRest($request) ? ['entity' => $entity] : new RedirectResponse('/my-entity');
            } elseif ($form->isSubmitted() && !$form->isValid() && $restConfig->isRest($request)) {
                throw new FormValidationException($form);
            }

            return [
                'form' => $form,
                'entity' => $entity,
            ]
        }
   }
   

namespace App\Protocol;

use Wizzaq\RestBundle\Config\RestConfig;
use Wizzaq\RestBundle\Protocol\NamedProtocolInterface;
use Wizzaq\RestBundle\Protocol\RestProtocol;

class MyProtocol extends RestProtocol implements NamedProtocolInterface
{
    public function __construct(RestConfig $restConfig, bool $debug = false, $serializer = null) 
    {
        parent::__construct($restConfig, $debug, $serializer);
    }
    
    public function getProtocolName(): string
    {
        return 'my_rest';
    }
    
    public function processResponse($response, Request $request): Response
    {
        return parent::processResponse(['success' => true, 'data' => $response], $request);
    }
}