c42d9883c62e7143877173b688bc18c523028c34
[yaffs-website] / web / core / modules / comment / src / Tests / CommentTestBase.php
1 <?php
2
3 namespace Drupal\comment\Tests;
4
5 use Drupal\comment\Entity\CommentType;
6 use Drupal\comment\Entity\Comment;
7 use Drupal\comment\CommentInterface;
8 use Drupal\field\Entity\FieldConfig;
9 use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
10 use Drupal\node\Entity\NodeType;
11 use Drupal\simpletest\WebTestBase;
12
13 /**
14  * Provides setup and helper methods for comment tests.
15  */
16 abstract class CommentTestBase extends WebTestBase {
17
18   use CommentTestTrait;
19
20   /**
21    * Modules to install.
22    *
23    * @var array
24    */
25   public static $modules = ['block', 'comment', 'node', 'history', 'field_ui', 'datetime'];
26
27   /**
28    * An administrative user with permission to configure comment settings.
29    *
30    * @var \Drupal\user\UserInterface
31    */
32   protected $adminUser;
33
34   /**
35    * A normal user with permission to post comments.
36    *
37    * @var \Drupal\user\UserInterface
38    */
39   protected $webUser;
40
41   /**
42    * A test node to which comments will be posted.
43    *
44    * @var \Drupal\node\NodeInterface
45    */
46   protected $node;
47
48   protected function setUp() {
49     parent::setUp();
50
51     // Create an article content type only if it does not yet exist, so that
52     // child classes may specify the standard profile.
53     $types = NodeType::loadMultiple();
54     if (empty($types['article'])) {
55       $this->drupalCreateContentType(['type' => 'article', 'name' => t('Article')]);
56     }
57
58     // Create two test users.
59     $this->adminUser = $this->drupalCreateUser([
60       'administer content types',
61       'administer comments',
62       'administer comment types',
63       'administer comment fields',
64       'administer comment display',
65       'skip comment approval',
66       'post comments',
67       'access comments',
68       // Usernames aren't shown in comment edit form autocomplete unless this
69       // permission is granted.
70       'access user profiles',
71       'access content',
72      ]);
73     $this->webUser = $this->drupalCreateUser([
74       'access comments',
75       'post comments',
76       'create article content',
77       'edit own comments',
78       'skip comment approval',
79       'access content',
80     ]);
81
82     // Create comment field on article.
83     $this->addDefaultCommentField('node', 'article');
84
85     // Create a test node authored by the web user.
86     $this->node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1, 'uid' => $this->webUser->id()]);
87     $this->drupalPlaceBlock('local_tasks_block');
88   }
89
90   /**
91    * Posts a comment.
92    *
93    * @param \Drupal\Core\Entity\EntityInterface|null $entity
94    *   Node to post comment on or NULL to post to the previously loaded page.
95    * @param string $comment
96    *   Comment body.
97    * @param string $subject
98    *   Comment subject.
99    * @param string $contact
100    *   Set to NULL for no contact info, TRUE to ignore success checking, and
101    *   array of values to set contact info.
102    * @param string $field_name
103    *   (optional) Field name through which the comment should be posted.
104    *   Defaults to 'comment'.
105    *
106    * @return \Drupal\comment\CommentInterface|null
107    *   The posted comment or NULL when posted comment was not found.
108    */
109   public function postComment($entity, $comment, $subject = '', $contact = NULL, $field_name = 'comment') {
110     $edit = [];
111     $edit['comment_body[0][value]'] = $comment;
112
113     if ($entity !== NULL) {
114       $field = FieldConfig::loadByName($entity->getEntityTypeId(), $entity->bundle(), $field_name);
115     }
116     else {
117       $field = FieldConfig::loadByName('node', 'article', $field_name);
118     }
119     $preview_mode = $field->getSetting('preview');
120
121     // Must get the page before we test for fields.
122     if ($entity !== NULL) {
123       $this->drupalGet('comment/reply/' . $entity->getEntityTypeId() . '/' . $entity->id() . '/' . $field_name);
124     }
125
126     // Determine the visibility of subject form field.
127     if (entity_get_form_display('comment', 'comment', 'default')->getComponent('subject')) {
128       // Subject input allowed.
129       $edit['subject[0][value]'] = $subject;
130     }
131     else {
132       $this->assertNoFieldByName('subject[0][value]', '', 'Subject field not found.');
133     }
134
135     if ($contact !== NULL && is_array($contact)) {
136       $edit += $contact;
137     }
138     switch ($preview_mode) {
139       case DRUPAL_REQUIRED:
140         // Preview required so no save button should be found.
141         $this->assertNoFieldByName('op', t('Save'), 'Save button not found.');
142         $this->drupalPostForm(NULL, $edit, t('Preview'));
143         // Don't break here so that we can test post-preview field presence and
144         // function below.
145       case DRUPAL_OPTIONAL:
146         $this->assertFieldByName('op', t('Preview'), 'Preview button found.');
147         $this->assertFieldByName('op', t('Save'), 'Save button found.');
148         $this->drupalPostForm(NULL, $edit, t('Save'));
149         break;
150
151       case DRUPAL_DISABLED:
152         $this->assertNoFieldByName('op', t('Preview'), 'Preview button not found.');
153         $this->assertFieldByName('op', t('Save'), 'Save button found.');
154         $this->drupalPostForm(NULL, $edit, t('Save'));
155         break;
156     }
157     $match = [];
158     // Get comment ID
159     preg_match('/#comment-([0-9]+)/', $this->getURL(), $match);
160
161     // Get comment.
162     if ($contact !== TRUE) { // If true then attempting to find error message.
163       if ($subject) {
164         $this->assertText($subject, 'Comment subject posted.');
165       }
166       $this->assertText($comment, 'Comment body posted.');
167       $this->assertTrue((!empty($match) && !empty($match[1])), 'Comment id found.');
168     }
169
170     if (isset($match[1])) {
171       \Drupal::entityManager()->getStorage('comment')->resetCache([$match[1]]);
172       return Comment::load($match[1]);
173     }
174   }
175
176   /**
177    * Checks current page for specified comment.
178    *
179    * @param \Drupal\comment\CommentInterface $comment
180    *   The comment object.
181    * @param bool $reply
182    *   Boolean indicating whether the comment is a reply to another comment.
183    *
184    * @return bool
185    *   Boolean indicating whether the comment was found.
186    */
187   public function commentExists(CommentInterface $comment = NULL, $reply = FALSE) {
188     if ($comment) {
189       $comment_element = $this->cssSelect('.comment-wrapper ' . ($reply ? '.indented ' : '') . '#comment-' . $comment->id() . ' ~ article');
190       if (empty($comment_element)) {
191         return FALSE;
192       }
193
194       $comment_title = $comment_element[0]->xpath('div/h3/a');
195       if (empty($comment_title) || ((string)$comment_title[0]) !== $comment->getSubject()) {
196         return FALSE;
197       }
198
199       $comment_body = $comment_element[0]->xpath('div/div/p');
200       if (empty($comment_body) || ((string)$comment_body[0]) !== $comment->comment_body->value) {
201         return FALSE;
202       }
203
204       return TRUE;
205     }
206     else {
207       return FALSE;
208     }
209   }
210
211   /**
212    * Deletes a comment.
213    *
214    * @param \Drupal\comment\CommentInterface $comment
215    *   Comment to delete.
216    */
217   public function deleteComment(CommentInterface $comment) {
218     $this->drupalPostForm('comment/' . $comment->id() . '/delete', [], t('Delete'));
219     $this->assertText(t('The comment and all its replies have been deleted.'), 'Comment deleted.');
220   }
221
222   /**
223    * Sets the value governing whether the subject field should be enabled.
224    *
225    * @param bool $enabled
226    *   Boolean specifying whether the subject field should be enabled.
227    */
228   public function setCommentSubject($enabled) {
229     $form_display = entity_get_form_display('comment', 'comment', 'default');
230     if ($enabled) {
231       $form_display->setComponent('subject', [
232         'type' => 'string_textfield',
233       ]);
234     }
235     else {
236       $form_display->removeComponent('subject');
237     }
238     $form_display->save();
239     // Display status message.
240     $this->pass('Comment subject ' . ($enabled ? 'enabled' : 'disabled') . '.');
241   }
242
243   /**
244    * Sets the value governing the previewing mode for the comment form.
245    *
246    * @param int $mode
247    *   The preview mode: DRUPAL_DISABLED, DRUPAL_OPTIONAL or DRUPAL_REQUIRED.
248    * @param string $field_name
249    *   (optional) Field name through which the comment should be posted.
250    *   Defaults to 'comment'.
251    */
252   public function setCommentPreview($mode, $field_name = 'comment') {
253     switch ($mode) {
254       case DRUPAL_DISABLED:
255         $mode_text = 'disabled';
256         break;
257
258       case DRUPAL_OPTIONAL:
259         $mode_text = 'optional';
260         break;
261
262       case DRUPAL_REQUIRED:
263         $mode_text = 'required';
264         break;
265     }
266     $this->setCommentSettings('preview', $mode, format_string('Comment preview @mode_text.', ['@mode_text' => $mode_text]), $field_name);
267   }
268
269   /**
270    * Sets the value governing whether the comment form is on its own page.
271    *
272    * @param bool $enabled
273    *   TRUE if the comment form should be displayed on the same page as the
274    *   comments; FALSE if it should be displayed on its own page.
275    * @param string $field_name
276    *   (optional) Field name through which the comment should be posted.
277    *   Defaults to 'comment'.
278    */
279   public function setCommentForm($enabled, $field_name = 'comment') {
280     $this->setCommentSettings('form_location', ($enabled ? CommentItemInterface::FORM_BELOW : CommentItemInterface::FORM_SEPARATE_PAGE), 'Comment controls ' . ($enabled ? 'enabled' : 'disabled') . '.', $field_name);
281   }
282
283   /**
284    * Sets the value governing restrictions on anonymous comments.
285    *
286    * @param int $level
287    *   The level of the contact information allowed for anonymous comments:
288    *   - 0: No contact information allowed.
289    *   - 1: Contact information allowed but not required.
290    *   - 2: Contact information required.
291    */
292   public function setCommentAnonymous($level) {
293     $this->setCommentSettings('anonymous', $level, format_string('Anonymous commenting set to level @level.', ['@level' => $level]));
294   }
295
296   /**
297    * Sets the value specifying the default number of comments per page.
298    *
299    * @param int $number
300    *   Comments per page value.
301    * @param string $field_name
302    *   (optional) Field name through which the comment should be posted.
303    *   Defaults to 'comment'.
304    */
305   public function setCommentsPerPage($number, $field_name = 'comment') {
306     $this->setCommentSettings('per_page', $number, format_string('Number of comments per page set to @number.', ['@number' => $number]), $field_name);
307   }
308
309   /**
310    * Sets a comment settings variable for the article content type.
311    *
312    * @param string $name
313    *   Name of variable.
314    * @param string $value
315    *   Value of variable.
316    * @param string $message
317    *   Status message to display.
318    * @param string $field_name
319    *   (optional) Field name through which the comment should be posted.
320    *   Defaults to 'comment'.
321    */
322   public function setCommentSettings($name, $value, $message, $field_name = 'comment') {
323     $field = FieldConfig::loadByName('node', 'article', $field_name);
324     $field->setSetting($name, $value);
325     $field->save();
326     // Display status message.
327     $this->pass($message);
328   }
329
330   /**
331    * Checks whether the commenter's contact information is displayed.
332    *
333    * @return bool
334    *   Contact info is available.
335    */
336   public function commentContactInfoAvailable() {
337     return preg_match('/(input).*?(name="name").*?(input).*?(name="mail").*?(input).*?(name="homepage")/s', $this->getRawContent());
338   }
339
340   /**
341    * Performs the specified operation on the specified comment.
342    *
343    * @param \Drupal\comment\CommentInterface $comment
344    *   Comment to perform operation on.
345    * @param string $operation
346    *   Operation to perform.
347    * @param bool $approval
348    *   Operation is found on approval page.
349    */
350   public function performCommentOperation(CommentInterface $comment, $operation, $approval = FALSE) {
351     $edit = [];
352     $edit['operation'] = $operation;
353     $edit['comments[' . $comment->id() . ']'] = TRUE;
354     $this->drupalPostForm('admin/content/comment' . ($approval ? '/approval' : ''), $edit, t('Update'));
355
356     if ($operation == 'delete') {
357       $this->drupalPostForm(NULL, [], t('Delete comments'));
358       $this->assertRaw(\Drupal::translation()->formatPlural(1, 'Deleted 1 comment.', 'Deleted @count comments.'), format_string('Operation "@operation" was performed on comment.', ['@operation' => $operation]));
359     }
360     else {
361       $this->assertText(t('The update has been performed.'), format_string('Operation "@operation" was performed on comment.', ['@operation' => $operation]));
362     }
363   }
364
365   /**
366    * Gets the comment ID for an unapproved comment.
367    *
368    * @param string $subject
369    *   Comment subject to find.
370    *
371    * @return int
372    *   Comment id.
373    */
374   public function getUnapprovedComment($subject) {
375     $this->drupalGet('admin/content/comment/approval');
376     preg_match('/href="(.*?)#comment-([^"]+)"(.*?)>(' . $subject . ')/', $this->getRawContent(), $match);
377
378     return $match[2];
379   }
380
381   /**
382    * Creates a comment comment type (bundle).
383    *
384    * @param string $label
385    *   The comment type label.
386    *
387    * @return \Drupal\comment\Entity\CommentType
388    *   Created comment type.
389    */
390   protected function createCommentType($label) {
391     $bundle = CommentType::create([
392       'id' => $label,
393       'label' => $label,
394       'description' => '',
395       'target_entity_type_id' => 'node',
396     ]);
397     $bundle->save();
398     return $bundle;
399   }
400
401 }