BonBonSlick
@BonBonSlick
Vanilla Web Architect

Как ловить ошибки при валидации API запроса через Argument Resolver?

Гайд который использовался

Выбивает огромное html полотно с ошибками
1) App\Tests\UAT\PostControllerTest::createEntity
PHPUnit\Framework\Exception: Symfony\Component\HttpFoundation\Response {#749
  +headers: Symfony\Component\HttpFoundation\ResponseHeaderBag {#743
    #computedCacheControl: array:2 [
      "no-cache" => true
      "private" => true
    ]
    #cookies: []
    #headerNames: array:5 [
      "content-type" => "Content-Type"
      "cache-control" => "Cache-Control"
      "date" => "Date"
      "x-robots-tag" => "X-Robots-Tag"
      "allow" => "Allow"
    ]
    #headers: array:5 [
      "content-type" => array:1 [
        0 => "text/html; charset=UTF-8"
      ]
      "cache-control" => array:1 [
        0 => "no-cache, private"
      ]
      "date" => array:1 [
        0 => "Wed, 26 Feb 2020 20:17:18 GMT"
      ]
      "x-robots-tag" => array:1 [
        0 => "noindex"
      ]
      "allow" => array:1 [
        0 => "POST"
      ]
    ]
    #cacheControl: []
  }
  #content: """
    <!-- Object(App\Entity\Post\DTO\CreatePostRequest).content:\n
        This value should not be blank. (code c1051bb4-d103-4f74-8988-acbcafc7fdc3)\n
    Object(App\Entity\Post\DTO\CreatePostRequest).thumbnailUrl:\n
        This value should not be blank. (code c1051bb4-d103-4f74-8988-acbcafc7fdc3)\n
     (400 Bad Request) -->\n
    <!DOCTYPE html>\n
    <html lang="en">\n
        <head>\n
            <meta charset="UTF-8" />\n

....
    \n
    /*]]>*/        </script>\n
        </body>\n
    </html>\n
    <!-- Object(App\Entity\Post\DTO\CreatePostRequest).content:\n
        This value should not be blank. (code c1051bb4-d103-4f74-8988-acbcafc7fdc3)\n
    Object(App\Entity\Post\DTO\CreatePostRequest).thumbnailUrl:\n
        This value should not be blank. (code c1051bb4-d103-4f74-8988-acbcafc7fdc3)\n
     (400 Bad Request) -->
    """
  #version: "1.1"
  #statusCode: 400
  #statusText: "Bad Request"
  #charset: "UTF-8"
}

Caused by
ErrorException: unserialize(): Error at offset 0 of 150553 bytes in /var/www/event_app_api/vendor/phpunit/phpunit/src/Util/PHP/AbstractPhpProcess.php:272
Stack trace:


/**
     * @RESTPost("/posts/create")
     *
     * @param CreatePostRequest                $request
     * @param ConstraintViolationListInterface $validationErrors
     *
     * @return JsonResponse
     *
     */
    public function createAction(
        CreatePostRequest $request,
        ConstraintViolationListInterface $validationErrors
    ): JsonResponse
    {
        dump('VALIDATED');
        die;

    }
  • Вопрос задан
  • 57 просмотров
Решения вопроса 2
maksim92
@maksim92
Нашел решение — пометь вопрос ответом!
BonBonSlick
@BonBonSlick Автор вопроса
Vanilla Web Architect
<?php declare(strict_types=1);

/*
 * Created by BonBonSlick
 */

namespace App\Subscribers;


use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Class self
 */
final class ValidationFormatterSubscriber implements EventSubscriberInterface
{

    /**
     * @return array
     */
    public static function getSubscribedEvents(): array
    {
        return array(
            KernelEvents::EXCEPTION => 'onKernelException'
        );
    }

    /**
     * @param ExceptionEvent $event
     */
    public function onKernelException(ExceptionEvent $event): void
    {
        $exception = $event->getThrowable();

        if (false === $exception instanceof BadRequestHttpException) {
            return;
        }

        $titles = $this->getStringBetweenStrings($exception->getMessage(), ').', ':');
        $errors = $this->getStringBetweenStrings($exception->getMessage(), ':', '.');

        $normalizedErrors = [];
        foreach ($errors as $key => $error) {
            $normalizedErrors[$titles[$key]] = trim($error);
        }

        $event->setResponse(
            new JsonResponse([
                'status' => 'error',
                'data' => $normalizedErrors,
            ], Response::HTTP_BAD_REQUEST));
    }

    /**
     * @param string $searchString
     * @param string $startDelimiter
     * @param string $endDelimiter
     *
     * @return array
     */
    private function getStringBetweenStrings(string $searchString, string $startDelimiter, string $endDelimiter): array
    {
        $contents = [];
        $startDelimiterLength = strlen($startDelimiter);
        $endDelimiterLength = strlen($endDelimiter);
        $startFrom = $contentStart = $contentEnd = 0;
        while (false !== ($contentStart = strpos($searchString, $startDelimiter, $startFrom))) {
            $contentStart += $startDelimiterLength;
            $contentEnd = strpos($searchString, $endDelimiter, $contentStart);
            if (false === $contentEnd) {
                break;
            }
            $contents[] = substr($searchString, $contentStart, $contentEnd - $contentStart);
            $startFrom = $contentEnd + $endDelimiterLength;
        }

        return $contents;
    }
}
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы