3 namespace Drupal\image\Tests;
5 use Drupal\Core\Field\FieldStorageDefinitionInterface;
6 use Drupal\field\Entity\FieldStorageConfig;
7 use Drupal\user\RoleInterface;
8 use Drupal\image\Entity\ImageStyle;
11 * Tests the display of image fields.
15 class ImageFieldDisplayTest extends ImageFieldTestBase {
17 protected $dumpHeaders = TRUE;
24 public static $modules = ['field_ui'];
27 * Test image formatters on node display for public files.
29 public function testImageFieldFormattersPublic() {
30 $this->_testImageFieldFormatters('public');
34 * Test image formatters on node display for private files.
36 public function testImageFieldFormattersPrivate() {
37 // Remove access content permission from anonymous users.
38 user_role_change_permissions(RoleInterface::ANONYMOUS_ID, ['access content' => FALSE]);
39 $this->_testImageFieldFormatters('private');
43 * Test image formatters on node display.
45 public function _testImageFieldFormatters($scheme) {
46 /** @var \Drupal\Core\Render\RendererInterface $renderer */
47 $renderer = $this->container->get('renderer');
48 $node_storage = $this->container->get('entity.manager')->getStorage('node');
49 $field_name = strtolower($this->randomMachineName());
50 $field_settings = ['alt_field_required' => 0];
51 $instance = $this->createImageField($field_name, 'article', ['uri_scheme' => $scheme], $field_settings);
53 // Go to manage display page.
54 $this->drupalGet("admin/structure/types/manage/article/display");
56 // Test for existence of link to image styles configuration.
57 $this->drupalPostAjaxForm(NULL, [], "{$field_name}_settings_edit");
58 $this->assertLinkByHref(\Drupal::url('entity.image_style.collection'), 0, 'Link to image styles configuration is found');
60 // Remove 'administer image styles' permission from testing admin user.
61 $admin_user_roles = $this->adminUser->getRoles(TRUE);
62 user_role_change_permissions(reset($admin_user_roles), ['administer image styles' => FALSE]);
64 // Go to manage display page again.
65 $this->drupalGet("admin/structure/types/manage/article/display");
67 // Test for absence of link to image styles configuration.
68 $this->drupalPostAjaxForm(NULL, [], "{$field_name}_settings_edit");
69 $this->assertNoLinkByHref(\Drupal::url('entity.image_style.collection'), 'Link to image styles configuration is absent when permissions are insufficient');
71 // Restore 'administer image styles' permission to testing admin user
72 user_role_change_permissions(reset($admin_user_roles), ['administer image styles' => TRUE]);
74 // Create a new node with an image attached.
75 $test_image = current($this->drupalGetTestFiles('image'));
77 // Ensure that preview works.
78 $this->previewNodeImage($test_image, $field_name, 'article');
80 // After previewing, make the alt field required. It cannot be required
81 // during preview because the form validation will fail.
82 $instance->setSetting('alt_field_required', 1);
85 // Create alt text for the image.
86 $alt = $this->randomMachineName();
89 $nid = $this->uploadNodeImage($test_image, $field_name, 'article', $alt);
90 $node_storage->resetCache([$nid]);
91 $node = $node_storage->load($nid);
93 // Test that the default formatter is being used.
94 $file = $node->{$field_name}->entity;
95 $image_uri = $file->getFileUri();
103 $default_output = str_replace("\n", NULL, $renderer->renderRoot($image));
104 $this->assertRaw($default_output, 'Default formatter displaying correctly on full node view.');
106 // Test the image linked to file formatter.
109 'settings' => ['image_link' => 'file'],
111 $display = entity_get_display('node', $node->getType(), 'default');
112 $display->setComponent($field_name, $display_options)
117 '#uri' => $image_uri,
122 $default_output = '<a href="' . file_create_url($image_uri) . '">' . $renderer->renderRoot($image) . '</a>';
123 $this->drupalGet('node/' . $nid);
124 $this->assertCacheTag($file->getCacheTags()[0]);
125 // @todo Remove in https://www.drupal.org/node/2646744.
126 $this->assertCacheContext('url.site');
127 $cache_tags_header = $this->drupalGetHeader('X-Drupal-Cache-Tags');
128 $this->assertTrue(!preg_match('/ image_style\:/', $cache_tags_header), 'No image style cache tag found.');
129 $this->assertRaw($default_output, 'Image linked to file formatter displaying correctly on full node view.');
130 // Verify that the image can be downloaded.
131 $this->assertEqual(file_get_contents($test_image->uri), $this->drupalGet(file_create_url($image_uri)), 'File was downloaded successfully.');
132 if ($scheme == 'private') {
133 // Only verify HTTP headers when using private scheme and the headers are
135 $this->assertEqual($this->drupalGetHeader('Content-Type'), 'image/png', 'Content-Type header was sent.');
136 $this->assertTrue(strstr($this->drupalGetHeader('Cache-Control'), 'private') !== FALSE, 'Cache-Control header was sent.');
138 // Log out and try to access the file.
139 $this->drupalLogout();
140 $this->drupalGet(file_create_url($image_uri));
141 $this->assertResponse('403', 'Access denied to original image as anonymous user.');
144 $this->drupalLogin($this->adminUser);
147 // Test the image linked to content formatter.
148 $display_options['settings']['image_link'] = 'content';
149 $display->setComponent($field_name, $display_options)
153 '#uri' => $image_uri,
157 $this->drupalGet('node/' . $nid);
158 $this->assertCacheTag($file->getCacheTags()[0]);
159 $cache_tags_header = $this->drupalGetHeader('X-Drupal-Cache-Tags');
160 $this->assertTrue(!preg_match('/ image_style\:/', $cache_tags_header), 'No image style cache tag found.');
161 $elements = $this->xpath(
162 '//a[@href=:path]/img[@src=:url and @alt=:alt and @width=:width and @height=:height]',
164 ':path' => $node->url(),
165 ':url' => file_url_transform_relative(file_create_url($image['#uri'])),
166 ':width' => $image['#width'],
167 ':height' => $image['#height'],
171 $this->assertEqual(count($elements), 1, 'Image linked to content formatter displaying correctly on full node view.');
173 // Test the image style 'thumbnail' formatter.
174 $display_options['settings']['image_link'] = '';
175 $display_options['settings']['image_style'] = 'thumbnail';
176 $display->setComponent($field_name, $display_options)
179 // Ensure the derivative image is generated so we do not have to deal with
180 // image style callback paths.
181 $this->drupalGet(ImageStyle::load('thumbnail')->buildUrl($image_uri));
183 '#theme' => 'image_style',
184 '#uri' => $image_uri,
187 '#style_name' => 'thumbnail',
190 $default_output = $renderer->renderRoot($image_style);
191 $this->drupalGet('node/' . $nid);
192 $image_style = ImageStyle::load('thumbnail');
193 $this->assertCacheTag($image_style->getCacheTags()[0]);
194 $this->assertRaw($default_output, 'Image style thumbnail formatter displaying correctly on full node view.');
196 if ($scheme == 'private') {
197 // Log out and try to access the file.
198 $this->drupalLogout();
199 $this->drupalGet(ImageStyle::load('thumbnail')->buildUrl($image_uri));
200 $this->assertResponse('403', 'Access denied to image style thumbnail as anonymous user.');
203 // Test the image URL formatter without an image style.
205 'type' => 'image_url',
206 'settings' => ['image_style' => ''],
208 $expected_url = file_url_transform_relative(file_create_url($image_uri));
209 $this->assertEqual($expected_url, $node->{$field_name}->view($display_options)[0]['#markup']);
211 // Test the image URL formatter with an image style.
212 $display_options['settings']['image_style'] = 'thumbnail';
213 $expected_url = file_url_transform_relative(ImageStyle::load('thumbnail')->buildUrl($image_uri));
214 $this->assertEqual($expected_url, $node->{$field_name}->view($display_options)[0]['#markup']);
218 * Tests for image field settings.
220 public function testImageFieldSettings() {
221 /** @var \Drupal\Core\Render\RendererInterface $renderer */
222 $renderer = $this->container->get('renderer');
223 $node_storage = $this->container->get('entity.manager')->getStorage('node');
224 $test_image = current($this->drupalGetTestFiles('image'));
225 list(, $test_image_extension) = explode('.', $test_image->filename);
226 $field_name = strtolower($this->randomMachineName());
229 'file_extensions' => $test_image_extension,
230 'max_filesize' => '50 KB',
231 'max_resolution' => '100x100',
232 'min_resolution' => '10x10',
236 'preview_image_style' => 'medium',
238 $field = $this->createImageField($field_name, 'article', [], $field_settings, $widget_settings);
240 // Verify that the min/max resolution set on the field are properly
241 // extracted, and displayed, on the image field's configuration form.
242 $this->drupalGet('admin/structure/types/manage/article/fields/' . $field->id());
243 $this->assertFieldByName('settings[max_resolution][x]', '100', 'Expected max resolution X value of 100.');
244 $this->assertFieldByName('settings[max_resolution][y]', '100', 'Expected max resolution Y value of 100.');
245 $this->assertFieldByName('settings[min_resolution][x]', '10', 'Expected min resolution X value of 10.');
246 $this->assertFieldByName('settings[min_resolution][y]', '10', 'Expected min resolution Y value of 10.');
248 $this->drupalGet('node/add/article');
249 $this->assertText(t('50 KB limit.'), 'Image widget max file size is displayed on article form.');
250 $this->assertText(t('Allowed types: @extensions.', ['@extensions' => $test_image_extension]), 'Image widget allowed file types displayed on article form.');
251 $this->assertText(t('Images must be larger than 10x10 pixels. Images larger than 100x100 pixels will be resized.'), 'Image widget allowed resolution displayed on article form.');
253 // We have to create the article first and then edit it because the alt
254 // and title fields do not display until the image has been attached.
256 // Create alt text for the image.
257 $alt = $this->randomMachineName();
259 $nid = $this->uploadNodeImage($test_image, $field_name, 'article', $alt);
260 $this->drupalGet('node/' . $nid . '/edit');
261 $this->assertFieldByName($field_name . '[0][alt]', '', 'Alt field displayed on article form.');
262 $this->assertFieldByName($field_name . '[0][title]', '', 'Title field displayed on article form.');
263 // Verify that the attached image is being previewed using the 'medium'
265 $node_storage->resetCache([$nid]);
266 $node = $node_storage->load($nid);
267 $file = $node->{$field_name}->entity;
269 $url = file_url_transform_relative(file_create_url(ImageStyle::load('medium')->buildUrl($file->getFileUri())));
270 $this->assertTrue($this->cssSelect('img[width=40][height=20][class=image-style-medium][src="' . $url . '"]'));
272 // Add alt/title fields to the image and verify that they are displayed.
275 '#uri' => $file->getFileUri(),
277 '#title' => $this->randomMachineName(),
282 $field_name . '[0][alt]' => $image['#alt'],
283 $field_name . '[0][title]' => $image['#title'],
285 $this->drupalPostForm('node/' . $nid . '/edit', $edit, t('Save and keep published'));
286 $default_output = str_replace("\n", NULL, $renderer->renderRoot($image));
287 $this->assertRaw($default_output, 'Image displayed using user supplied alt and title attributes.');
289 // Verify that alt/title longer than allowed results in a validation error.
292 $field_name . '[0][alt]' => $this->randomMachineName($test_size),
293 $field_name . '[0][title]' => $this->randomMachineName($test_size),
295 $this->drupalPostForm('node/' . $nid . '/edit', $edit, t('Save and keep published'));
296 $schema = $field->getFieldStorageDefinition()->getSchema();
297 $this->assertRaw(t('Alternative text cannot be longer than %max characters but is currently %length characters long.', [
298 '%max' => $schema['columns']['alt']['length'],
299 '%length' => $test_size,
301 $this->assertRaw(t('Title cannot be longer than %max characters but is currently %length characters long.', [
302 '%max' => $schema['columns']['title']['length'],
303 '%length' => $test_size,
306 // Set cardinality to unlimited and add upload a second image.
307 // The image widget is extending on the file widget, but the image field
308 // type does not have the 'display_field' setting which is expected by
309 // the file widget. This resulted in notices before when cardinality is not
310 // 1, so we need to make sure the file widget prevents these notices by
311 // providing all settings, even if they are not used.
312 // @see FileWidget::formMultipleElements().
313 $this->drupalPostForm('admin/structure/types/manage/article/fields/node.article.' . $field_name . '/storage', ['cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED], t('Save field settings'));
315 'files[' . $field_name . '_1][]' => drupal_realpath($test_image->uri),
317 $this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save and keep published'));
318 // Add the required alt text.
319 $this->drupalPostForm(NULL, [$field_name . '[1][alt]' => $alt], t('Save and keep published'));
320 $this->assertText(format_string('Article @title has been updated.', ['@title' => $node->getTitle()]));
322 // Assert ImageWidget::process() calls FieldWidget::process().
323 $this->drupalGet('node/' . $node->id() . '/edit');
325 'files[' . $field_name . '_2][]' => drupal_realpath($test_image->uri),
327 $this->drupalPostAjaxForm(NULL, $edit, $field_name . '_2_upload_button');
328 $this->assertNoRaw('<input multiple type="file" id="edit-' . strtr($field_name, '_', '-') . '-2-upload" name="files[' . $field_name . '_2][]" size="22" class="js-form-file form-file">');
329 $this->assertRaw('<input multiple type="file" id="edit-' . strtr($field_name, '_', '-') . '-3-upload" name="files[' . $field_name . '_3][]" size="22" class="js-form-file form-file">');
333 * Test use of a default image with an image field.
335 public function testImageFieldDefaultImage() {
336 /** @var \Drupal\Core\Render\RendererInterface $renderer */
337 $renderer = $this->container->get('renderer');
339 $node_storage = $this->container->get('entity.manager')->getStorage('node');
340 // Create a new image field.
341 $field_name = strtolower($this->randomMachineName());
342 $this->createImageField($field_name, 'article');
344 // Create a new node, with no images and verify that no images are
346 $node = $this->drupalCreateNode(['type' => 'article']);
347 $this->drupalGet('node/' . $node->id());
348 // Verify that no image is displayed on the page by checking for the class
349 // that would be used on the image field.
350 $this->assertNoPattern('<div class="(.*?)field--name-' . strtr($field_name, '_', '-') . '(.*?)">', 'No image displayed when no image is attached and no default image specified.');
351 $cache_tags_header = $this->drupalGetHeader('X-Drupal-Cache-Tags');
352 $this->assertTrue(!preg_match('/ image_style\:/', $cache_tags_header), 'No image style cache tag found.');
354 // Add a default image to the public image field.
355 $images = $this->drupalGetTestFiles('image');
356 $alt = $this->randomString(512);
357 $title = $this->randomString(1024);
359 // Get the path of the 'image-test.png' file.
360 'files[settings_default_image_uuid]' => drupal_realpath($images[0]->uri),
361 'settings[default_image][alt]' => $alt,
362 'settings[default_image][title]' => $title,
364 $this->drupalPostForm("admin/structure/types/manage/article/fields/node.article.$field_name/storage", $edit, t('Save field settings'));
365 // Clear field definition cache so the new default image is detected.
366 \Drupal::entityManager()->clearCachedFieldDefinitions();
367 $field_storage = FieldStorageConfig::loadByName('node', $field_name);
368 $default_image = $field_storage->getSetting('default_image');
369 $file = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']);
370 $this->assertTrue($file->isPermanent(), 'The default image status is permanent.');
373 '#uri' => $file->getFileUri(),
379 $default_output = str_replace("\n", NULL, $renderer->renderRoot($image));
380 $this->drupalGet('node/' . $node->id());
381 $this->assertCacheTag($file->getCacheTags()[0]);
382 $cache_tags_header = $this->drupalGetHeader('X-Drupal-Cache-Tags');
383 $this->assertTrue(!preg_match('/ image_style\:/', $cache_tags_header), 'No image style cache tag found.');
384 $this->assertRaw($default_output, 'Default image displayed when no user supplied image is present.');
386 // Create a node with an image attached and ensure that the default image
389 // Create alt text for the image.
390 $alt = $this->randomMachineName();
392 // Upload the 'image-test.gif' file.
393 $nid = $this->uploadNodeImage($images[2], $field_name, 'article', $alt);
394 $node_storage->resetCache([$nid]);
395 $node = $node_storage->load($nid);
396 $file = $node->{$field_name}->entity;
399 '#uri' => $file->getFileUri(),
404 $image_output = str_replace("\n", NULL, $renderer->renderRoot($image));
405 $this->drupalGet('node/' . $nid);
406 $this->assertCacheTag($file->getCacheTags()[0]);
407 $cache_tags_header = $this->drupalGetHeader('X-Drupal-Cache-Tags');
408 $this->assertTrue(!preg_match('/ image_style\:/', $cache_tags_header), 'No image style cache tag found.');
409 $this->assertNoRaw($default_output, 'Default image is not displayed when user supplied image is present.');
410 $this->assertRaw($image_output, 'User supplied image is displayed.');
412 // Remove default image from the field and make sure it is no longer used.
414 'settings[default_image][uuid][fids]' => 0,
416 $this->drupalPostForm("admin/structure/types/manage/article/fields/node.article.$field_name/storage", $edit, t('Save field settings'));
417 // Clear field definition cache so the new default image is detected.
418 \Drupal::entityManager()->clearCachedFieldDefinitions();
419 $field_storage = FieldStorageConfig::loadByName('node', $field_name);
420 $default_image = $field_storage->getSetting('default_image');
421 $this->assertFalse($default_image['uuid'], 'Default image removed from field.');
422 // Create an image field that uses the private:// scheme and test that the
423 // default image works as expected.
424 $private_field_name = strtolower($this->randomMachineName());
425 $this->createImageField($private_field_name, 'article', ['uri_scheme' => 'private']);
426 // Add a default image to the new field.
428 // Get the path of the 'image-test.gif' file.
429 'files[settings_default_image_uuid]' => drupal_realpath($images[2]->uri),
430 'settings[default_image][alt]' => $alt,
431 'settings[default_image][title]' => $title,
433 $this->drupalPostForm('admin/structure/types/manage/article/fields/node.article.' . $private_field_name . '/storage', $edit, t('Save field settings'));
434 // Clear field definition cache so the new default image is detected.
435 \Drupal::entityManager()->clearCachedFieldDefinitions();
437 $private_field_storage = FieldStorageConfig::loadByName('node', $private_field_name);
438 $default_image = $private_field_storage->getSetting('default_image');
439 $file = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']);
440 $this->assertEqual('private', file_uri_scheme($file->getFileUri()), 'Default image uses private:// scheme.');
441 $this->assertTrue($file->isPermanent(), 'The default image status is permanent.');
442 // Create a new node with no image attached and ensure that default private
443 // image is displayed.
444 $node = $this->drupalCreateNode(['type' => 'article']);
447 '#uri' => $file->getFileUri(),
453 $default_output = str_replace("\n", NULL, $renderer->renderRoot($image));
454 $this->drupalGet('node/' . $node->id());
455 $this->assertCacheTag($file->getCacheTags()[0]);
456 $cache_tags_header = $this->drupalGetHeader('X-Drupal-Cache-Tags');
457 $this->assertTrue(!preg_match('/ image_style\:/', $cache_tags_header), 'No image style cache tag found.');
458 $this->assertRaw($default_output, 'Default private image displayed when no user supplied image is present.');