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