You are here

class FileTestSaveUploadFromForm in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/file/tests/file_test/src/Form/FileTestSaveUploadFromForm.php \Drupal\file_test\Form\FileTestSaveUploadFromForm
  2. 10 core/modules/file/tests/file_test/src/Form/FileTestSaveUploadFromForm.php \Drupal\file_test\Form\FileTestSaveUploadFromForm

File test form class.

Hierarchy

Expanded class hierarchy of FileTestSaveUploadFromForm

1 string reference to 'FileTestSaveUploadFromForm'
file_test.routing.yml in core/modules/file/tests/file_test/file_test.routing.yml
core/modules/file/tests/file_test/file_test.routing.yml

File

core/modules/file/tests/file_test/src/Form/FileTestSaveUploadFromForm.php, line 15

Namespace

Drupal\file_test\Form
View source
class FileTestSaveUploadFromForm extends FormBase {

  /**
   * Stores the state storage service.
   *
   * @var \Drupal\Core\State\StateInterface
   */
  protected $state;

  /**
   * The messenger.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * Constructs a FileTestSaveUploadFromForm object.
   *
   * @param \Drupal\Core\State\StateInterface $state
   *   The state key value store.
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger.
   */
  public function __construct(StateInterface $state, MessengerInterface $messenger) {
    $this->state = $state;
    $this->messenger = $messenger;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('state'), $container
      ->get('messenger'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return '_file_test_save_upload_from_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['file_test_upload'] = [
      '#type' => 'file',
      '#multiple' => TRUE,
      '#title' => $this
        ->t('Upload a file'),
    ];
    $form['file_test_replace'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Replace existing image'),
      '#options' => [
        FileSystemInterface::EXISTS_RENAME => $this
          ->t('Appends number until name is unique'),
        FileSystemInterface::EXISTS_REPLACE => $this
          ->t('Replace the existing file'),
        FileSystemInterface::EXISTS_ERROR => $this
          ->t('Fail with an error'),
      ],
      '#default_value' => FileSystemInterface::EXISTS_RENAME,
    ];
    $form['file_subdir'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Subdirectory for test file'),
      '#default_value' => '',
    ];
    $form['extensions'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Allowed extensions.'),
      '#default_value' => '',
    ];
    $form['allow_all_extensions'] = [
      '#title' => t('Allow all extensions?'),
      '#type' => 'radios',
      '#options' => [
        'false' => 'No',
        'empty_array' => 'Empty array',
        'empty_string' => 'Empty string',
      ],
      '#default_value' => 'false',
    ];
    $form['is_image_file'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Is this an image file?'),
      '#default_value' => TRUE,
    ];
    $form['error_message'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Custom error message.'),
      '#default_value' => '',
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Submit'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

    // Process the upload and perform validation. Note: we're using the
    // form value for the $replace parameter.
    if (!$form_state
      ->isValueEmpty('file_subdir')) {
      $destination = 'temporary://' . $form_state
        ->getValue('file_subdir');
      \Drupal::service('file_system')
        ->prepareDirectory($destination, FileSystemInterface::CREATE_DIRECTORY);
    }
    else {
      $destination = FALSE;
    }

    // Preset custom error message if requested.
    if ($form_state
      ->getValue('error_message')) {
      $this->messenger
        ->addError($form_state
        ->getValue('error_message'));
    }

    // Setup validators.
    $validators = [];
    if ($form_state
      ->getValue('is_image_file')) {
      $validators['file_validate_is_image'] = [];
    }
    $allow = $form_state
      ->getValue('allow_all_extensions');
    if ($allow === 'empty_array') {
      $validators['file_validate_extensions'] = [];
    }
    elseif ($allow === 'empty_string') {
      $validators['file_validate_extensions'] = [
        '',
      ];
    }
    elseif (!$form_state
      ->isValueEmpty('extensions')) {
      $validators['file_validate_extensions'] = [
        $form_state
          ->getValue('extensions'),
      ];
    }

    // The test for \Drupal::service('file_system')->moveUploadedFile()
    // triggering a warning is unavoidable. We're interested in what happens
    // afterwards in _file_save_upload_from_form().
    if ($this->state
      ->get('file_test.disable_error_collection')) {
      define('SIMPLETEST_COLLECT_ERRORS', FALSE);
    }
    $form['file_test_upload']['#upload_validators'] = $validators;
    $form['file_test_upload']['#upload_location'] = $destination;
    $this->messenger
      ->addStatus($this
      ->t('Number of error messages before _file_save_upload_from_form(): @count.', [
      '@count' => count($this->messenger
        ->messagesByType(MessengerInterface::TYPE_ERROR)),
    ]));
    $file = _file_save_upload_from_form($form['file_test_upload'], $form_state, 0, $form_state
      ->getValue('file_test_replace'));
    $this->messenger
      ->addStatus($this
      ->t('Number of error messages after _file_save_upload_from_form(): @count.', [
      '@count' => count($this->messenger
        ->messagesByType(MessengerInterface::TYPE_ERROR)),
    ]));
    if ($file) {
      $form_state
        ->setValue('file_test_upload', $file);
      $this->messenger
        ->addStatus($this
        ->t('File @filepath was uploaded.', [
        '@filepath' => $file
          ->getFileUri(),
      ]));
      $this->messenger
        ->addStatus($this
        ->t('File name is @filename.', [
        '@filename' => $file
          ->getFilename(),
      ]));
      $this->messenger
        ->addStatus($this
        ->t('File MIME type is @mimetype.', [
        '@mimetype' => $file
          ->getMimeType(),
      ]));
      $this->messenger
        ->addStatus($this
        ->t('You WIN!'));
    }
    elseif ($file === FALSE) {
      $this->messenger
        ->addError($this
        ->t('Epic upload FAIL!'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FileTestSaveUploadFromForm::$messenger protected property The messenger. Overrides MessengerTrait::$messenger
FileTestSaveUploadFromForm::$state protected property Stores the state storage service.
FileTestSaveUploadFromForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
FileTestSaveUploadFromForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
FileTestSaveUploadFromForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
FileTestSaveUploadFromForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
FileTestSaveUploadFromForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
FileTestSaveUploadFromForm::__construct public function Constructs a FileTestSaveUploadFromForm object.
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.