You are here

public function FileUpload::handleFileUploadForExistingResource in JSON:API 8.2

Handles JSON:API file upload requests.

Parameters

\Symfony\Component\HttpFoundation\Request $request: The HTTP request object.

\Drupal\jsonapi\ResourceType\ResourceType $resource_type: The JSON:API resource type for the current request.

string $file_field_name: The file field for which the file is to be uploaded.

\Drupal\Core\Entity\FieldableEntityInterface $entity: The entity for which the file is to be uploaded.

Return value

\Drupal\jsonapi\ResourceResponse The response object.

Throws

\Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException Thrown when there are validation errors.

\Drupal\Core\Entity\EntityStorageException Thrown if the upload's target resource could not be saved.

\Exception Thrown if an exception occurs during a subrequest to fetch the newly created file entity.

File

src/Controller/FileUpload.php, line 114

Class

FileUpload
Handles file upload requests.

Namespace

Drupal\jsonapi\Controller

Code

public function handleFileUploadForExistingResource(Request $request, ResourceType $resource_type, $file_field_name, FieldableEntityInterface $entity) {
  $field_definition = $this
    ->validateAndLoadFieldDefinition($resource_type
    ->getEntityTypeId(), $resource_type
    ->getBundle(), $file_field_name);
  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 (ConstraintViolationInterface $violation) {
      return PlainTextOutput::renderFromHtml($violation
        ->getMessage());
    }, (array) $violations
      ->getIterator()));
    throw new UnprocessableEntityHttpException($message);
  }
  if ($field_definition
    ->getFieldStorageDefinition()
    ->getCardinality() === 1) {
    $entity->{$file_field_name} = $file;
  }
  else {
    $entity
      ->get($file_field_name)
      ->appendItem($file);
  }
  static::validate($entity, [
    $file_field_name,
  ]);
  $entity
    ->save();
  $route_parameters = [
    'entity' => $entity
      ->uuid(),
  ];
  $route_name = sprintf('jsonapi.%s.%s.related', $resource_type
    ->getTypeName(), $file_field_name);
  $related_url = Url::fromRoute($route_name, $route_parameters)
    ->toString(TRUE);
  $request = Request::create($related_url
    ->getGeneratedUrl(), 'GET', [], $request->cookies
    ->all(), [], $request->server
    ->all());
  return $this->httpKernel
    ->handle($request, HttpKernelInterface::SUB_REQUEST);
}