0
votes

I am trying to use the class ApiProblemException inside a Symfony Controller. This should return an error response for an API. When I send wrong parameters in the AJAX request body, so that throw new ApiProblemException($apiProblem); is executed I get:

Attempted to load class "ApiProblemException" from namespace "AppBundle\Libraries\Core\Api". Did you forget a "use" statement for another namespace? 500 Internal Server Error - ClassNotFoundException

But I have the use statement use AppBundle\Libraries\Core\Api\ApiProblemException;.

The file locations:

  • ApiCityselectionController: Project\src\AppBundle\Controller\Api\User\ApiCityselectionController.php

  • ApiProblem: Project\src\AppBundle\Libraries\Core\Api\ApiProblem.php

  • ApiProblemExeption: Project\src\AppBundle\Libraries\Core\Api\ApiProblemExeption.php

My code:

ApiProblem:

namespace AppBundle\Libraries\Core\Api;

use Symfony\Component\HttpFoundation\Response;

/**
 * A wrapper for holding data to be used for a application/problem+json response
 */
class ApiProblem
{
    //Validation
    const TYPE_VALIDATION_ERROR = 'validation_error';

    //Wrong input
    const TYPE_INVALID_REQUEST_BODY_FORMAT = 'invalid_body_format';
    const TYPE_INVALID_REQUEST_BODY_DATATYPE = "invalid_body_datatype";

    //Not found
    const TYPE_USER_NOT_FOUND = "user_not_found";
    const TYPE_CITY_NOT_FOUND = "city_not_found";

    private static $titles = array(
        self::TYPE_VALIDATION_ERROR => 'Ein Validierungsfehler ist aufgetreten',
        self::TYPE_INVALID_REQUEST_BODY_FORMAT => 'Ungültiges JSON gesendet',
        self::TYPE_INVALID_REQUEST_BODY_DATATYPE => "Falschen Datentyp gesendet",
        self::TYPE_USER_NOT_FOUND => "Benutzer konnte nicht gefunden werden",
        self::TYPE_CITY_NOT_FOUND => "Gemeinde konnte nicht gefunden werden",
    );
    private $statusCode;
    private $type;
    private $title;
    private $extraData = array();

    public function __construct($statusCode, $type = null)
    {
        $this->statusCode = $statusCode;
        if ($type === null)
        {
            // no type? The default is about:blank and the title should
            // be the standard status code message
            $type = 'about:blank';
            $title = isset(Response::$statusTexts[$statusCode])
                ? Response::$statusTexts[$statusCode]
                : 'Unknown status code :(';
        }
        else
        {
            if (!isset(self::$titles[$type]))
            {
                throw new \InvalidArgumentException('No title for type '.$type);
            }
            $title = self::$titles[$type];
        }
        $this->type = $type;
        $this->title = $title;
    }

    public function toArray()
    {
        return array_merge(
            $this->extraData,
            array(
                'status' => $this->statusCode,
                'type' => $this->type,
                'title' => $this->title,
            )
        );
    }

    public function set($name, $value)
    {
        $this->extraData[$name] = $value;
    }

    public function getStatusCode()
    {
        return $this->statusCode;
    }

    public function getTitle()
    {
        return $this->title;
    }
}

ApiProblemExeption:

namespace AppBundle\Libraries\Core\Api;

use Symfony\Component\HttpKernel\Exception\HttpException;

class ApiProblemException extends HttpException
{
    private $apiProblem;

    public function __construct(ApiProblem $apiProblem, \Exception $previous = null, array $headers = array(), $code = 0)
    {
        $this->apiProblem = $apiProblem;
        $statusCode = $apiProblem->getStatusCode();
        $message = $apiProblem->getTitle();
        parent::__construct($statusCode, $message, $previous, $headers, $code);
    }
}

ApiCityselectionController:

namespace AppBundle\Controller\Api\User;

use AppBundle\Libraries\Core\Api\ApiProblem;
use AppBundle\Libraries\Core\Api\ApiProblemException;
use AppBundle\Libraries\Data\Users;
use AppBundle\Libraries\Core\EntitySerializer;
use AppBundle\Libraries\Core\Validator;
use FOS\RestBundle\Controller\FOSRestController;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\HttpException;

class ApiCityselectionController extends FOSRestController
{
    /**
     * @Route("/", name="api_user_cityselection")
     * @Method("POST")
     * @param Request $request
     * @return JsonResponse
     * Sets the city of a user
     */
    public function CityselectionAction(Request $request)
    {
        $validator = new Validator();

        $userId = json_decode($request->request->get('userId'));
        $cityId = json_decode($request->request->get('cityId'));

        $isUserIdValid = $validator->validateInt($userId);
        $isCityIdValid = $validator->validateInt($cityId);

        if($isUserIdValid && $isCityIdValid)
        {
            $user = $this->getDoctrine()
                ->getRepository('AppBundle:Users')
                ->findOneBy(array('id' => $userId));

            $city = $this->getDoctrine()
                ->getRepository('AppBundle:Cities')
                ->findOneBy(array('id' => $cityId));

            $isUserValid = $validator->validateEntity($user);

            //Check if user exists
            if (!$isUserValid)
            {
                $apiProblem = new ApiProblem(400, ApiProblem::TYPE_USER_NOT_FOUND);

                throw new ApiProblemException($apiProblem);
            }

            $isCityValid = $validator->validateEntity($city);

            if($isUserValid && $isCityValid)
            {
                $user->setFkCity($city);

                $em = $this->getDoctrine()->getManager();
                $em->persist($user);
                $em->flush();

                $serializer = new EntitySerializer($this->getDoctrine()->getManager());
                $responseData = $serializer->serializeUser($user);
            }
            else
            {
                $apiProblem = new ApiProblem(400, ApiProblem::TYPE_CITY_NOT_FOUND);

                throw new ApiProblemException($apiProblem);
            }
        }
        else
        {
            $apiProblem = new ApiProblem(400, ApiProblem::TYPE_INVALID_REQUEST_BODY_DATATYPE);

            throw new ApiProblemException($apiProblem);
        }

        $response = new JsonResponse($responseData, 200);
        return $response;
    }
}

It works when the code throw new ApiProblemException($apiProblem); is not executed.

1

1 Answers

2
votes

You have a typo in your filename

Project\src\AppBundle\Libraries\Core\Api\ApiProblemExeption.php

it should be

ApiProblemException.php