function FileUpload::handleFileUploadForExistingResource

Same name in other branches
  1. 9 core/modules/jsonapi/src/Controller/FileUpload.php \Drupal\jsonapi\Controller\FileUpload::handleFileUploadForExistingResource()
  2. 8.9.x core/modules/jsonapi/src/Controller/FileUpload.php \Drupal\jsonapi\Controller\FileUpload::handleFileUploadForExistingResource()
  3. 10 core/modules/jsonapi/src/Controller/FileUpload.php \Drupal\jsonapi\Controller\FileUpload::handleFileUploadForExistingResource()

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

core/modules/jsonapi/src/Controller/FileUpload.php, line 96

Class

FileUpload
Handles file upload requests.

Namespace

Drupal\jsonapi\Controller

Code

public function handleFileUploadForExistingResource(Request $request, ResourceType $resource_type, string $file_field_name, FieldableEntityInterface $entity) : Response {
    $result = $this->handleFileUploadForResource($request, $resource_type, $file_field_name, $entity);
    $file = $result->getFile();
    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();
    $route_parameters = [
        'entity' => $entity->uuid(),
    ];
    $route_name = sprintf('jsonapi.%s.%s.related', $resource_type->getTypeName(), $resource_type->getPublicName($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);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.