d061c00f1ebced89f2874ae7accebc9ae5e9fe08
[yaffs-website] / web / core / modules / text / src / Tests / TextFieldTest.php
1 <?php
2
3 namespace Drupal\text\Tests;
4
5 use Drupal\Component\Utility\Unicode;
6 use Drupal\entity_test\Entity\EntityTest;
7 use Drupal\field\Entity\FieldConfig;
8 use Drupal\field\Tests\String\StringFieldTest;
9 use Drupal\field\Entity\FieldStorageConfig;
10 use Drupal\filter\Entity\FilterFormat;
11
12 /**
13  * Tests the creation of text fields.
14  *
15  * @group text
16  */
17 class TextFieldTest extends StringFieldTest {
18
19   /**
20    * A user with relevant administrative privileges.
21    *
22    * @var \Drupal\user\UserInterface
23    */
24   protected $adminUser;
25
26   protected function setUp() {
27     parent::setUp();
28
29     $this->adminUser = $this->drupalCreateUser(['administer filters']);
30   }
31
32   // Test fields.
33
34   /**
35    * Test text field validation.
36    */
37   public function testTextFieldValidation() {
38     // Create a field with settings to validate.
39     $max_length = 3;
40     $field_name = Unicode::strtolower($this->randomMachineName());
41     $field_storage = FieldStorageConfig::create([
42       'field_name' => $field_name,
43       'entity_type' => 'entity_test',
44       'type' => 'text',
45       'settings' => [
46         'max_length' => $max_length,
47       ]
48     ]);
49     $field_storage->save();
50     FieldConfig::create([
51       'field_storage' => $field_storage,
52       'bundle' => 'entity_test',
53     ])->save();
54
55     // Test validation with valid and invalid values.
56     $entity = EntityTest::create();
57     for ($i = 0; $i <= $max_length + 2; $i++) {
58       $entity->{$field_name}->value = str_repeat('x', $i);
59       $violations = $entity->{$field_name}->validate();
60       if ($i <= $max_length) {
61         $this->assertEqual(count($violations), 0, "Length $i does not cause validation error when max_length is $max_length");
62       }
63       else {
64         $this->assertEqual(count($violations), 1, "Length $i causes validation error when max_length is $max_length");
65       }
66     }
67   }
68
69   /**
70    * Test required long text with file upload.
71    */
72   public function testRequiredLongTextWithFileUpload() {
73     // Create a text field.
74     $text_field_name = 'text_long';
75     $field_storage = FieldStorageConfig::create([
76       'field_name' => $text_field_name,
77       'entity_type' => 'entity_test',
78       'type' => 'text_with_summary',
79     ]);
80     $field_storage->save();
81     FieldConfig::create([
82       'field_storage' => $field_storage,
83       'bundle' => 'entity_test',
84       'label' => $this->randomMachineName() . '_label',
85       'required' => TRUE,
86     ])->save();
87
88     // Create a file field.
89     $file_field_name = 'file_field';
90     $field_storage = FieldStorageConfig::create([
91       'field_name' => $file_field_name,
92       'entity_type' => 'entity_test',
93       'type' => 'file'
94     ]);
95     $field_storage->save();
96     FieldConfig::create([
97       'field_storage' => $field_storage,
98       'bundle' => 'entity_test',
99       'label' => $this->randomMachineName() . '_label',
100     ])->save();
101
102     entity_get_form_display('entity_test', 'entity_test', 'default')
103       ->setComponent($text_field_name, [
104         'type' => 'text_textarea_with_summary',
105       ])
106       ->setComponent($file_field_name, [
107         'type' => 'file_generic',
108       ])
109       ->save();
110     entity_get_display('entity_test', 'entity_test', 'full')
111       ->setComponent($text_field_name)
112       ->setComponent($file_field_name)
113       ->save();
114
115     $test_file = current($this->drupalGetTestFiles('text'));
116     $edit['files[file_field_0]'] = drupal_realpath($test_file->uri);
117     $this->drupalPostForm('entity_test/add', $edit, 'Upload');
118     $this->assertResponse(200);
119     $edit = [
120       'text_long[0][value]' => 'Long text'
121     ];
122     $this->drupalPostForm(NULL, $edit, 'Save');
123     $this->assertResponse(200);
124     $this->drupalGet('entity_test/1');
125     $this->assertText('Long text');
126   }
127
128   /**
129    * Test widgets.
130    */
131   public function testTextfieldWidgets() {
132     $this->_testTextfieldWidgets('text', 'text_textfield');
133     $this->_testTextfieldWidgets('text_long', 'text_textarea');
134   }
135
136   /**
137    * Test widgets + 'formatted_text' setting.
138    */
139   public function testTextfieldWidgetsFormatted() {
140     $this->_testTextfieldWidgetsFormatted('text', 'text_textfield');
141     $this->_testTextfieldWidgetsFormatted('text_long', 'text_textarea');
142   }
143
144   /**
145    * Helper function for testTextfieldWidgetsFormatted().
146    */
147   public function _testTextfieldWidgetsFormatted($field_type, $widget_type) {
148     /** @var \Drupal\Core\Render\RendererInterface $renderer */
149     $renderer = $this->container->get('renderer');
150
151     // Create a field.
152     $field_name = Unicode::strtolower($this->randomMachineName());
153     $field_storage = FieldStorageConfig::create([
154       'field_name' => $field_name,
155       'entity_type' => 'entity_test',
156       'type' => $field_type
157     ]);
158     $field_storage->save();
159     FieldConfig::create([
160       'field_storage' => $field_storage,
161       'bundle' => 'entity_test',
162       'label' => $this->randomMachineName() . '_label',
163     ])->save();
164     entity_get_form_display('entity_test', 'entity_test', 'default')
165       ->setComponent($field_name, [
166         'type' => $widget_type,
167       ])
168       ->save();
169     entity_get_display('entity_test', 'entity_test', 'full')
170       ->setComponent($field_name)
171       ->save();
172
173     // Disable all text formats besides the plain text fallback format.
174     $this->drupalLogin($this->adminUser);
175     foreach (filter_formats() as $format) {
176       if (!$format->isFallbackFormat()) {
177         $this->drupalPostForm('admin/config/content/formats/manage/' . $format->id() . '/disable', [], t('Disable'));
178       }
179     }
180     $this->drupalLogin($this->webUser);
181
182     // Display the creation form. Since the user only has access to one format,
183     // no format selector will be displayed.
184     $this->drupalGet('entity_test/add');
185     $this->assertFieldByName("{$field_name}[0][value]", '', 'Widget is displayed');
186     $this->assertNoFieldByName("{$field_name}[0][format]", '', 'Format selector is not displayed');
187
188     // Submit with data that should be filtered.
189     $value = '<em>' . $this->randomMachineName() . '</em>';
190     $edit = [
191       "{$field_name}[0][value]" => $value,
192     ];
193     $this->drupalPostForm(NULL, $edit, t('Save'));
194     preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
195     $id = $match[1];
196     $this->assertText(t('entity_test @id has been created.', ['@id' => $id]), 'Entity was created');
197
198     // Display the entity.
199     $entity = EntityTest::load($id);
200     $display = entity_get_display($entity->getEntityTypeId(), $entity->bundle(), 'full');
201     $content = $display->build($entity);
202     $this->setRawContent($renderer->renderRoot($content));
203     $this->assertNoRaw($value, 'HTML tags are not displayed.');
204     $this->assertEscaped($value, 'Escaped HTML is displayed correctly.');
205
206     // Create a new text format that does not escape HTML, and grant the user
207     // access to it.
208     $this->drupalLogin($this->adminUser);
209     $edit = [
210       'format' => Unicode::strtolower($this->randomMachineName()),
211       'name' => $this->randomMachineName(),
212     ];
213     $this->drupalPostForm('admin/config/content/formats/add', $edit, t('Save configuration'));
214     filter_formats_reset();
215     $format = FilterFormat::load($edit['format']);
216     $format_id = $format->id();
217     $permission = $format->getPermissionName();
218     $roles = $this->webUser->getRoles();
219     $rid = $roles[0];
220     user_role_grant_permissions($rid, [$permission]);
221     $this->drupalLogin($this->webUser);
222
223     // Display edition form.
224     // We should now have a 'text format' selector.
225     $this->drupalGet('entity_test/manage/' . $id . '/edit');
226     $this->assertFieldByName("{$field_name}[0][value]", NULL, 'Widget is displayed');
227     $this->assertFieldByName("{$field_name}[0][format]", NULL, 'Format selector is displayed');
228
229     // Edit and change the text format to the new one that was created.
230     $edit = [
231       "{$field_name}[0][format]" => $format_id,
232     ];
233     $this->drupalPostForm(NULL, $edit, t('Save'));
234     $this->assertText(t('entity_test @id has been updated.', ['@id' => $id]), 'Entity was updated');
235
236     // Display the entity.
237     $this->container->get('entity.manager')->getStorage('entity_test')->resetCache([$id]);
238     $entity = EntityTest::load($id);
239     $display = entity_get_display($entity->getEntityTypeId(), $entity->bundle(), 'full');
240     $content = $display->build($entity);
241     $this->setRawContent($renderer->renderRoot($content));
242     $this->assertRaw($value, 'Value is displayed unfiltered');
243   }
244
245 }