Completed
Push — master ( 8c4363...20d778 )
by Daniel
51s queued 13s
created

UserDefinedFormTest::testDuplicatingForm()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 33
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 20
nc 1
nop 0
dl 0
loc 33
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
namespace SilverStripe\UserForms\Tests\Model;
4
5
use SilverStripe\Control\Controller;
6
use SilverStripe\Control\Email\Email;
7
use SilverStripe\Core\Convert;
8
use SilverStripe\Dev\FunctionalTest;
9
use SilverStripe\Forms\DropdownField;
10
use SilverStripe\Forms\FieldList;
11
use SilverStripe\Forms\Form;
12
use SilverStripe\Forms\GridField\GridField;
13
use SilverStripe\Forms\GridField\GridFieldDataColumns;
14
use SilverStripe\ORM\DB;
15
use SilverStripe\UserForms\Extension\UserFormFieldEditorExtension;
16
use SilverStripe\UserForms\Extension\UserFormValidator;
17
use SilverStripe\UserForms\Model\EditableCustomRule;
18
use SilverStripe\UserForms\Model\EditableFormField;
19
use SilverStripe\UserForms\Model\EditableFormField\EditableDropdown;
20
use SilverStripe\UserForms\Model\EditableFormField\EditableEmailField;
21
use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroup;
22
use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroupEnd;
23
use SilverStripe\UserForms\Model\Recipient\EmailRecipient;
24
use SilverStripe\UserForms\Model\UserDefinedForm;
25
use SilverStripe\Versioned\Versioned;
26
27
/**
28
 * @package userforms
29
 */
30
class UserDefinedFormTest extends FunctionalTest
31
{
32
    protected static $fixture_file = '../UserFormsTest.yml';
33
34
    protected static $required_extensions = [
35
        UserDefinedForm::class => [UserFormFieldEditorExtension::class],
36
    ];
37
38
    protected function setUp()
39
    {
40
        parent::setUp();
41
        Email::config()->update('admin_email', '[email protected]');
42
    }
43
44
    public function testRollbackToVersion()
45
    {
46
        $this->markTestSkipped(
47
            'UserDefinedForm::rollback() has not been implemented completely'
48
        );
49
50
        // @todo
51
        $this->logInWithPermission('ADMIN');
52
        $form = $this->objFromFixture(UserDefinedForm::class, 'basic-form-page');
53
54
        $form->SubmitButtonText = 'Button Text';
55
        $form->write();
56
        $form->publishRecursive();
57
        $origVersion = $form->Version;
58
59
        $form->SubmitButtonText = 'Updated Button Text';
60
        $form->write();
61
        $form->publishRecursive();
62
63
        // check published site
64
        $updated = Versioned::get_one_by_stage(UserDefinedForm::class, 'Stage', "\"UserDefinedForm\".\"ID\" = $form->ID");
65
        $this->assertEquals($updated->SubmitButtonText, 'Updated Button Text');
66
67
        $form->doRollbackTo($origVersion);
68
69
        $orignal = Versioned::get_one_by_stage(UserDefinedForm::class, 'Stage', "\"UserDefinedForm\".\"ID\" = $form->ID");
70
        $this->assertEquals($orignal->SubmitButtonText, 'Button Text');
71
    }
72
73
    public function testGetCMSFields()
74
    {
75
        $this->logInWithPermission('ADMIN');
76
        $form = $this->objFromFixture(UserDefinedForm::class, 'basic-form-page');
77
78
        $fields = $form->getCMSFields();
79
80
        $this->assertNotNull($fields->dataFieldByName('Fields'));
81
        $this->assertNotNull($fields->dataFieldByName('EmailRecipients'));
82
        $this->assertNotNull($fields->dataFieldByName('Submissions'));
83
        $this->assertNotNull($fields->dataFieldByName('OnCompleteMessage'));
84
    }
85
86
87
    public function testGetCMSFieldsShowInSummary()
88
    {
89
        $this->logInWithPermission('ADMIN');
90
        $form = $this->objFromFixture(UserDefinedForm::class, 'summary-rules-form');
91
92
        $fields = $form->getCMSFields();
93
94
        $this->assertInstanceOf(GridField::class, $fields->dataFieldByName('Submissions'));
95
96
        $submissionsgrid = $fields->dataFieldByName('Submissions');
97
        $gridFieldDataColumns = $submissionsgrid->getConfig()->getComponentByType(GridFieldDataColumns::class);
98
99
        $summaryFields = $gridFieldDataColumns->getDisplayFields($submissionsgrid);
100
101
        $this->assertContains('SummaryShow', array_keys($summaryFields), 'Summary field not showing displayed field');
102
        $this->assertNotContains('SummaryHide', array_keys($summaryFields), 'Summary field showing displayed field');
103
    }
104
105
106
    public function testEmailRecipientPopup()
107
    {
108
        $this->logInWithPermission('ADMIN');
109
110
        $form = $this->objFromFixture(UserDefinedForm::class, 'basic-form-page');
111
112
        $popup = new EmailRecipient();
113
        $popup->FormID = $form->ID;
0 ignored issues
show
Bug Best Practice introduced by
The property FormID does not exist on SilverStripe\UserForms\M...ecipient\EmailRecipient. Since you implemented __set, consider adding a @property annotation.
Loading history...
114
        $popup->FormClass = UserDefinedForm::class;
0 ignored issues
show
Bug Best Practice introduced by
The property FormClass does not exist on SilverStripe\UserForms\M...ecipient\EmailRecipient. Since you implemented __set, consider adding a @property annotation.
Loading history...
115
116
        $fields = $popup->getCMSFields();
117
118
        $this->assertNotNull($fields->dataFieldByName('EmailSubject'));
119
        $this->assertNotNull($fields->dataFieldByName('EmailFrom'));
120
        $this->assertNotNull($fields->dataFieldByName('EmailAddress'));
121
        $this->assertNotNull($fields->dataFieldByName('HideFormData'));
122
        $this->assertNotNull($fields->dataFieldByName('SendPlain'));
123
        $this->assertNotNull($fields->dataFieldByName('EmailBody'));
124
125
        // add an email field, it should now add a or from X address picker
126
        $email = $this->objFromFixture(EditableEmailField::class, 'email-field');
127
        $form->Fields()->add($email);
128
129
        $popup->write();
130
131
        $fields = $popup->getCMSFields();
132
        $this->assertThat($fields->dataFieldByName('SendEmailToFieldID'), $this->isInstanceOf(DropdownField::class));
133
134
        // if the front end has checkboxes or dropdown they can select from that can also be used to send things
135
        $dropdown = $this->objFromFixture(EditableDropdown::class, 'department-dropdown');
136
        $form->Fields()->add($dropdown);
137
138
        $fields = $popup->getCMSFields();
139
        $this->assertTrue($fields->dataFieldByName('SendEmailToFieldID') !== null);
140
141
        $popup->delete();
142
    }
143
144
    public function testGetEmailBodyContent()
145
    {
146
        $recipient = new EmailRecipient();
147
148
        $emailBody = 'not html';
149
        $emailBodyHtml = '<p>html</p>';
150
151
        $recipient->EmailBody = $emailBody;
0 ignored issues
show
Bug Best Practice introduced by
The property EmailBody does not exist on SilverStripe\UserForms\M...ecipient\EmailRecipient. Since you implemented __set, consider adding a @property annotation.
Loading history...
152
        $recipient->EmailBodyHtml = $emailBodyHtml;
0 ignored issues
show
Bug Best Practice introduced by
The property EmailBodyHtml does not exist on SilverStripe\UserForms\M...ecipient\EmailRecipient. Since you implemented __set, consider adding a @property annotation.
Loading history...
153
        $recipient->write();
154
155
        $this->assertEquals($recipient->SendPlain, 0);
0 ignored issues
show
Bug Best Practice introduced by
The property SendPlain does not exist on SilverStripe\UserForms\M...ecipient\EmailRecipient. Since you implemented __get, consider adding a @property annotation.
Loading history...
156
        $this->assertEquals($recipient->getEmailBodyContent(), $emailBodyHtml);
157
158
        $recipient->SendPlain = 1;
0 ignored issues
show
Bug Best Practice introduced by
The property SendPlain does not exist on SilverStripe\UserForms\M...ecipient\EmailRecipient. Since you implemented __set, consider adding a @property annotation.
Loading history...
159
        $recipient->write();
160
161
        $this->assertEquals($recipient->getEmailBodyContent(), $emailBody);
162
163
        $recipient->delete();
164
    }
165
166
    public function testGetEmailTemplateDropdownValues()
167
    {
168
        $page = $this->objFromFixture(UserDefinedForm::class, 'basic-form-page');
169
        $recipient = new EmailRecipient();
170
        $recipient->FormID = $page->ID;
0 ignored issues
show
Bug Best Practice introduced by
The property FormID does not exist on SilverStripe\UserForms\M...ecipient\EmailRecipient. Since you implemented __set, consider adding a @property annotation.
Loading history...
171
        $recipient->FormClass = UserDefinedForm::class;
0 ignored issues
show
Bug Best Practice introduced by
The property FormClass does not exist on SilverStripe\UserForms\M...ecipient\EmailRecipient. Since you implemented __set, consider adding a @property annotation.
Loading history...
172
173
        $result = $recipient->getEmailTemplateDropdownValues();
174
175
        // Installation path can be as a project when testing in Travis, so check partial match
176
        $this->assertContains('email' . DIRECTORY_SEPARATOR . 'SubmittedFormEmail', key($result));
177
        $this->assertSame('SubmittedFormEmail', current($result));
178
    }
179
180
    public function testEmailTemplateExists()
181
    {
182
        $page = $this->objFromFixture(UserDefinedForm::class, 'basic-form-page');
183
        $recipient = new EmailRecipient();
184
        $recipient->FormID = $page->ID;
0 ignored issues
show
Bug Best Practice introduced by
The property FormID does not exist on SilverStripe\UserForms\M...ecipient\EmailRecipient. Since you implemented __set, consider adding a @property annotation.
Loading history...
185
        $recipient->FormClass = UserDefinedForm::class;
0 ignored issues
show
Bug Best Practice introduced by
The property FormClass does not exist on SilverStripe\UserForms\M...ecipient\EmailRecipient. Since you implemented __set, consider adding a @property annotation.
Loading history...
186
187
        // Set the default template
188
        $recipient->EmailTemplate = current(array_keys($recipient->getEmailTemplateDropdownValues()));
0 ignored issues
show
Bug Best Practice introduced by
The property EmailTemplate does not exist on SilverStripe\UserForms\M...ecipient\EmailRecipient. Since you implemented __set, consider adding a @property annotation.
Loading history...
189
        $recipient->write();
190
191
        // The default template exists
192
        $this->assertTrue($recipient->emailTemplateExists());
193
194
        // A made up template doesn't exists
195
        $this->assertFalse($recipient->emailTemplateExists('MyTemplateThatsNotThere'));
196
197
        $recipient->delete();
198
    }
199
200
    public function testCanEditAndDeleteRecipient()
201
    {
202
        $form = $this->objFromFixture(UserDefinedForm::class, 'basic-form-page');
203
204
        $this->logInWithPermission('ADMIN');
205
        foreach ($form->EmailRecipients() as $recipient) {
206
            $this->assertTrue($recipient->canEdit());
207
            $this->assertTrue($recipient->canDelete());
208
        }
209
210
        $this->logOut();
211
        $this->logInWithPermission('SITETREE_VIEW_ALL');
212
213
        foreach ($form->EmailRecipients() as $recipient) {
214
            $this->assertFalse($recipient->canEdit());
215
            $this->assertFalse($recipient->canDelete());
216
        }
217
    }
218
219
    public function testPublishing()
220
    {
221
        $this->logInWithPermission('ADMIN');
222
223
        $form = $this->objFromFixture(UserDefinedForm::class, 'basic-form-page');
224
        $form->write();
225
226
        $form->publishRecursive();
227
228
        $live = Versioned::get_one_by_stage(UserDefinedForm::class, 'Live', "\"UserDefinedForm_Live\".\"ID\" = $form->ID");
229
230
        $this->assertNotNull($live);
231
        $this->assertEquals(2, $live->Fields()->Count()); // one page and one field
232
233
        $dropdown = $this->objFromFixture(EditableDropdown::class, 'basic-dropdown');
234
        $form->Fields()->add($dropdown);
235
236
        $stage = Versioned::get_one_by_stage(UserDefinedForm::class, 'Stage', "\"UserDefinedForm\".\"ID\" = $form->ID");
237
        $this->assertEquals(3, $stage->Fields()->Count());
238
239
        // should not have published the dropdown
240
        $liveDropdown = Versioned::get_one_by_stage(EditableFormField::class, 'Live', "\"EditableFormField_Live\".\"ID\" = $dropdown->ID");
241
        $this->assertNull($liveDropdown);
242
243
        // when publishing it should have added it
244
        $form->publishRecursive();
245
246
        $live = Versioned::get_one_by_stage(UserDefinedForm::class, 'Live', "\"UserDefinedForm_Live\".\"ID\" = $form->ID");
247
        $this->assertEquals(3, $live->Fields()->Count());
248
249
        // edit the title
250
        $text = $form->Fields()->limit(1, 1)->First();
251
        $text->Title = 'Edited title';
252
        $text->write();
253
254
        $liveText = Versioned::get_one_by_stage(EditableFormField::class, 'Live', "\"EditableFormField_Live\".\"ID\" = $text->ID");
255
        $this->assertFalse($liveText->Title == $text->Title);
256
257
        $form->publishRecursive();
258
259
        $liveText = Versioned::get_one_by_stage(EditableFormField::class, 'Live', "\"EditableFormField_Live\".\"ID\" = $text->ID");
260
        $this->assertTrue($liveText->Title == $text->Title);
261
262
        // Add a display rule to the dropdown
263
        $displayRule = new EditableCustomRule();
264
        $displayRule->ParentID = $dropdown->ID;
0 ignored issues
show
Bug Best Practice introduced by
The property ParentID does not exist on SilverStripe\UserForms\Model\EditableCustomRule. Since you implemented __set, consider adding a @property annotation.
Loading history...
265
        $displayRule->ConditionFieldID = $text->ID;
0 ignored issues
show
Bug Best Practice introduced by
The property ConditionFieldID does not exist on SilverStripe\UserForms\Model\EditableCustomRule. Since you implemented __set, consider adding a @property annotation.
Loading history...
266
        $displayRule->write();
267
        $ruleID = $displayRule->ID;
268
269
        // Not live
270
        $liveRule = Versioned::get_one_by_stage(EditableCustomRule::class, 'Live', "\"EditableCustomRule_Live\".\"ID\" = $ruleID");
271
        $this->assertEmpty($liveRule);
272
273
        // Publish form, it's now live
274
        $form->publishRecursive();
275
        $liveRule = Versioned::get_one_by_stage(EditableCustomRule::class, 'Live', "\"EditableCustomRule_Live\".\"ID\" = $ruleID");
276
        $this->assertNotEmpty($liveRule);
277
278
        // Remove rule
279
        $displayRule->delete();
280
281
        // Live rule still exists
282
        $liveRule = Versioned::get_one_by_stage(EditableCustomRule::class, 'Live', "\"EditableCustomRule_Live\".\"ID\" = $ruleID");
283
        $this->assertNotEmpty($liveRule);
284
285
        // Publish form, it should remove this rule
286
        /**
287
         * @todo Currently failing, revisit once https://github.com/silverstripe/silverstripe-versioned/issues/34 is resolved
288
         */
289
        // $form->publishRecursive();
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
290
        // $liveRule = Versioned::get_one_by_stage(EditableCustomRule::class, 'Live', "\"EditableCustomRule_Live\".\"ID\" = $ruleID");
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
291
        // $this->assertEmpty($liveRule);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
292
    }
293
294
    public function testUnpublishing()
295
    {
296
        $this->logInWithPermission('ADMIN');
297
        $form = $this->objFromFixture(UserDefinedForm::class, 'basic-form-page');
298
        $form->write();
299
        $this->assertEquals(0, DB::query("SELECT COUNT(*) FROM \"EditableFormField_Live\"")->value());
300
        $form->publishRecursive();
301
302
        // assert that it exists and has a field
303
        $live = Versioned::get_one_by_stage(UserDefinedForm::class, 'Live', "\"UserDefinedForm_Live\".\"ID\" = $form->ID");
304
305
        $this->assertTrue(isset($live));
306
        $this->assertEquals(2, DB::query("SELECT COUNT(*) FROM \"EditableFormField_Live\"")->value());
307
308
        // unpublish
309
        $form->doUnpublish();
310
311
        $this->assertNull(Versioned::get_one_by_stage(UserDefinedForm::class, 'Live', "\"UserDefinedForm_Live\".\"ID\" = $form->ID"));
312
        $this->assertEquals(0, DB::query("SELECT COUNT(*) FROM \"EditableFormField_Live\"")->value());
313
    }
314
315
    public function testDoRevertToLive()
316
    {
317
        $this->logInWithPermission('ADMIN');
318
        $form = $this->objFromFixture(UserDefinedForm::class, 'basic-form-page');
319
        $field = $form->Fields()->First();
320
321
        $field->Title = 'Title';
322
        $field->write();
323
324
        $form->publishRecursive();
325
326
        $field->Title = 'Edited title';
327
        $field->write();
328
329
        // check that the published version is not updated
330
        $live = Versioned::get_one_by_stage(EditableFormField::class, 'Live', "\"EditableFormField_Live\".\"ID\" = $field->ID");
331
        $this->assertInstanceOf(EditableFormField::class, $live);
332
        $this->assertEquals('Title', $live->Title);
333
334
        // revert back to the live data
335
        $form->doRevertToLive();
336
        $form->flushCache();
337
338
        $check = Versioned::get_one_by_stage(EditableFormField::class, 'Stage', "\"EditableFormField\".\"ID\" = $field->ID");
339
340
        $this->assertEquals('Title', $check->Title);
341
    }
342
343
    public function testDuplicatingForm()
344
    {
345
        $this->logInWithPermission('ADMIN');
346
        $form = $this->objFromFixture(UserDefinedForm::class, 'basic-form-page');
347
348
        $duplicate = $form->duplicate();
349
350
        $this->assertEquals($form->Fields()->Count(), $duplicate->Fields()->Count());
351
352
        // can't compare object since the dates/ids change
353
        $this->assertEquals($form->Fields()->First()->Title, $duplicate->Fields()->First()->Title);
354
355
        // Test duplicate with group
356
        $form2 = $this->objFromFixture(UserDefinedForm::class, 'page-with-group');
357
        $form2Validator = new UserFormValidator();
358
        $form2Validator->setForm(new Form(new Controller(), Form::class, new FieldList(), new FieldList()));
359
        $this->assertTrue($form2Validator->php($form2->toMap()));
360
361
        // Check field groups exist
362
        $form2GroupStart = $form2->Fields()->filter('ClassName', EditableFieldGroup::class)->first();
363
        $form2GroupEnd = $form2->Fields()->filter('ClassName', EditableFieldGroupEnd::class)->first();
364
        $this->assertEquals($form2GroupEnd->ID, $form2GroupStart->EndID);
365
366
        // Duplicate this
367
        $form3 = $form2->duplicate();
368
        $form3Validator = new UserFormValidator();
369
        $form3Validator->setForm(new Form(new Controller(), Form::class, new FieldList(), new FieldList()));
370
        $this->assertTrue($form3Validator->php($form3->toMap()));
371
        // Check field groups exist
372
        $form3GroupStart = $form3->Fields()->filter('ClassName', EditableFieldGroup::class)->first();
373
        $form3GroupEnd = $form3->Fields()->filter('ClassName', EditableFieldGroupEnd::class)->first();
374
        $this->assertEquals($form3GroupEnd->ID, $form3GroupStart->EndID);
375
        $this->assertNotEquals($form2GroupEnd->ID, $form3GroupStart->EndID);
376
    }
377
378
    public function testDuplicateFormDuplicatesRecursively()
379
    {
380
        $this->logInWithPermission('ADMIN');
381
        /** @var UserDefinedForm $form */
382
        $form = $this->objFromFixture(UserDefinedForm::class, 'form-with-multioptions');
383
384
        $this->assertGreaterThanOrEqual(1, $form->Fields()->count(), 'Fixtured page has a field');
385
        $this->assertCount(
386
            2,
387
            $form->Fields()->Last()->Options(),
388
            'Fixtured multiple option field has two options'
389
        );
390
391
        $newForm = $form->duplicate();
392
        $this->assertEquals(
393
            $form->Fields()->count(),
394
            $newForm->Fields()->count(),
395
            'Duplicated page has same number of fields'
396
        );
397
        $this->assertEquals(
398
            $form->Fields()->Last()->Options()->count(),
0 ignored issues
show
Bug introduced by
The method count() does not exist on Traversable. It seems like you code against a sub-type of Traversable such as DOMNodeList or Threaded or SimpleXMLElement or DOMNamedNodeMap or Thread or Worker or Stackable or MongoGridFSCursor or ResourceBundle or SilverStripe\ORM\SS_List or SilverStripe\View\ViewableData or PHPUnit_Framework_TestSuite or SilverStripe\ORM\Map or Symfony\Component\Finder\Finder or SebastianBergmann\CodeCoverage\Node\Directory or ArrayObject or SplDoublyLinkedList or HttpMessage or HttpRequestPool or PHP_CodeSniffer\Files\FileList or SplFixedArray or SplObjectStorage or SQLiteResult or Imagick or SplPriorityQueue or MongoCursor or SplHeap or MongoGridFSCursor or CachingIterator or PHP_Token_Stream or Phar or ArrayIterator or GlobIterator or Phar or Phar or RecursiveCachingIterator or RecursiveArrayIterator or SimpleXMLIterator or Phar. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

398
            $form->Fields()->Last()->Options()->/** @scrutinizer ignore-call */ count(),
Loading history...
399
            $newForm->Fields()->Last()->Options()->count(),
400
            'Duplicated dropdown field from duplicated form has duplicated options'
401
        );
402
    }
403
404
    public function testFormOptions()
405
    {
406
        $this->logInWithPermission('ADMIN');
407
        $form = $this->objFromFixture(UserDefinedForm::class, 'basic-form-page');
408
409
        $fields = $form->getFormOptions();
410
        $submit = $fields->fieldByName('SubmitButtonText');
411
        $reset = $fields->fieldByName('ShowClearButton');
412
413
        $this->assertEquals($submit->Title(), 'Text on submit button:');
414
        $this->assertEquals($reset->Title(), 'Show Clear Form Button');
415
    }
416
417
    public function testEmailRecipientFilters()
418
    {
419
        /** @var UserDefinedForm $form */
420
        $form = $this->objFromFixture(UserDefinedForm::class, 'filtered-form-page');
421
422
        // Check unfiltered recipients
423
        $result0 = $form
424
            ->EmailRecipients()
425
            ->sort('EmailAddress')
426
            ->column('EmailAddress');
427
        $this->assertEquals(
428
            [
429
                '[email protected]',
430
                '[email protected]',
431
                '[email protected]'
432
            ],
433
            $result0
434
        );
435
436
        // check filters based on given data
437
        $result1 = $form->FilteredEmailRecipients(
438
            [
439
                'your-name' => 'Value',
440
                'address' => '',
441
                'street' => 'Anything',
442
                'city' => 'Matches Not Equals',
443
                'colours' => ['Red'] // matches 2
444
            ],
445
            null
446
        )
447
            ->sort('EmailAddress')
448
            ->column('EmailAddress');
449
        $this->assertEquals(
450
            [
451
                '[email protected]',
452
                '[email protected]'
453
            ],
454
            $result1
455
        );
456
457
        // Check all positive matches
458
        $result2 = $form->FilteredEmailRecipients(
459
            [
460
                'your-name' => '',
461
                'address' => 'Anything',
462
                'street' => 'Matches Equals',
463
                'city' => 'Anything',
464
                'colours' => ['Red', 'Blue'] // matches 2
465
            ],
466
            null
467
        )
468
            ->sort('EmailAddress')
469
            ->column('EmailAddress');
470
        $this->assertEquals(
471
            [
472
                '[email protected]',
473
                '[email protected]',
474
                '[email protected]'
475
            ],
476
            $result2
477
        );
478
479
        $result3 = $form->FilteredEmailRecipients(
480
            [
481
                'your-name' => 'Should be blank but is not',
482
                'address' => 'Anything',
483
                'street' => 'Matches Equals',
484
                'city' => 'Anything',
485
                'colours' => ['Blue']
486
            ],
487
            null
488
        )->column('EmailAddress');
489
        $this->assertEquals(
490
            [
491
                '[email protected]'
492
            ],
493
            $result3
494
        );
495
496
497
        $result4 = $form->FilteredEmailRecipients(
498
            [
499
                'your-name' => '',
500
                'address' => 'Anything',
501
                'street' => 'Wrong value for this field',
502
                'city' => '',
503
                'colours' => ['Blue', 'Green']
504
            ],
505
            null
506
        )->column('EmailAddress');
507
        $this->assertEquals(
508
            ['[email protected]'],
509
            $result4
510
        );
511
    }
512
513
    public function testIndex()
514
    {
515
        // Test that the $UserDefinedForm is stripped out
516
        $page = $this->objFromFixture(UserDefinedForm::class, 'basic-form-page');
517
        $page->publish('Stage', 'Live');
518
519
        $result = $this->get($page->Link());
520
        $body = Convert::nl2os($result->getBody(), ''); // strip out newlines
521
        $this->assertFalse($result->isError());
522
        $this->assertContains('<p>Here is my form</p><form', $body);
523
        $this->assertContains('</form><p>Thank you for filling it out</p>', $body);
524
525
        $this->assertNotContains('<p>$UserDefinedForm</p>', $body);
526
        $this->assertNotContains('<p></p>', $body);
527
        $this->assertNotContains('</p><p>Thank you for filling it out</p>', $body);
528
    }
529
530
    public function testEmailAddressValidation()
531
    {
532
        $this->logInWithPermission('ADMIN');
533
534
        // test invalid email addresses fail validation
535
        $recipient = $this->objFromFixture(
536
            EmailRecipient::class,
537
            'invalid-recipient-list'
538
        );
539
        $result = $recipient->validate();
540
        $this->assertFalse($result->isValid());
541
        $this->assertNotEmpty($result->getMessages());
542
        $this->assertContains('filtered.example.com', $result->getMessages()[0]['message']);
543
        $this->assertNotContains('[email protected]', $result->getMessages()[0]['message']);
544
545
        // test valid email addresses pass validation
546
        $recipient = $this->objFromFixture(
547
            EmailRecipient::class,
548
            'valid-recipient-list'
549
        );
550
        $result = $recipient->validate();
551
        $this->assertTrue($result->isValid());
552
        $this->assertEmpty($result->getMessages());
553
    }
554
}
555