You are here

public function WebformManagedFileBase::getTestValues in Webform 6.x

Same name and namespace in other branches
  1. 8.5 src/Plugin/WebformElement/WebformManagedFileBase.php \Drupal\webform\Plugin\WebformElement\WebformManagedFileBase::getTestValues()

Get test values for an element.

Parameters

array $element: An element.

\Drupal\webform\WebformInterface $webform: A webform.

array $options: Options used to generate a test value.

Return value

mixed A test value for an element.

Overrides WebformElementBase::getTestValues

File

src/Plugin/WebformElement/WebformManagedFileBase.php, line 530

Class

WebformManagedFileBase
Provides a base class webform 'managed_file' elements.

Namespace

Drupal\webform\Plugin\WebformElement

Code

public function getTestValues(array $element, WebformInterface $webform, array $options = []) {
  if ($this
    ->isDisabled()) {
    return NULL;
  }

  // Get element or composite key.
  if (isset($element['#webform_key'])) {
    $key = $element['#webform_key'];
  }
  elseif (isset($element['#webform_composite_key'])) {
    $key = $element['#webform_composite_key'];
  }
  else {
    return NULL;
  }

  // Append delta to key.
  // @see \Drupal\webform\Plugin\WebformElement\WebformCompositeBase::getTestValues
  if (isset($options['delta'])) {
    $key .= '_' . $options['delta'];
  }
  $file_extensions = explode(' ', $this
    ->getFileExtensions($element));
  $file_extension = $file_extensions[array_rand($file_extensions)];
  $upload_location = $this
    ->getUploadLocation($element, $webform);
  $file_destination = $upload_location . '/' . $key . '.' . $file_extension;

  // Look for an existing temp files that have not been uploaded.
  $fids = $this
    ->getFileStorage()
    ->getQuery()
    ->condition('status', 0)
    ->condition('uid', $this->currentUser
    ->id())
    ->condition('uri', $upload_location . '/' . $key . '.%', 'LIKE')
    ->execute();
  if ($fids) {
    return reset($fids);
  }

  // Copy sample file or generate a new temp file that can be uploaded.
  $sample_file = drupal_get_path('module', 'webform') . '/tests/files/sample.' . $file_extension;
  if (file_exists($sample_file)) {
    $file_uri = $this->fileSystem
      ->copy($sample_file, $file_destination);
  }
  else {
    $file_uri = $this->fileSystem
      ->saveData('{empty}', $file_destination);
  }
  $file = $this
    ->getFileStorage()
    ->create([
    'uri' => $file_uri,
    'uid' => $this->currentUser
      ->id(),
  ]);
  $file
    ->save();
  $fid = $file
    ->id();
  return [
    $fid,
  ];
}