Overview

Namespaces

  • ApiBundle
    • DataFixtures
      • Faker
        • Provider
    • DependencyInjection
    • Doctrine
      • DBAL
        • Type
      • ORM
        • Filter
          • User
    • Entity
    • EventListener
      • Doctrine
    • Manager
    • Utils
  • FrontBundle
    • Bundle
      • UserBundle
    • Client
      • Exception
    • Controller
    • DependencyInjection
    • Form
      • DataTransformer
      • Type
    • Menu
    • Security
      • Http
        • Authentication
    • Services
      • Http
    • Twig
    • Utils

Classes

  • ApiBundle\ApiBundle
  • ApiBundle\DataFixtures\Faker\Provider\DateTimeProvider
  • ApiBundle\DataFixtures\Faker\Provider\JobProvider
  • ApiBundle\DataFixtures\Faker\Provider\MandateProvider
  • ApiBundle\DataFixtures\Faker\Provider\StudentConventionProvider
  • ApiBundle\DataFixtures\Faker\Provider\UserProvider
  • ApiBundle\DependencyInjection\ApiExtension
  • ApiBundle\Doctrine\DBAL\Type\UTCDateTimeType
  • ApiBundle\Doctrine\ORM\Filter\AbstractResourceSearchFilter
  • ApiBundle\Doctrine\ORM\Filter\User\UserMandateFilter
  • ApiBundle\Doctrine\ORM\Filter\User\UserTypeFilter
  • ApiBundle\Entity\Address
  • ApiBundle\Entity\Job
  • ApiBundle\Entity\Mandate
  • ApiBundle\Entity\StudentConvention
  • ApiBundle\Entity\User
  • ApiBundle\EventListener\Doctrine\JobListener
  • ApiBundle\EventListener\Doctrine\MandateListener
  • ApiBundle\Manager\JobManager
  • ApiBundle\Manager\MandateManager
  • ApiBundle\Manager\UserManager
  • ApiBundle\Utils\UserRoles
  • FrontBundle\Bundle\UserBundle\FrontUserBundle
  • FrontBundle\Client\ApiClient
  • FrontBundle\Controller\BaseController
  • FrontBundle\Controller\DashboardController
  • FrontBundle\Controller\JobController
  • FrontBundle\Controller\MandateController
  • FrontBundle\Controller\UserController
  • FrontBundle\DependencyInjection\FrontExtension
  • FrontBundle\Form\DataTransformer\MandateDateTransformer
  • FrontBundle\Form\DataTransformer\StudentConventionTransformer
  • FrontBundle\Form\Type\JobFilteringType
  • FrontBundle\Form\Type\JobType
  • FrontBundle\Form\Type\MandateType
  • FrontBundle\Form\Type\StudentConventionType
  • FrontBundle\Form\Type\UserFilteringType
  • FrontBundle\Form\Type\UserType
  • FrontBundle\FrontBundle
  • FrontBundle\Menu\MenuBuilder
  • FrontBundle\Security\Http\Authentication\AuthenticationSuccessHandler
  • FrontBundle\Services\Http\RequestBuilder
  • FrontBundle\Services\Http\UrlBuilder
  • FrontBundle\Twig\FrontExtension
  • FrontBundle\Utils\IriHelper
  • FrontBundle\Utils\RoleHierarchyHelper

Interfaces

  • ApiBundle\Manager\NonPersistentEntityManagerInterface
  • FrontBundle\Client\ClientInterface
  • FrontBundle\Client\Exception\ClientException
  • FrontBundle\Controller\ApiControllerInterface
  • Overview
  • Namespace
  • Class
  1:   2:   3:   4:   5:   6:   7:   8:   9:  10:  11:  12:  13:  14:  15:  16:  17:  18:  19:  20:  21:  22:  23:  24:  25:  26:  27:  28:  29:  30:  31:  32:  33:  34:  35:  36:  37:  38:  39:  40:  41:  42:  43:  44:  45:  46:  47:  48:  49:  50:  51:  52:  53:  54:  55:  56:  57:  58:  59:  60:  61:  62:  63:  64:  65:  66:  67:  68:  69:  70:  71:  72:  73:  74:  75:  76:  77:  78:  79:  80:  81:  82:  83:  84:  85:  86:  87:  88:  89:  90:  91:  92:  93:  94:  95:  96:  97:  98:  99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: 145: 146: 147: 148: 149: 150: 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: 162: 163: 164: 165: 166: 167: 168: 169: 170: 171: 172: 173: 174: 175: 176: 177: 178: 179: 180: 181: 182: 183: 184: 185: 186: 187: 188: 189: 190: 191: 192: 193: 194: 195: 196: 197: 198: 199: 200: 201: 202: 203: 204: 205: 206: 207: 208: 209: 210: 211: 212: 213: 214: 215: 216: 
<?php

/*
 * This file is part of the Incipio package.
 *
 * (c) Théo FIDRY <theo.fidry@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace FrontBundle\Controller;

use FrontBundle\Client\ClientInterface;
use FrontBundle\Utils\IriHelper;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\TransferException;
use Psr\Http\Message\RequestInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller as SymfonyController;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Serializer\Encoder\DecoderInterface;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\SerializerInterface;

/**
 * @author Théo FIDRY <theo.fidry@gmail.com>
 */
class BaseController extends SymfonyController implements ApiControllerInterface
{
    /**
     * @var ClientInterface
     */
    protected $client;

    /**
     * @var SerializerInterface|NormalizerInterface|DecoderInterface
     */
    protected $serializer;

    public function setContainer(ContainerInterface $container = null)
    {
        parent::setContainer($container);

        $this->client = $this->get('api.client');
        $this->serializer = $this->get('serializer');
    }

    /**
     * {@inheritdoc}
     */
    public function generateUrl($route, $parameters = [], $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH)
    {
        if (array_key_exists('id', $parameters)) {
            $parameters['id'] = IriHelper::extractId($parameters['id']);
        }

        return parent::generateUrl($route, $parameters, $referenceType);
    }

    /**
     * {@inheritdoc}
     */
    public function decode($data, array $context = [])
    {
        return $this->serializer->decode($data, JsonEncoder::FORMAT, $context);
    }

    /**
     * {@inheritdoc}
     */
    public function createRequest($method, $url = null, $token = null, $options = [], $wholeCollection = false)
    {
        // If token is a request, get the token value from the header
        if ($token instanceof RequestInterface) {
            if (!isset($options['headers'])) {
                $options['headers'] = [];
            }
            $options['headers']['authorization'] = $token->getHeader('authorization');
            $token = null;
        } elseif ($token instanceof Request) {
            $token = $token->getSession()->get('api_token');
        }

        return $this->client->createRequest($method, $url, $token, $options);
    }

    /**
     * {@inheritdoc}
     */
    public function requestAndDecode($method, $url = null, $token = null, $options = [], $wholeCollection = false)
    {
        return $this->sendAndDecode($this->createRequest($method, $url, $token, $options), $wholeCollection);
    }

    /**
     * {@inheritdoc}
     */
    public function sendAndDecode(RequestInterface $request, $wholeCollection = false)
    {
        $decodedResponse = $this->decode($this->client->send($request)->getBody());

        if (false === $wholeCollection) {
            return $decodedResponse;
        }

        return $this->getEntitiesFromCollection(
            $decodedResponse,
            $request
        );
    }

    /**
     * {@inheritdoc}
     */
    public function handleGuzzleException(TransferException $exception)
    {
        $message = null;

        switch (true) {
            case $exception instanceof ConnectException:
                // Get exception message
                break;

            case $exception instanceof RequestException:
                $response = $exception->getResponse();
                switch ($response->getHeader('Content-Type')) {

                    case 'application/ld+json':
                        $body = $this->decode($response->getBody());
                        $type = $body['@type'];
                        switch ($type) {
                            case 'Error':
                                $message = sprintf(
                                    '%s: %s',
                                    $body['hydra:title'],
                                    $body['hydra:description']
                                );
                                break;

                            case 'ConstraintViolationList':
                                foreach ($body['violations'] as $violation) {
                                    $this->addFlash(
                                        'error',
                                        sprintf('%s: %s', $violation['propertyPath'], $violation['message'])
                                    );
                                }

                                return;
                        }
                        break;

                    case 'application/json':
                        $message = $this->decode($response->getBody());
                        break;
                }
                break;
        }

        // Other
        if (null === $message) {
            $message = $exception->getMessage();
            $message = (true === empty($message))
                ? 'Une erreur est survenue.'
                : $message
            ;
        }

        $this->addFlash('error', $message);
    }

    /**
     * {@inheritdoc}
     *
     * @deprecated Should not have to use Doctrine.
     *
     * @throws \LogicException If used.
     */
    public function getDoctrine()
    {
        throw new \LogicException('The DoctrineBundle should not be used in the Front application.');
    }

    /**
     * Helper to retrieve all resources from a paginated collection. If the decoded response is not a collection,
     * will return the decoded response.
     *
     * @param array               $decodedResponse
     * @param Request|string|null $token
     *
     * @return array Decoded response or all entities of the paginated collection.
     */
    private function getEntitiesFromCollection(array $decodedResponse, $token = null)
    {
        if ('hydra:PagedCollection' !== $decodedResponse['@type']) {
            return $decodedResponse;
        }

        $resources = [$decodedResponse['hydra:member']];
        while (isset($decodedResponse['hydra:nextPage'])) {
            $decodedResponse = $this->requestAndDecode(
                'GET',
                $decodedResponse['hydra:nextPage'],
                $token
            );

            $resources[] = $decodedResponse['hydra:member'];
        }

        return call_user_func_array('array_merge', $resources);
    }
}
API documentation generated by ApiGen