Updated Drupal to 8.6. This goes with the following updates because it's possible...
[yaffs-website] / web / core / modules / file / src / Tests / FileFieldTestBase.php
1 <?php
2
3 namespace Drupal\file\Tests;
4
5 @trigger_error('The ' . __NAMESPACE__ . '\FileFieldTestBase is deprecated in Drupal 8.5.x and will be removed before Drupal 9.0.0. Instead, use \Drupal\Tests\file\Functional\FileFieldTestBase. See https://www.drupal.org/node/2969361.', E_USER_DEPRECATED);
6
7 use Drupal\field\Entity\FieldStorageConfig;
8 use Drupal\field\Entity\FieldConfig;
9 use Drupal\file\FileInterface;
10 use Drupal\simpletest\WebTestBase;
11 use Drupal\file\Entity\File;
12
13 /**
14  * Provides methods specifically for testing File module's field handling.
15  *
16  * @deprecated Scheduled for removal in Drupal 9.0.0.
17  *   Use \Drupal\Tests\file\Functional\FileFieldTestBase instead.
18  */
19 abstract class FileFieldTestBase extends WebTestBase {
20
21   /**
22   * Modules to enable.
23   *
24   * @var array
25   */
26   public static $modules = ['node', 'file', 'file_module_test', 'field_ui'];
27
28   /**
29    * An user with administration permissions.
30    *
31    * @var \Drupal\user\UserInterface
32    */
33   protected $adminUser;
34
35   protected function setUp() {
36     parent::setUp();
37     $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']);
38     $this->drupalLogin($this->adminUser);
39     $this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']);
40   }
41
42   /**
43    * Retrieves a sample file of the specified type.
44    *
45    * @return \Drupal\file\FileInterface
46    */
47   public function getTestFile($type_name, $size = NULL) {
48     // Get a file to upload.
49     $file = current($this->drupalGetTestFiles($type_name, $size));
50
51     // Add a filesize property to files as would be read by
52     // \Drupal\file\Entity\File::load().
53     $file->filesize = filesize($file->uri);
54
55     return File::create((array) $file);
56   }
57
58   /**
59    * Retrieves the fid of the last inserted file.
60    */
61   public function getLastFileId() {
62     return (int) db_query('SELECT MAX(fid) FROM {file_managed}')->fetchField();
63   }
64
65   /**
66    * Creates a new file field.
67    *
68    * @param string $name
69    *   The name of the new field (all lowercase), exclude the "field_" prefix.
70    * @param string $entity_type
71    *   The entity type.
72    * @param string $bundle
73    *   The bundle that this field will be added to.
74    * @param array $storage_settings
75    *   A list of field storage settings that will be added to the defaults.
76    * @param array $field_settings
77    *   A list of instance settings that will be added to the instance defaults.
78    * @param array $widget_settings
79    *   A list of widget settings that will be added to the widget defaults.
80    */
81   public function createFileField($name, $entity_type, $bundle, $storage_settings = [], $field_settings = [], $widget_settings = []) {
82     $field_storage = FieldStorageConfig::create([
83       'entity_type' => $entity_type,
84       'field_name' => $name,
85       'type' => 'file',
86       'settings' => $storage_settings,
87       'cardinality' => !empty($storage_settings['cardinality']) ? $storage_settings['cardinality'] : 1,
88     ]);
89     $field_storage->save();
90
91     $this->attachFileField($name, $entity_type, $bundle, $field_settings, $widget_settings);
92     return $field_storage;
93   }
94
95   /**
96    * Attaches a file field to an entity.
97    *
98    * @param string $name
99    *   The name of the new field (all lowercase), exclude the "field_" prefix.
100    * @param string $entity_type
101    *   The entity type this field will be added to.
102    * @param string $bundle
103    *   The bundle this field will be added to.
104    * @param array $field_settings
105    *   A list of field settings that will be added to the defaults.
106    * @param array $widget_settings
107    *   A list of widget settings that will be added to the widget defaults.
108    */
109   public function attachFileField($name, $entity_type, $bundle, $field_settings = [], $widget_settings = []) {
110     $field = [
111       'field_name' => $name,
112       'label' => $name,
113       'entity_type' => $entity_type,
114       'bundle' => $bundle,
115       'required' => !empty($field_settings['required']),
116       'settings' => $field_settings,
117     ];
118     FieldConfig::create($field)->save();
119
120     entity_get_form_display($entity_type, $bundle, 'default')
121       ->setComponent($name, [
122         'type' => 'file_generic',
123         'settings' => $widget_settings,
124       ])
125       ->save();
126     // Assign display settings.
127     entity_get_display($entity_type, $bundle, 'default')
128       ->setComponent($name, [
129         'label' => 'hidden',
130         'type' => 'file_default',
131       ])
132       ->save();
133   }
134
135   /**
136    * Updates an existing file field with new settings.
137    */
138   public function updateFileField($name, $type_name, $field_settings = [], $widget_settings = []) {
139     $field = FieldConfig::loadByName('node', $type_name, $name);
140     $field->setSettings(array_merge($field->getSettings(), $field_settings));
141     $field->save();
142
143     entity_get_form_display('node', $type_name, 'default')
144       ->setComponent($name, [
145         'settings' => $widget_settings,
146       ])
147       ->save();
148   }
149
150   /**
151    * Uploads a file to a node.
152    *
153    * @param \Drupal\file\FileInterface $file
154    *   The File to be uploaded.
155    * @param string $field_name
156    *   The name of the field on which the files should be saved.
157    * @param $nid_or_type
158    *   A numeric node id to upload files to an existing node, or a string
159    *   indicating the desired bundle for a new node.
160    * @param bool $new_revision
161    *   The revision number.
162    * @param array $extras
163    *   Additional values when a new node is created.
164    *
165    * @return int
166    *   The node id.
167    */
168   public function uploadNodeFile(FileInterface $file, $field_name, $nid_or_type, $new_revision = TRUE, array $extras = []) {
169     return $this->uploadNodeFiles([$file], $field_name, $nid_or_type, $new_revision, $extras);
170   }
171
172   /**
173    * Uploads multiple files to a node.
174    *
175    * @param \Drupal\file\FileInterface[] $files
176    *   The files to be uploaded.
177    * @param string $field_name
178    *   The name of the field on which the files should be saved.
179    * @param $nid_or_type
180    *   A numeric node id to upload files to an existing node, or a string
181    *   indicating the desired bundle for a new node.
182    * @param bool $new_revision
183    *   The revision number.
184    * @param array $extras
185    *   Additional values when a new node is created.
186    *
187    * @return int
188    *   The node id.
189    */
190   public function uploadNodeFiles(array $files, $field_name, $nid_or_type, $new_revision = TRUE, array $extras = []) {
191     $edit = [
192       'title[0][value]' => $this->randomMachineName(),
193       'revision' => (string) (int) $new_revision,
194     ];
195
196     $node_storage = $this->container->get('entity.manager')->getStorage('node');
197     if (is_numeric($nid_or_type)) {
198       $nid = $nid_or_type;
199       $node_storage->resetCache([$nid]);
200       $node = $node_storage->load($nid);
201     }
202     else {
203       // Add a new node.
204       $extras['type'] = $nid_or_type;
205       $node = $this->drupalCreateNode($extras);
206       $nid = $node->id();
207       // Save at least one revision to better simulate a real site.
208       $node->setNewRevision();
209       $node->save();
210       $node_storage->resetCache([$nid]);
211       $node = $node_storage->load($nid);
212       $this->assertNotEqual($nid, $node->getRevisionId(), 'Node revision exists.');
213     }
214
215     // Attach files to the node.
216     $field_storage = FieldStorageConfig::loadByName('node', $field_name);
217     // File input name depends on number of files already uploaded.
218     $field_num = count($node->{$field_name});
219     $name = 'files[' . $field_name . "_$field_num]";
220     if ($field_storage->getCardinality() != 1) {
221       $name .= '[]';
222     }
223     foreach ($files as $file) {
224       $file_path = $this->container->get('file_system')->realpath($file->getFileUri());
225       if (count($files) == 1) {
226         $edit[$name] = $file_path;
227       }
228       else {
229         $edit[$name][] = $file_path;
230       }
231     }
232     $this->drupalPostForm("node/$nid/edit", $edit, t('Save'));
233
234     return $nid;
235   }
236
237   /**
238    * Removes a file from a node.
239    *
240    * Note that if replacing a file, it must first be removed then added again.
241    */
242   public function removeNodeFile($nid, $new_revision = TRUE) {
243     $edit = [
244       'revision' => (string) (int) $new_revision,
245     ];
246
247     $this->drupalPostForm('node/' . $nid . '/edit', [], t('Remove'));
248     $this->drupalPostForm(NULL, $edit, t('Save'));
249   }
250
251   /**
252    * Replaces a file within a node.
253    */
254   public function replaceNodeFile($file, $field_name, $nid, $new_revision = TRUE) {
255     $edit = [
256       'files[' . $field_name . '_0]' => \Drupal::service('file_system')->realpath($file->getFileUri()),
257       'revision' => (string) (int) $new_revision,
258     ];
259
260     $this->drupalPostForm('node/' . $nid . '/edit', [], t('Remove'));
261     $this->drupalPostForm(NULL, $edit, t('Save'));
262   }
263
264   /**
265    * Asserts that a file exists physically on disk.
266    */
267   public function assertFileExists($file, $message = NULL) {
268     $message = isset($message) ? $message : format_string('File %file exists on the disk.', ['%file' => $file->getFileUri()]);
269     $this->assertTrue(is_file($file->getFileUri()), $message);
270   }
271
272   /**
273    * Asserts that a file exists in the database.
274    */
275   public function assertFileEntryExists($file, $message = NULL) {
276     $this->container->get('entity.manager')->getStorage('file')->resetCache();
277     $db_file = File::load($file->id());
278     $message = isset($message) ? $message : format_string('File %file exists in database at the correct path.', ['%file' => $file->getFileUri()]);
279     $this->assertEqual($db_file->getFileUri(), $file->getFileUri(), $message);
280   }
281
282   /**
283    * Asserts that a file does not exist on disk.
284    */
285   public function assertFileNotExists($file, $message = NULL) {
286     $message = isset($message) ? $message : format_string('File %file exists on the disk.', ['%file' => $file->getFileUri()]);
287     $this->assertFalse(is_file($file->getFileUri()), $message);
288   }
289
290   /**
291    * Asserts that a file does not exist in the database.
292    */
293   public function assertFileEntryNotExists($file, $message) {
294     $this->container->get('entity.manager')->getStorage('file')->resetCache();
295     $message = isset($message) ? $message : format_string('File %file exists in database at the correct path.', ['%file' => $file->getFileUri()]);
296     $this->assertFalse(File::load($file->id()), $message);
297   }
298
299   /**
300    * Asserts that a file's status is set to permanent in the database.
301    */
302   public function assertFileIsPermanent(FileInterface $file, $message = NULL) {
303     $message = isset($message) ? $message : format_string('File %file is permanent.', ['%file' => $file->getFileUri()]);
304     $this->assertTrue($file->isPermanent(), $message);
305   }
306
307 }