FileTestSaveUploadFromForm.php 5.88 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\file_test\Form;

5
use Drupal\Core\File\FileSystemInterface;
6 7
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
8
use Drupal\Core\Messenger\MessengerInterface;
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
use Drupal\Core\State\StateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * File test form class.
 */
class FileTestSaveUploadFromForm extends FormBase {

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

24 25 26 27 28 29 30
  /**
   * The messenger.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

31 32 33 34 35
  /**
   * Constructs a FileTestSaveUploadFromForm object.
   *
   * @param \Drupal\Core\State\StateInterface $state
   *   The state key value store.
36 37
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger.
38
   */
39
  public function __construct(StateInterface $state, MessengerInterface $messenger) {
40
    $this->state = $state;
41
    $this->messenger = $messenger;
42 43 44 45 46 47 48
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
49 50
      $container->get('state'),
      $container->get('messenger')
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
    );
  }

  /**
   * {@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' => [
74 75 76
        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'),
77
      ],
78
      '#default_value' => FileSystemInterface::EXISTS_RENAME,
79 80 81 82 83 84 85 86 87 88 89 90 91 92
    ];
    $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'] = [
93 94 95 96 97 98 99 100
      '#title' => t('Allow all extensions?'),
      '#type' => 'radios',
      '#options' => [
        'false' => 'No',
        'empty_array' => 'Empty array',
        'empty_string' => 'Empty string',
      ],
      '#default_value' => 'false',
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
    ];

    $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');
130
      \Drupal::service('file_system')->prepareDirectory($destination, FileSystemInterface::CREATE_DIRECTORY);
131 132 133 134 135 136 137
    }
    else {
      $destination = FALSE;
    }

    // Preset custom error message if requested.
    if ($form_state->getValue('error_message')) {
138
      $this->messenger->addError($form_state->getValue('error_message'));
139 140 141 142 143 144 145 146
    }

    // Setup validators.
    $validators = [];
    if ($form_state->getValue('is_image_file')) {
      $validators['file_validate_is_image'] = [];
    }

147 148
    $allow = $form_state->getValue('allow_all_extensions');
    if ($allow === 'empty_array') {
149 150
      $validators['file_validate_extensions'] = [];
    }
151 152 153
    elseif ($allow === 'empty_string') {
      $validators['file_validate_extensions'] = [''];
    }
154 155 156 157
    elseif (!$form_state->isValueEmpty('extensions')) {
      $validators['file_validate_extensions'] = [$form_state->getValue('extensions')];
    }

158 159 160
    // 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().
161 162 163 164 165 166 167
    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;

168
    $this->messenger->addStatus($this->t('Number of error messages before _file_save_upload_from_form(): @count.', ['@count' => count($this->messenger->messagesByType(MessengerInterface::TYPE_ERROR))]));
169
    $file = _file_save_upload_from_form($form['file_test_upload'], $form_state, 0, $form_state->getValue('file_test_replace'));
170
    $this->messenger->addStatus($this->t('Number of error messages after _file_save_upload_from_form(): @count.', ['@count' => count($this->messenger->messagesByType(MessengerInterface::TYPE_ERROR))]));
171 172 173

    if ($file) {
      $form_state->setValue('file_test_upload', $file);
174 175 176 177
      $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!'));
178 179
    }
    elseif ($file === FALSE) {
180
      $this->messenger->addError($this->t('Epic upload FAIL!'));
181 182 183 184 185 186 187 188 189
    }
  }

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

}