You are here

public function Upload::opUpload in IMCE 8.2

Same name and namespace in other branches
  1. 8 src/Plugin/ImcePlugin/Upload.php \Drupal\imce\Plugin\ImcePlugin\Upload::opUpload()

Operation handler: upload.

File

src/Plugin/ImcePlugin/Upload.php, line 45

Class

Upload
Defines Imce Upload plugin.

Namespace

Drupal\imce\Plugin\ImcePlugin

Code

public function opUpload(ImceFM $fm) {
  $folder = $fm->activeFolder;
  if (!$folder || !$folder
    ->getPermission('upload_files')) {
    return;
  }

  // Prepare save options.
  $destination = $folder
    ->getUri();
  $replace = $fm
    ->getConf('replace', FileSystemInterface::EXISTS_RENAME);
  $validators = [];

  // Extension validator.
  $exts = $fm
    ->getConf('extensions', '');
  $validators['file_validate_extensions'] = [
    $exts === '*' ? NULL : $exts,
  ];

  // File size and user quota validator.
  $validators['file_validate_size'] = [
    $fm
      ->getConf('maxsize'),
    $fm
      ->getConf('quota'),
  ];

  // Image resolution validator.
  $width = $fm
    ->getConf('maxwidth');
  $height = $fm
    ->getConf('maxheight');
  if ($width || $height) {
    $validators['file_validate_image_resolution'] = [
      ($width ? $width : 10000) . 'x' . ($height ? $height : 10000),
    ];
  }

  // Name validator.
  $validators[get_class($this) . '::validateFileName'] = [
    $fm,
  ];

  // Save files.
  if ($files = file_save_upload('imce', $validators, $destination, NULL, $replace)) {
    $fs = \Drupal::service('file_system');
    foreach (array_filter($files) as $file) {

      // Set status and save.
      $file
        ->setPermanent();
      $file
        ->save();

      // Add to the folder and to js response.
      $name = $fs
        ->basename($file
        ->getFileUri());
      $item = $folder
        ->addFile($name);
      $item->uuid = $file
        ->uuid();
      $item
        ->addToJs();
    }
  }
}