You are here

public function Resize::resizeItems in IMCE 8

Same name and namespace in other branches
  1. 8.2 src/Plugin/ImcePlugin/Resize.php \Drupal\imce\Plugin\ImcePlugin\Resize::resizeItems()

Resizes a list of imce items and returns succeeded ones.

1 call to Resize::resizeItems()
Resize::opResize in src/Plugin/ImcePlugin/Resize.php
Operation handler: resize.

File

src/Plugin/ImcePlugin/Resize.php, line 64

Class

Resize
Defines Imce Resize plugin.

Namespace

Drupal\imce\Plugin\ImcePlugin

Code

public function resizeItems(ImceFM $fm, array $items, $width, $height, $copy = FALSE) {
  $factory = \Drupal::service('image.factory');
  $fs = \Drupal::service('file_system');
  $success = [];
  foreach ($items as $item) {
    $uri = $item
      ->getUri();
    $image = $factory
      ->get($uri);

    // Check vallidity.
    if (!$image
      ->isValid()) {
      continue;
    }

    // Check if resizing is needed.
    $resize = $image
      ->getWidth() != $width || $image
      ->getHeight() != $height;
    if (!$resize && !$copy) {
      continue;
    }
    if ($resize && !$image
      ->resize($width, $height)) {
      continue;
    }

    // Save.
    $destination = $copy ? $fs
      ->createFilename($fs
      ->basename($uri), $fs
      ->dirname($uri)) : $uri;
    if (!$image
      ->save($destination)) {
      continue;
    }

    // Create a new file record.
    if ($copy) {
      $filename = $fs
        ->basename($destination);
      $values = [
        'uid' => $fm->user
          ->id(),
        'status' => 1,
        'filename' => $filename,
        'uri' => $destination,
        'filesize' => $image
          ->getFileSize(),
        'filemime' => $image
          ->getMimeType(),
      ];
      $file = \Drupal::entityTypeManager()
        ->getStorage('file')
        ->create($values);

      // Check quota.
      if ($errors = file_validate_size($file, 0, $fm
        ->getConf('quota'))) {
        $fs
          ->delete($destination);
        $fm
          ->setMessage($errors[0]);
      }
      else {
        $file
          ->save();

        // Add imce item.
        $item->parent
          ->addFile($filename)
          ->addToJs();
      }
    }
    else {
      if ($file = Imce::getFileEntity($uri)) {
        $file
          ->setSize($image
          ->getFileSize());
        $file
          ->save();
      }

      // Add to js.
      $item
        ->addToJs();
    }
    $success[] = $item;
  }
  return $success;
}