You are here

protected function ImportTrainingForm::importTrainingImage in Opigno module 8

Same name and namespace in other branches
  1. 3.x src/Form/ImportTrainingForm.php \Drupal\opigno_module\Form\ImportTrainingForm::importTrainingImage()

Create Media Image for training entity.

Parameters

array $training_content: List of settings from imported file.

Return value

Drupal\media\Entity\Media|Bool

Throws

\Exception

1 call to ImportTrainingForm::importTrainingImage()
ImportTrainingForm::importTraining in src/Form/ImportTrainingForm.php
Create training entity.

File

src/Form/ImportTrainingForm.php, line 470

Class

ImportTrainingForm
Import Course form.

Namespace

Drupal\opigno_module\Form

Code

protected function importTrainingImage($training_content) {
  if (!empty($training_content['field_learning_path_media_image']['media'])) {
    $file_info = $training_content['field_learning_path_media_image'];
    $media_image = $file_info['media'];
    $slide_file_path = $this->tmp . '/' . $file_info['media'][0]['target_id'] . '-' . $file_info['file_name'];
    $current_timestamp = \Drupal::time()
      ->getCurrentTime();
    $date = date('Y-m', $current_timestamp);

    // Save image file.
    $uri = $this
      ->copyFile($slide_file_path, 'public://' . $date . '/' . $file_info['file_name'], 'public://' . $date);
    if (!empty($uri)) {
      $file = File::Create([
        'uri' => $uri,
        'uid' => $this
          ->currentUser()
          ->id(),
        'status' => !empty($file_info['status']) ? $file_info['status'] : 1,
      ]);
      $file
        ->save();

      // Create Media Entity.
      $media_image[0]['target_id'] = $file
        ->id();
      $media = Media::create([
        'bundle' => $file_info['bundle'],
        'name' => $file_info['file_name'],
        'field_media_image' => $media_image,
      ]);
      $media
        ->save();
      return $media;
    }
  }
  return FALSE;
}