FileFieldTestBase.php 7.65 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\Tests\file\Functional;

5
use Drupal\Component\Render\FormattableMarkup;
6 7 8 9 10
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Entity\FieldConfig;
use Drupal\file\FileInterface;
use Drupal\Tests\BrowserTestBase;
use Drupal\file\Entity\File;
11
use Drupal\Tests\TestFileCreationTrait;
12 13 14 15 16 17

/**
 * Provides methods specifically for testing File module's field handling.
 */
abstract class FileFieldTestBase extends BrowserTestBase {

18
  use FileFieldCreationTrait;
19 20 21
  use TestFileCreationTrait {
    getTestFiles as drupalGetTestFiles;
  }
22

23
  /**
24 25 26
   * {@inheritdoc}
   */
  protected static $modules = ['node', 'file', 'file_module_test', 'field_ui'];
27 28

  /**
29
   * A user with administration permissions.
30 31 32 33 34
   *
   * @var \Drupal\user\UserInterface
   */
  protected $adminUser;

35 36 37
  /**
   * {@inheritdoc}
   */
38 39
  protected function setUp() {
    parent::setUp();
40 41 42 43 44 45 46 47 48 49 50 51
    $this->adminUser = $this->drupalCreateUser([
      'access content',
      'access administration pages',
      'administer site configuration',
      'administer users',
      'administer permissions',
      'administer content types',
      'administer node fields',
      'administer node display',
      'administer nodes',
      'bypass node access',
    ]);
52
    $this->drupalLogin($this->adminUser);
53
    $this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']);
54 55 56 57 58 59
  }

  /**
   * Retrieves a sample file of the specified type.
   *
   * @return \Drupal\file\FileInterface
60
   *   The new unsaved file entity.
61
   */
62
  public function getTestFile($type_name, $size = NULL) {
63 64 65 66 67 68 69 70 71 72 73 74 75
    // Get a file to upload.
    $file = current($this->drupalGetTestFiles($type_name, $size));

    // Add a filesize property to files as would be read by
    // \Drupal\file\Entity\File::load().
    $file->filesize = filesize($file->uri);

    return File::create((array) $file);
  }

  /**
   * Retrieves the fid of the last inserted file.
   */
76
  public function getLastFileId() {
77 78 79 80
    return (int) \Drupal::entityQueryAggregate('file')
      ->accessCheck(FALSE)
      ->aggregate('fid', 'max')
      ->execute()[0]['fid_max'];
81 82 83 84 85
  }

  /**
   * Updates an existing file field with new settings.
   */
86
  public function updateFileField($name, $type_name, $field_settings = [], $widget_settings = []) {
87 88 89 90
    $field = FieldConfig::loadByName('node', $type_name, $name);
    $field->setSettings(array_merge($field->getSettings(), $field_settings));
    $field->save();

91
    \Drupal::service('entity_display.repository')->getFormDisplay('node', $type_name)
92
      ->setComponent($name, [
93
        'settings' => $widget_settings,
94
      ])
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
      ->save();
  }

  /**
   * Uploads a file to a node.
   *
   * @param \Drupal\file\FileInterface $file
   *   The File to be uploaded.
   * @param string $field_name
   *   The name of the field on which the files should be saved.
   * @param $nid_or_type
   *   A numeric node id to upload files to an existing node, or a string
   *   indicating the desired bundle for a new node.
   * @param bool $new_revision
   *   The revision number.
   * @param array $extras
   *   Additional values when a new node is created.
   *
   * @return int
   *   The node id.
   */
116
  public function uploadNodeFile(FileInterface $file, $field_name, $nid_or_type, $new_revision = TRUE, array $extras = []) {
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
    return $this->uploadNodeFiles([$file], $field_name, $nid_or_type, $new_revision, $extras);
  }

  /**
   * Uploads multiple files to a node.
   *
   * @param \Drupal\file\FileInterface[] $files
   *   The files to be uploaded.
   * @param string $field_name
   *   The name of the field on which the files should be saved.
   * @param $nid_or_type
   *   A numeric node id to upload files to an existing node, or a string
   *   indicating the desired bundle for a new node.
   * @param bool $new_revision
   *   The revision number.
   * @param array $extras
   *   Additional values when a new node is created.
   *
   * @return int
   *   The node id.
   */
138
  public function uploadNodeFiles(array $files, $field_name, $nid_or_type, $new_revision = TRUE, array $extras = []) {
139
    $edit = [
140 141
      'title[0][value]' => $this->randomMachineName(),
      'revision' => (string) (int) $new_revision,
142
    ];
143

144
    $node_storage = $this->container->get('entity_type.manager')->getStorage('node');
145 146
    if (is_numeric($nid_or_type)) {
      $nid = $nid_or_type;
147
      $node_storage->resetCache([$nid]);
148 149 150 151 152 153 154 155 156 157
      $node = $node_storage->load($nid);
    }
    else {
      // Add a new node.
      $extras['type'] = $nid_or_type;
      $node = $this->drupalCreateNode($extras);
      $nid = $node->id();
      // Save at least one revision to better simulate a real site.
      $node->setNewRevision();
      $node->save();
158
      $node_storage->resetCache([$nid]);
159
      $node = $node_storage->load($nid);
160
      $this->assertNotEquals($nid, $node->getRevisionId(), 'Node revision exists.');
161
    }
162 163
    $this->drupalGet("node/$nid/edit");
    $page = $this->getSession()->getPage();
164 165 166 167 168

    // Attach files to the node.
    $field_storage = FieldStorageConfig::loadByName('node', $field_name);
    // File input name depends on number of files already uploaded.
    $field_num = count($node->{$field_name});
169 170
    foreach ($files as $i => $file) {
      $delta = $field_num + $i;
171
      $file_path = $this->container->get('file_system')->realpath($file->getFileUri());
172 173 174 175
      $name = 'files[' . $field_name . '_' . $delta . ']';
      if ($field_storage->getCardinality() != 1) {
        $name .= '[]';
      }
176 177 178 179
      if (count($files) == 1) {
        $edit[$name] = $file_path;
      }
      else {
180
        $page->attachFileToField($name, $file_path);
181
        $this->submitForm([], 'Upload');
182 183
      }
    }
184

185
    $this->submitForm($edit, 'Save');
186 187 188 189 190 191 192 193 194

    return $nid;
  }

  /**
   * Removes a file from a node.
   *
   * Note that if replacing a file, it must first be removed then added again.
   */
195
  public function removeNodeFile($nid, $new_revision = TRUE) {
196
    $edit = [
197
      'revision' => (string) (int) $new_revision,
198
    ];
199

200
    $this->drupalPostForm('node/' . $nid . '/edit', [], 'Remove');
201
    $this->submitForm($edit, 'Save');
202 203 204 205 206
  }

  /**
   * Replaces a file within a node.
   */
207
  public function replaceNodeFile($file, $field_name, $nid, $new_revision = TRUE) {
208
    $edit = [
209
      'files[' . $field_name . '_0]' => \Drupal::service('file_system')->realpath($file->getFileUri()),
210
      'revision' => (string) (int) $new_revision,
211
    ];
212

213
    $this->drupalPostForm('node/' . $nid . '/edit', [], 'Remove');
214
    $this->submitForm($edit, 'Save');
215 216 217 218 219
  }

  /**
   * Asserts that a file exists in the database.
   */
220
  public function assertFileEntryExists($file, $message = NULL) {
221
    $this->container->get('entity_type.manager')->getStorage('file')->resetCache();
222
    $db_file = File::load($file->id());
223
    $message = isset($message) ? $message : new FormattableMarkup('File %file exists in database at the correct path.', ['%file' => $file->getFileUri()]);
224
    $this->assertEqual($file->getFileUri(), $db_file->getFileUri(), $message);
225 226 227 228 229
  }

  /**
   * Asserts that a file does not exist in the database.
   */
230
  public function assertFileEntryNotExists($file, $message) {
231
    $this->container->get('entity_type.manager')->getStorage('file')->resetCache();
232
    $message = isset($message) ? $message : new FormattableMarkup('File %file exists in database at the correct path.', ['%file' => $file->getFileUri()]);
233
    $this->assertNull(File::load($file->id()), $message);
234 235 236 237 238
  }

  /**
   * Asserts that a file's status is set to permanent in the database.
   */
239
  public function assertFileIsPermanent(FileInterface $file, $message = NULL) {
240
    $message = isset($message) ? $message : new FormattableMarkup('File %file is permanent.', ['%file' => $file->getFileUri()]);
241 242 243 244
    $this->assertTrue($file->isPermanent(), $message);
  }

}