You are here

public static function Upload::valueCallback in Lightning Media 8.3

Same name and namespace in other branches
  1. 8.4 src/Element/Upload.php \Drupal\lightning_media\Element\Upload::valueCallback()
  2. 8 src/Element/Upload.php \Drupal\lightning_media\Element\Upload::valueCallback()
  3. 8.2 src/Element/Upload.php \Drupal\lightning_media\Element\Upload::valueCallback()

Determines how user input is mapped to an element's #value property.

Parameters

array $element: An associative array containing the properties of the element.

mixed $input: The incoming input to populate the form element. If this is FALSE, the element's default value should be returned.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Return value

mixed The value to assign to the element.

Overrides FormElement::valueCallback

File

src/Element/Upload.php, line 89

Class

Upload
A form element to handle file uploads.

Namespace

Drupal\lightning_media\Element

Code

public static function valueCallback(&$element, $input, FormStateInterface $form_state) {

  /** @var \Drupal\Core\File\FileSystemInterface $file_system */
  $file_system = \Drupal::service('file_system');
  $id = implode('_', $element['#parents']);
  $upload = \Drupal::request()->files
    ->get($id);
  if ($upload instanceof UploadedFile) {
    $destination = $file_system
      ->realPath($element['#upload_location']);
    $name = file_munge_filename($upload
      ->getClientOriginalName(), NULL);

    // Support both Drupal 8.7's FileSystemInterface API, and its earlier
    // antecedents. We need to call file_create_filename() in an obscure way
    // to prevent deprecation testing failures.
    $name = version_compare(\Drupal::VERSION, '8.7.0', '>=') ? $file_system
      ->createFilename($name, $destination) : call_user_func('file_create_filename', $name, $destination);
    $name = $upload
      ->move($destination, $name)
      ->getFilename();
    $uri = $element['#upload_location'];
    if (substr($uri, -1) != '/') {
      $uri .= '/';
    }
    $uri .= $name;
    $file = File::create([
      'uri' => $uri,
      'uid' => \Drupal::currentUser()
        ->id(),
    ]);
    $file
      ->setTemporary();
    $file
      ->save();
    \Drupal::request()->files
      ->remove($id);
    return $file
      ->id();
  }
  else {
    return NULL;
  }
}