UnprocessableEntityHttpException example

        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());
        }
        catch (InvalidArgumentException $e) {
          throw new UnprocessableEntityHttpException($e->getMessage());
        }
      }
    }

    return $unserialized;
  }

  /** * Delegates an incoming request to the appropriate REST resource plugin. * * @param \Drupal\Core\Routing\RouteMatchInterface $route_match * The route match. * @param \Symfony\Component\HttpFoundation\Request $request * The HTTP request object. * @param mixed|null $unserialized * The unserialized request body, if any. * @param \Drupal\rest\Plugin\ResourceInterface $resource * The REST resource plugin. * * @return \Symfony\Component\HttpFoundation\Response|\Drupal\rest\ResourceResponseInterface * The REST resource response. */


namespace Symfony\Component\HttpKernel\Tests\Exception;

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

class UnprocessableEntityHttpExceptionTest extends HttpExceptionTest
{
    protected function createException(string $message = '', \Throwable $previous = null, int $code = 0, array $headers = []): HttpException
    {
        return new UnprocessableEntityHttpException($message$previous$code$headers);
    }
}
throw new AccessDeniedHttpException('Only anonymous users can register a user.');
    }

    // Verify that the current user can register a user account.     if ($this->userSettings->get('register') == UserInterface::REGISTER_ADMINISTRATORS_ONLY) {
      throw new AccessDeniedHttpException('You cannot register a new user account.');
    }

    if (!$this->userSettings->get('verify_mail')) {
      if (empty($account->getPassword())) {
        // If no e-mail verification then the user must provide a password.         throw new UnprocessableEntityHttpException('No password provided.');
      }
    }
    else {
      if (!empty($account->getPassword())) {
        // If e-mail verification required then a password cannot provided.         // The password will be set when the user logs in.         throw new UnprocessableEntityHttpException('A Password cannot be specified. It will be generated on login.');
      }
    }
  }

  
    // as in \Drupal\file\Upload\FileUploadHandler::handleFileUpload().     // For backwards compatibility this part is copied from ::validate() to     // leave that method behavior unchanged.     // @todo Improve this with a file uploader service in     // https://www.drupal.org/project/drupal/issues/2940383     $errors = file_validate($file$validators);

    if (!empty($errors)) {
      $message = "Unprocessable Entity: file validation failed.\n";
      $message .= implode("\n", array_map([PlainTextOutput::class, 'renderFromHtml']$errors));

      throw new UnprocessableEntityHttpException($message);
    }

    $file->setFileUri($file_uri);
    // Move the file to the correct location after validation. Use     // FileSystemInterface::EXISTS_ERROR as the file location has already been     // determined above in FileSystem::getDestinationFilename().     try {
      $this->fileSystem->move($temp_file_path$file_uri, FileSystemInterface::EXISTS_ERROR);
    }
    catch (FileException $e) {
      throw new HttpException(500, 'Temporary file could not be moved to file location');
    }
    foreach ($data as $public_field_name => $field_value) {
      $internal_name = $resource_type->getInternalName($public_field_name);

      // Skip any disabled field, except the always required bundle key and       // required-in-case-of-PATCHing uuid key.       // @see \Drupal\jsonapi\ResourceType\ResourceTypeRepository::getFieldMapping()       if ($resource_type->hasField($internal_name) && !$resource_type->isFieldEnabled($internal_name) && $bundle_key !== $internal_name && $uuid_key !== $internal_name) {
        continue;
      }

      if (!isset($field_map[$internal_name]) || !in_array($resource_type->getBundle()$field_map[$internal_name]['bundles'], TRUE)) {
        throw new UnprocessableEntityHttpException(sprintf(
          'The attribute %s does not exist on the %s resource type.',
          $internal_name,
          $resource_type->getTypeName()
        ));
      }

      $field_type = $field_map[$internal_name]['type'];
      $field_class = $this->pluginManager->getDefinition($field_type)['list_class'];

      $field_denormalization_context = array_merge($context[
        'field_type' => $field_type,
        
// Begin building file entity.     $file = File::create([]);
    $file->setOwnerId($this->currentUser->id());
    $file->setFilename($prepared_filename);
    $file->setMimeType($this->mimeTypeGuesser->guessMimeType($prepared_filename));

    $file->setFileUri($file_uri);
    $file->setSize(@filesize($temp_file_path));

    $violations = $this->validate($file$validators);
    if ($violations->count() > 0) {
      throw new UnprocessableEntityHttpException($violations->__toString());
    }

    try {
      $this->fileSystem->move($temp_file_path$file_uri, FileSystemInterface::EXISTS_ERROR);
    }
    catch (FileException $e) {
      throw new HttpException(500, 'Temporary file could not be moved to file location');
    }

    $file->save();

    
// Filter violations by explicitly provided array of field names.       $violations->filterByFields(array_diff(array_keys($entity->getFieldDefinitions())$fields_to_validate));
    }

    if ($violations->count() > 0) {
      $message = "Unprocessable Entity: validation failed.\n";
      foreach ($violations as $violation) {
        // We strip every HTML from the error message to have a nicer to read         // message on REST responses.         $message .= $violation->getPropertyPath() . ': ' . PlainTextOutput::renderFromHtml($violation->getMessage()) . "\n";
      }
      throw new UnprocessableEntityHttpException($message);
    }
  }

}
try {
      $context = ['resource_type' => $resource_type];
      if ($relationship_field_name) {
        $context['related'] = $resource_type->getInternalName($relationship_field_name);
      }
      return $this->serializer->denormalize($decoded$class, 'api_json', $context);
    }
    // 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());
    }
    catch (InvalidArgumentException $e) {
      throw new UnprocessableEntityHttpException($e->getMessage());
    }
  }

  /** * Gets a basic query for a collection. * * @param \Drupal\jsonapi\ResourceType\ResourceType $resource_type * The base JSON:API resource type for the query. * @param array $params * The parameters for the query. * @param \Drupal\Core\Cache\CacheableMetadata $query_cacheability * Collects cacheability for the query. * * @return \Drupal\Core\Entity\Query\QueryInterface * A new query. */
static::ensureFileUploadAccess($this->currentUser, $field_definition$entity);

    $filename = $this->fileUploader->validateAndParseContentDispositionHeader($request);
    $file = $this->fileUploader->handleFileUploadForField($field_definition$filename$this->currentUser);

    if ($file instanceof EntityConstraintViolationListInterface) {
      $violations = $file;
      $message = "Unprocessable Entity: file validation failed.\n";
      $message .= implode("\n", array_map(function DConstraintViolationInterface $violation) {
        return PlainTextOutput::renderFromHtml($violation->getMessage());
      }(array) $violations->getIterator()));
      throw new UnprocessableEntityHttpException($message);
    }

    if ($resource_type->getFieldByInternalName($file_field_name)->hasOne()) {
      $entity->{$file_field_name} = $file;
    }
    else {
      $entity->get($file_field_name)->appendItem($file);
    }
    static::validate($entity[$file_field_name]);
    $entity->save();

    
protected static function validateRequestBody(array $document, ResourceType $resource_type) {
    // Ensure that the relationships key was not placed in the top level.     if (isset($document['relationships']) && !empty($document['relationships'])) {
      throw new BadRequestHttpException("Found \"relationships\" within the document's top level. The \"relationships\" key must be within resource object.");
    }
    // Ensure that the resource object contains the "type" key.     if (!isset($document['data']['type'])) {
      throw new BadRequestHttpException("Resource object must include a \"type\".");
    }
    // Ensure that the client provided ID is a valid UUID.     if (isset($document['data']['id']) && !Uuid::isValid($document['data']['id'])) {
      throw new UnprocessableEntityHttpException('IDs should be properly generated and formatted UUIDs as described in RFC 4122.');
    }
    // Ensure that no relationship fields are being set via the attributes     // resource object member.     if (isset($document['data']['attributes'])) {
      $received_attribute_field_names = array_keys($document['data']['attributes']);
      $relationship_field_names = array_keys($resource_type->getRelatableResourceTypes());
      if ($relationship_fields_sent_as_attributes = array_intersect($received_attribute_field_names$relationship_field_names)) {
        throw new UnprocessableEntityHttpException(sprintf("The following relationship fields were provided as attributes: [ %s ]", implode(', ', $relationship_fields_sent_as_attributes)));
      }
    }
  }

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