MethodNotAllowedHttpException example

$this->assertEquals('301', $response->getStatusCode());
        $this->assertEquals('/login', $response->headers->get('Location'));
    }

    public function testHandleHttpException()
    {
        $dispatcher = new EventDispatcher();
        $dispatcher->addListener(KernelEvents::EXCEPTION, function D$event) {
            $event->setResponse(new Response($event->getThrowable()->getMessage()));
        });

        $kernel = $this->getHttpKernel($dispatcherstatic fn () => throw new MethodNotAllowedHttpException(['POST']));
        $response = $kernel->handle(new Request());

        $this->assertEquals('405', $response->getStatusCode());
        $this->assertEquals('POST', $response->headers->get('Allow'));
    }

    public function getStatusCodes()
    {
        return [
            [200, 404],
            [404, 200],
            [
$this->assertEquals('401', $flattened->getStatusCode());

        $flattened = FlattenException::createFromThrowable(new BadRequestHttpException());
        $this->assertEquals('400', $flattened->getStatusCode());

        $flattened = FlattenException::createFromThrowable(new NotAcceptableHttpException());
        $this->assertEquals('406', $flattened->getStatusCode());

        $flattened = FlattenException::createFromThrowable(new ConflictHttpException());
        $this->assertEquals('409', $flattened->getStatusCode());

        $flattened = FlattenException::createFromThrowable(new MethodNotAllowedHttpException(['POST']));
        $this->assertEquals('405', $flattened->getStatusCode());

        $flattened = FlattenException::createFromThrowable(new AccessDeniedHttpException());
        $this->assertEquals('403', $flattened->getStatusCode());

        $flattened = FlattenException::createFromThrowable(new GoneHttpException());
        $this->assertEquals('410', $flattened->getStatusCode());

        $flattened = FlattenException::createFromThrowable(new LengthRequiredHttpException());
        $this->assertEquals('411', $flattened->getStatusCode());

        


namespace Symfony\Component\HttpKernel\Tests\Exception;

use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;

class MethodNotAllowedHttpExceptionTest extends HttpExceptionTest
{
    public function testHeadersDefault()
    {
        $exception = new MethodNotAllowedHttpException(['GET', 'PUT']);
        $this->assertSame(['Allow' => 'GET, PUT']$exception->getHeaders());
    }

    public function testWithHeaderConstruct()
    {
        $headers = [
            'Cache-Control' => 'public, s-maxage=1200',
        ];

        $exception = new MethodNotAllowedHttpException(['get'], '', null, 0, $headers);

        

class DefaultExceptionSubscriberTest extends UnitTestCase {

  /** * @covers ::on4xx */
  public function testOn4xx() {
    $kernel = $this->prophesize(HttpKernelInterface::class);
    $request = Request::create('/test');
    $request->setRequestFormat('json');

    $e = new MethodNotAllowedHttpException(['POST', 'PUT'], 'test message');
    $event = new ExceptionEvent($kernel->reveal()$request, HttpKernelInterface::MAIN_REQUEST, $e);
    $subscriber = new DefaultExceptionSubscriber(new Serializer([][new JsonEncoder()])[]);
    $subscriber->on4xx($event);
    $response = $event->getResponse();

    $this->assertInstanceOf(Response::class$response);
    $this->assertEquals('{"message":"test message"}', $response->getContent());
    $this->assertEquals(405, $response->getStatusCode());
    $this->assertEquals('POST, PUT', $response->headers->get('Allow'));
    $this->assertEquals('application/json', $response->headers->get('Content-Type'));
  }

}
$this->assertInstanceOf($expected_response_class$response);
    $this->assertEquals('{"message":"test message"}', $response->getContent());
    $this->assertEquals(405, $response->getStatusCode());
    $this->assertEquals('POST, PUT', $response->headers->get('Allow'));
    $this->assertEquals('application/json', $response->headers->get('Content-Type'));
  }

  public function providerTestOn4xx() {
    return [
      'uncacheable exception' => [
        new MethodNotAllowedHttpException(['POST', 'PUT'], 'test message'),
        JsonResponse::class,
      ],
      'cacheable exception' => [
        new CacheableMethodNotAllowedHttpException((new CacheableMetadata())->setCacheContexts(['route'])['POST', 'PUT'], 'test message'),
        CacheableJsonResponse::class,
      ],
    ];
  }

}
 catch (ResourceNotFoundException $e) {
            $message = sprintf('No route found for "%s %s"', $request->getMethod()$request->getUriForPath($request->getPathInfo()));

            if ($referer = $request->headers->get('referer')) {
                $message .= sprintf(' (from "%s")', $referer);
            }

            throw new NotFoundHttpException($message$e);
        } catch (MethodNotAllowedException $e) {
            $message = sprintf('No route found for "%s %s": Method Not Allowed (Allow: %s)', $request->getMethod()$request->getUriForPath($request->getPathInfo())implode(', ', $e->getAllowedMethods()));

            throw new MethodNotAllowedHttpException($e->getAllowedMethods()$message$e);
        }
    }

    public function onKernelException(ExceptionEvent $event): void
    {
        if (!$this->debug || !($e = $event->getThrowable()) instanceof NotFoundHttpException) {
            return;
        }

        if ($e->getPrevious() instanceof NoConfigurationException) {
            $event->setResponse($this->createWelcomeResponse());
        }
/** * @covers ::onException */
  public function testOnExceptionWithUnknownFormat() {
    $config_factory = $this->getConfigFactoryStub();

    $kernel = $this->prophesize(HttpKernelInterface::class);
    $request = Request::create('/test');
    // \Drupal\Core\StackMiddleware\NegotiationMiddleware normally takes care     // of this so we'll hard code it here.     $request->setRequestFormat('bananas');
    $e = new MethodNotAllowedHttpException(['POST', 'PUT'], 'test message');
    $event = new ExceptionEvent($kernel->reveal()$request, HttpKernelInterface::MAIN_REQUEST, $e);
    $subscriber = new TestDefaultExceptionSubscriber($config_factory);
    $subscriber->setStringTranslation($this->getStringTranslationStub());
    $subscriber->onException($event);
    $response = $event->getResponse();

    $this->assertInstanceOf(Response::class$response);
    $this->assertStringStartsWith('The website encountered an unexpected error. Please try again later.<br><br><em class="placeholder">Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException</em>: test message in ', $response->getContent());
    $this->assertEquals(405, $response->getStatusCode());
    $this->assertEquals('POST, PUT', $response->headers->get('Allow'));
    // Also check that the text/plain content type was added.
$supported_methods = $route->getMethods();
      assert(count($supported_methods) > 0, 'JSON:API routes always have a method specified.');
      $is_read_only_route = empty(array_diff($supported_methods$read_only_methods));
      if (!$is_read_only_route) {
        $collection->remove($name);
      }
    }
    if (count($collection)) {
      return $collection;
    }
    throw new MethodNotAllowedHttpException(array_intersect($all_supported_methods$read_only_methods)sprintf("JSON:API is configured to accept only read operations. Site administrators can configure this at %s.", Url::fromRoute('jsonapi.settings')->setAbsolute()->toString(TRUE)->getGeneratedUrl()));
  }

}
$entity = reset($entities);
      // If the entity type is translatable, ensure we return the proper       // translation object for the current context.       if ($entity instanceof TranslatableInterface && $entity->isTranslatable()) {
        // @see https://www.drupal.org/project/drupal/issues/2624770         $entity = $this->entityRepository->getTranslationFromContext($entity, NULL, ['operation' => 'entity_upcast']);
        // JSON:API always has only one method per route.         $method = $defaults[RouteObjectInterface::ROUTE_OBJECT]->getMethods()[0];
        if (in_array($method['PATCH', 'DELETE'], TRUE)) {
          $current_content_language = $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();
          if ($method === 'DELETE' && (!$entity->isDefaultTranslation() || $entity->language()->getId() !== $current_content_language)) {
            throw new MethodNotAllowedHttpException(['GET'], 'Deleting a resource object translation is not yet supported. See https://www.drupal.org/docs/8/modules/jsonapi/translations.');
          }
          if ($method === 'PATCH' && $entity->language()->getId() !== $current_content_language) {
            $available_translations = implode(', ', array_keys($entity->getTranslationLanguages()));
            throw new MethodNotAllowedHttpException(['GET']sprintf('The requested translation of the resource object does not exist, instead modify one of the translations that do exist: %s.', $available_translations));
          }
        }
      }
      return $entity;
    }
    return NULL;
  }

  
 catch (ResourceNotFoundException $e) {
            $message = sprintf('No route found for "%s %s"', $request->getMethod()$request->getUriForPath($request->getPathInfo()));

            if ($referer = $request->headers->get('referer')) {
                $message .= sprintf(' (from "%s")', $referer);
            }

            throw new NotFoundHttpException($message$e);
        } catch (MethodNotAllowedException $e) {
            $message = sprintf('No route found for "%s %s": Method Not Allowed (Allow: %s)', $request->getMethod()$request->getUriForPath($request->getPathInfo())implode(', ', $e->getAllowedMethods()));

            throw new MethodNotAllowedHttpException($e->getAllowedMethods()$message$e);
        }
    }

    public function onKernelException(ExceptionEvent $event): void
    {
        if (!$this->debug || !($e = $event->getThrowable()) instanceof NotFoundHttpException) {
            return;
        }

        if ($e->getPrevious() instanceof NoConfigurationException) {
            $event->setResponse($this->createWelcomeResponse());
        }
Home | Imprint | This part of the site doesn't use cookies.