You are here

public function RotateController::rotate in Insert 8.2

Same name and namespace in other branches
  1. 8 src/Controller/RotateController.php \Drupal\insert\Controller\RotateController::rotate()

Rotates an image regenerating image derivatives for every image style and saving the corresponding entity with the updated image dimensions.

Parameters

\Symfony\Component\HttpFoundation\Request $request:

Return value

\Symfony\Component\HttpFoundation\JsonResponse

1 string reference to 'RotateController::rotate'
insert.routing.yml in ./insert.routing.yml
insert.routing.yml

File

src/Controller/RotateController.php, line 25

Class

RotateController

Namespace

Drupal\insert\Controller

Code

public function rotate(Request $request) {
  $fid = $request->query
    ->get('fid', NULL);
  $degree = $request->query
    ->get('degree', NULL);
  $nid = $request->query
    ->get('nid', NULL);
  $absolute = \Drupal::config('insert.config')
    ->get('absolute');
  if ($fid === NULL || $degree === NULL || $nid === NULL) {
    return new JsonResponse([]);
  }
  $file = File::load($fid);
  if ($file === NULL) {
    return new JsonResponse([]);
  }

  /** @var \Drupal\Core\Image\ImageInterface $image */
  $image = \Drupal::service('image.factory')
    ->get($file
    ->getFileUri());
  if (!$image
    ->isValid()) {
    return new JsonResponse([]);
  }
  if ($image
    ->rotate(floatval($degree))) {
    $image
      ->save();
  }
  $styleUrls = [
    'image' => $this
      ->convertUrl(file_create_url($image
      ->getSource()), $absolute),
  ];

  /* @var ImageStyle $style */
  foreach (ImageStyle::loadMultiple() as $style) {
    $style
      ->flush($image
      ->getSource());
    $url = $style
      ->buildUrl($image
      ->getSource());
    $styleUrls[$style
      ->getName()] = $this
      ->convertUrl($url, $absolute);
  }
  $revision = NULL;

  // Update dimensions in node.
  $node = Node::load($nid);
  if ($node !== NULL) {

    /** @var \Drupal\Core\Field\FieldDefinitionInterface $definition */
    foreach ($node
      ->getFieldDefinitions() as $field_name => $definition) {
      if ($definition
        ->getType() === 'image') {
        $value = $node
          ->get($field_name)
          ->getValue();
        $found = FALSE;
        foreach ($value as &$item) {
          if ($item['target_id'] === $fid) {
            $width = $item['width'];
            $item['width'] = $item['height'];
            $item['height'] = $width;
            $node
              ->set($field_name, $value, FALSE);
            $node
              ->save();
            $found = TRUE;
            break;
          }
        }
        if ($found) {
          break;
        }
      }
    }
    $revision = $node
      ->getChangedTimeAcrossTranslations();
  }
  return new JsonResponse([
    'revision' => $revision,
    'data' => $styleUrls,
  ]);
}