BadRequestHttpException example

$defaults['entity']->addCacheContexts([static::CACHE_CONTEXT]);
    }

    // If no version was specified, nothing is left to enhance.     if (!$has_version_param) {
      return $defaults;
    }

    // Provide a helpful error when a version is specified with an unsafe     // method.     if (!$request->isMethodCacheable()) {
      throw new BadRequestHttpException(sprintf('%s requests with a `%s` query parameter are not supported.', $request->getMethod()static::RESOURCE_VERSION_QUERY_PARAMETER));
    }

    $resource_version_identifier = $request->query->get(static::RESOURCE_VERSION_QUERY_PARAMETER);

    if (!static::isValidVersionIdentifier($resource_version_identifier)) {
      $cacheability = (new CacheableMetadata())->addCacheContexts([static::CACHE_CONTEXT]);
      $message = sprintf('A resource version identifier was provided in an invalid format: `%s`', $resource_version_identifier);
      throw new CacheableBadRequestHttpException($cacheability$message);
    }

    // Determine if the request is for a collection resource.

  protected function validateAndParseContentDispositionHeader(Request $request) {
    // Firstly, check the header exists.     if (!$request->headers->has('content-disposition')) {
      throw new BadRequestHttpException('"Content-Disposition" header is required. A file name in the format "filename=FILENAME" must be provided');
    }

    $content_disposition = $request->headers->get('content-disposition');

    // Parse the header value. This regex does not allow an empty filename.     // i.e. 'filename=""'. This also matches on a word boundary so other keys     // like 'not_a_filename' don't work.     if (!preg_match(static::REQUEST_HEADER_FILENAME_REGEX, $content_disposition$matches)) {
      throw new BadRequestHttpException('No filename found in "Content-Disposition" header. A file name in the format "filename=FILENAME" must be provided');
    }

    

  }

  /** * @covers ::normalize */
  public function testNormalizeException() {
    $normalized = $this
      ->container
      ->get('jsonapi.serializer')
      ->normalize(
        new JsonApiDocumentTopLevel(new ErrorCollection([new BadRequestHttpException('Lorem')])new NullIncludedData()new LinkCollection([])),
        'api_json',
        []
      )->getNormalization();
    $this->assertNotEmpty($normalized['errors']);
    $this->assertArrayNotHasKey('data', $normalized);
    $this->assertEquals(400, $normalized['errors'][0]['status']);
    $this->assertEquals('Lorem', $normalized['errors'][0]['detail']);
    $this->assertEquals([
      'info' => [
        'href' => 'http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.1',
      ],
      

  public function render(Request $request) {
    if (!$request->request->has('ids')) {
      throw new BadRequestHttpException('No contextual ids specified.');
    }
    $ids = $request->request->all('ids');

    if (!$request->request->has('tokens')) {
      throw new BadRequestHttpException('No contextual ID tokens specified.');
    }
    $tokens = $request->request->all('tokens');

    $rendered = [];
    foreach ($ids as $key => $id) {
      if (!isset($tokens[$key]) || !hash_equals($tokens[$key], Crypt::hmacBase64($id, Settings::getHashSalt() . \Drupal::service('private_key')->get()))) {
        
public function validationProvider() {
    return [
      [['path' => 'some_field', 'value' => 'some_value'], NULL],
      [
        ['path' => 'some_field', 'value' => 'some_value', 'operator' => '='],
        NULL,
      ],
      [['path' => 'some_field', 'operator' => 'IS NULL'], NULL],
      [['path' => 'some_field', 'operator' => 'IS NOT NULL'], NULL],
      [
        ['path' => 'some_field', 'operator' => 'IS', 'value' => 'some_value'],
        new BadRequestHttpException("The 'IS' operator is not allowed in a filter parameter."),
      ],
      [
        [
          'path' => 'some_field',
          'operator' => 'NOT_ALLOWED',
          'value' => 'some_value',
        ],
        new BadRequestHttpException("The 'NOT_ALLOWED' operator is not allowed in a filter parameter."),
      ],
      [
        [
          
/** * {@inheritdoc} */
  protected function getGroups(AttachedAssetsInterface $attached_assets, Request $request): array {
    // The header and footer scripts are two distinct sets of asset groups. The     // $group_key is not sufficient to find the group, we also need to locate it     // within either the header or footer set.     $language = $this->languageManager()->getLanguage($request->get('language'));
    [$js_assets_header$js_assets_footer] = $this->assetResolver->getJsAssets($attached_assets, FALSE, $language);
    $scope = $request->get('scope');
    if (!isset($scope)) {
      throw new BadRequestHttpException('The URL must have a scope query argument.');
    }
    $assets = $scope === 'header' ? $js_assets_header : $js_assets_footer;
    // While the asset resolver will find settings, these are never aggregated,     // so filter them out.     unset($assets['drupalSettings']);
    return $this->grouper->group($assets);
  }

}
$this->assertEquals('403', $flattened->getStatusCode());

        $flattened = FlattenException::createFromThrowable(new \DivisionByZeroError());
        $this->assertEquals('500', $flattened->getStatusCode());

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

        $flattened = FlattenException::createFromThrowable(new UnauthorizedHttpException('Basic realm="My Realm"'));
        $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());

        
$definition = $resource->getPluginDefinition();

      // First decode the request data. We can then determine if the       // serialized data was malformed.       try {
        $unserialized = $this->serializer->decode($received$format['request_method' => $method]);
      }
      catch (UnexpectedValueException $e) {
        // If an exception was thrown at this stage, there was a problem         // decoding the data. Throw a 400 http exception.         throw new BadRequestHttpException($e->getMessage());
      }

      // Then attempt to denormalize if there is a serialization class.       if (!empty($definition['serialization_class'])) {
        try {
          $unserialized = $this->serializer->denormalize($unserialized$definition['serialization_class']$format['request_method' => $method]);
        }
        // These two serialization exception types mean there was a problem         // with the structure of the decoded data and it's not valid.         catch (UnexpectedValueException $e) {
          throw new UnprocessableEntityHttpException($e->getMessage());
        }

  public function mediaEntityMetadata(Request $request) {
    $uuid = $request->query->get('uuid');
    if (!$uuid || !Uuid::isValid($uuid)) {
      throw new BadRequestHttpException();
    }
    // Access is enforced on route level.     // @see \Drupal\ckeditor5\Controller\CKEditor5MediaController::access().     if (!$media = $this->entityRepository->loadEntityByUuid('media', $uuid)) {
      throw new NotFoundHttpException();
    }
    $image_field = $this->getMediaImageSourceFieldName($media);
    $response = [];
    $response['type'] = $media->bundle();
    // If this uses the image media source and the "alt" field is enabled,     // expose additional metadata.
public function get($id = NULL) {
    if ($id) {
      $record = Database::getConnection()->query("SELECT * FROM {watchdog} WHERE [wid] = :wid", [':wid' => $id])
        ->fetchAssoc();
      if (!empty($record)) {
        return new ResourceResponse($record);
      }

      throw new NotFoundHttpException("Log entry with ID '$id' was not found");
    }

    throw new BadRequestHttpException('No log entry ID was provided');
  }

}
$this->requestStack->push($request);
        $response = null;
        try {
            return $response = $this->handleRaw($request$type);
        } catch (\Throwable $e) {
            if ($e instanceof \Error && !$this->handleAllThrowables) {
                throw $e;
            }

            if ($e instanceof RequestExceptionInterface) {
                $e = new BadRequestHttpException($e->getMessage()$e);
            }
            if (false === $catch) {
                $this->finishRequest($request$type);

                throw $e;
            }

            return $response = $this->handleThrowable($e$request$type);
        } finally {
            $this->requestStack->pop();

            

  public function denormalize($data$class$format = NULL, array $context = []): mixed {
    // If we get here, it's via a relationship POST/PATCH.     /** @var \Drupal\jsonapi\ResourceType\ResourceType $resource_type */
    $resource_type = $context['resource_type'];
    $entity_type_id = $resource_type->getEntityTypeId();
    $field_definitions = $this->fieldManager->getFieldDefinitions(
      $entity_type_id,
      $resource_type->getBundle()
    );
    if (empty($context['related']) || empty($field_definitions[$context['related']])) {
      throw new BadRequestHttpException('Invalid or missing related field.');
    }
    /** @var \Drupal\field\Entity\FieldConfig $field_definition */
    $field_definition = $field_definitions[$context['related']];
    $target_resource_types = $resource_type->getRelatableResourceTypesByField($resource_type->getPublicName($context['related']));
    $target_resource_type_names = array_map(function DResourceType $resource_type) {
      return $resource_type->getTypeName();
    }$target_resource_types);

    $is_multiple = $field_definition->getFieldStorageDefinition()->isMultiple();
    $data = $this->massageRelationshipInput($data$is_multiple);
    $resource_identifiers = array_map(function D$value) use ($target_resource_type_names) {
      

  public static function findSitePath(Request $request$require_settings = TRUE, $app_root = NULL) {
    if (static::validateHostname($request) === FALSE) {
      throw new BadRequestHttpException();
    }

    if ($app_root === NULL) {
      $app_root = static::guessApplicationRoot();
    }

    // Check for a test override.     if ($test_prefix = drupal_valid_test_ua()) {
      $test_db = new TestDatabase($test_prefix);
      return $test_db->getTestSitePath();
    }

    

  public function render(Request $request) {
    // @todo Move domain check logic to a separate method.     $allowed_domain = \Drupal::config('media.settings')->get('iframe_domain');
    if ($allowed_domain) {
      $allowed_host = parse_url($allowed_domain, PHP_URL_HOST);
      $host = parse_url($request->getSchemeAndHttpHost(), PHP_URL_HOST);
      if ($allowed_host !== $host) {
        throw new BadRequestHttpException('This resource is not available');
      }
    }

    $url = $request->query->get('url');
    $max_width = $request->query->getInt('max_width');
    $max_height = $request->query->getInt('max_height');

    // Hash the URL and max dimensions, and ensure it is equal to the hash     // parameter passed in the query string.     $hash = $this->iFrameUrlHelper->getHash($url$max_width$max_height);
    if (!hash_equals($hash$request->query->get('hash', ''))) {
      

  public function validateAndParseContentDispositionHeader(Request $request) {
    // First, check the header exists.     if (!$request->headers->has('content-disposition')) {
      throw new BadRequestHttpException('"Content-Disposition" header is required. A file name in the format "filename=FILENAME" must be provided.');
    }

    $content_disposition = $request->headers->get('content-disposition');

    // Parse the header value. This regex does not allow an empty filename.     // i.e. 'filename=""'. This also matches on a word boundary so other keys     // like 'not_a_filename' don't work.     if (!preg_match(static::REQUEST_HEADER_FILENAME_REGEX, $content_disposition$matches)) {
      throw new BadRequestHttpException('No filename found in "Content-Disposition" header. A file name in the format "filename=FILENAME" must be provided.');
    }

    
Home | Imprint | This part of the site doesn't use cookies.