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