Completed
Push — master ( 79d3cf...7bc817 )
by Damian
09:08
created

CheckboxSetFieldTest   B

Complexity

Total Complexity 10

Size/Duplication

Total Lines 372
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 17

Importance

Changes 0
Metric Value
dl 0
loc 372
rs 7.8571
c 0
b 0
f 0
wmc 10
lcom 1
cbo 17

10 Methods

Rating   Name   Duplication   Size   Complexity  
B testSetDefaultItems() 0 36 1
B testSources() 0 36 1
A testSaveWithNothingSelected() 0 20 1
B testSaveWithArrayValueSet() 0 40 1
B testLoadDataFromObject() 0 29 1
B testSavingIntoTextField() 0 26 1
B testValidationWithArray() 0 33 1
B testValidationWithDataList() 0 86 1
B testSafelyCast() 0 25 1
A testNoAriaRequired() 0 15 1
1
<?php
2
3
namespace SilverStripe\Forms\Tests;
4
5
use SilverStripe\Forms\Tests\CheckboxSetFieldTest\Article;
6
use SilverStripe\Forms\Tests\CheckboxSetFieldTest\Tag;
7
use SilverStripe\ORM\ArrayList;
8
use SilverStripe\ORM\DataObject;
9
use SilverStripe\ORM\DB;
10
use SilverStripe\Security\Member;
11
use SilverStripe\ORM\FieldType\DBField;
12
use SilverStripe\Dev\CSSContentParser;
13
use SilverStripe\Dev\SapphireTest;
14
use SilverStripe\Control\Controller;
15
use SilverStripe\Forms\CheckboxSetField;
16
use SilverStripe\Forms\FieldList;
17
use SilverStripe\Forms\Form;
18
use SilverStripe\Forms\RequiredFields;
19
use SilverStripe\View\ArrayData;
20
21
class CheckboxSetFieldTest extends SapphireTest
22
{
23
24
    protected static $fixture_file = 'CheckboxSetFieldTest.yml';
25
26
    protected static $extra_dataobjects = array(
27
        Article::class,
28
        Tag::class,
29
    );
30
31
    public function testSetDefaultItems()
32
    {
33
        $f = new CheckboxSetField(
34
            'Test',
35
            false,
36
            array(0 => 'Zero', 1 => 'One', 2 => 'Two', 3 => 'Three')
37
        );
38
39
        $f->setValue(array(0,1));
40
        $f->setDefaultItems(array(2));
41
        $p = new CSSContentParser($f->Field());
42
        $item0 = $p->getBySelector('#Test_0');
43
        $item1 = $p->getBySelector('#Test_1');
44
        $item2 = $p->getBySelector('#Test_2');
45
        $item3 = $p->getBySelector('#Test_3');
46
        $this->assertEquals(
47
            (string)$item0[0]['checked'],
48
            'checked',
49
            'Selected through value'
50
        );
51
        $this->assertEquals(
52
            (string)$item1[0]['checked'],
53
            'checked',
54
            'Selected through value'
55
        );
56
        $this->assertEquals(
57
            (string)$item2[0]['checked'],
58
            'checked',
59
            'Selected through default items'
60
        );
61
        $this->assertEquals(
62
            (string)$item3[0]['checked'],
63
            '',
64
            'Not selected by either value or default items'
65
        );
66
    }
67
68
    /**
69
     * Test different data sources
70
     */
71
    public function testSources()
72
    {
73
        // Array
74
        $items = array('a' => 'Apple', 'b' => 'Banana', 'c' => 'Cranberry');
75
        $field = new CheckboxSetField('Field', null, $items);
76
        $this->assertEquals($items, $field->getSource());
77
78
        // SS_List
79
        $list = new ArrayList(
80
            array(
81
            new ArrayData(
82
                array(
83
                'ID' => 'a',
84
                'Title' => 'Apple'
85
                )
86
            ),
87
            new ArrayData(
88
                array(
89
                'ID' => 'b',
90
                'Title' => 'Banana'
91
                )
92
            ),
93
            new ArrayData(
94
                array(
95
                'ID' => 'c',
96
                'Title' => 'Cranberry'
97
                )
98
            )
99
            )
100
        );
101
        $field2 = new CheckboxSetField('Field', null, $list);
102
        $this->assertEquals($items, $field2->getSource());
103
104
        $field3 = new CheckboxSetField('Field', null, $list->map());
105
        $this->assertEquals($items, $field3->getSource());
106
    }
107
108
    public function testSaveWithNothingSelected()
109
    {
110
        $article = $this->objFromFixture(Article::class, 'articlewithouttags');
111
112
        /* Create a CheckboxSetField with nothing selected */
113
        $field = new CheckboxSetField("Tags", "Test field", DataObject::get(Tag::class)->map());
114
115
        /* Saving should work */
116
        $field->saveInto($article);
0 ignored issues
show
Bug introduced by
It seems like $article defined by $this->objFromFixture(\S..., 'articlewithouttags') on line 110 can be null; however, SilverStripe\Forms\MultiSelectField::saveInto() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
117
118
        $this->assertNull(
119
            DB::prepared_query(
120
                "SELECT *
121
				FROM \"CheckboxSetFieldTest_Article_Tags\"
122
				WHERE \"CheckboxSetFieldTest_Article_Tags\".\"CheckboxSetFieldTest_ArticleID\" = ?",
123
                array($article->ID)
124
            )->value(),
125
            'Nothing should go into manymany join table for a saved field without any ticked boxes'
126
        );
127
    }
128
129
    public function testSaveWithArrayValueSet()
130
    {
131
        $article = $this->objFromFixture(Article::class, 'articlewithouttags');
132
        $articleWithTags = $this->objFromFixture(Article::class, 'articlewithtags');
133
        $tag1 = $this->objFromFixture(Tag::class, 'tag1');
134
        $tag2 = $this->objFromFixture(Tag::class, 'tag2');
135
136
        /* Create a CheckboxSetField with 2 items selected.  Note that the array is a list of values */
137
        $field = new CheckboxSetField("Tags", "Test field", DataObject::get(Tag::class)->map());
138
        $field->setValue(
139
            array(
140
            $tag1->ID,
141
            $tag2->ID
142
            )
143
        );
144
145
        /* Saving should work */
146
        $field->saveInto($article);
0 ignored issues
show
Bug introduced by
It seems like $article defined by $this->objFromFixture(\S..., 'articlewithouttags') on line 131 can be null; however, SilverStripe\Forms\MultiSelectField::saveInto() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
147
148
        $this->assertEquals(
149
            array($tag1->ID,$tag2->ID),
150
            DB::prepared_query(
151
                "SELECT \"CheckboxSetFieldTest_TagID\"
152
				FROM \"CheckboxSetFieldTest_Article_Tags\"
153
				WHERE \"CheckboxSetFieldTest_Article_Tags\".\"CheckboxSetFieldTest_ArticleID\" = ?",
154
                array($article->ID)
155
            )->column(),
156
            'Data shold be saved into CheckboxSetField manymany relation table on the "right end"'
157
        );
158
        $this->assertEquals(
159
            array($articleWithTags->ID,$article->ID),
160
            DB::query(
161
                "SELECT \"CheckboxSetFieldTest_ArticleID\"
162
				FROM \"CheckboxSetFieldTest_Article_Tags\"
163
				WHERE \"CheckboxSetFieldTest_Article_Tags\".\"CheckboxSetFieldTest_TagID\" = $tag1->ID
164
			"
165
            )->column(),
166
            'Data shold be saved into CheckboxSetField manymany relation table on the "left end"'
167
        );
168
    }
169
170
    public function testLoadDataFromObject()
171
    {
172
        $article = $this->objFromFixture(Article::class, 'articlewithouttags');
173
        $articleWithTags = $this->objFromFixture(Article::class, 'articlewithtags');
174
        $tag1 = $this->objFromFixture(Tag::class, 'tag1');
175
        $tag2 = $this->objFromFixture(Tag::class, 'tag2');
176
177
        $field = new CheckboxSetField("Tags", "Test field", DataObject::get(Tag::class)->map());
178
        /**
179
 * @skipUpgrade
180
*/
181
        $form = new Form(
182
            new Controller(),
183
            'Form',
184
            new FieldList($field),
185
            new FieldList()
186
        );
187
        $form->loadDataFrom($articleWithTags);
0 ignored issues
show
Bug introduced by
It seems like $articleWithTags defined by $this->objFromFixture(\S...ass, 'articlewithtags') on line 173 can be null; however, SilverStripe\Forms\Form::loadDataFrom() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
188
        $value = $field->Value();
189
        sort($value);
190
        $this->assertEquals(
191
            array(
192
                $tag1->ID,
193
                $tag2->ID
194
            ),
195
            $value,
196
            'CheckboxSetField loads data from a manymany relationship in an object through Form->loadDataFrom()'
197
        );
198
    }
199
200
    public function testSavingIntoTextField()
201
    {
202
        $field = new CheckboxSetField(
203
            'Content',
204
            'Content',
205
            array(
206
            'Test' => 'Test',
207
            'Another' => 'Another',
208
            'Something' => 'Something'
209
            )
210
        );
211
        $article = new CheckboxSetFieldTest\Article();
212
        $field->setValue(array('Test' => 'Test', 'Another' => 'Another'));
213
        $field->saveInto($article);
214
        $article->write();
215
216
        $dbValue = DB::query(
217
            sprintf(
218
                'SELECT "Content" FROM "CheckboxSetFieldTest_Article" WHERE "ID" = %s',
219
                $article->ID
220
            )
221
        )->value();
222
223
        // JSON encoded values
224
        $this->assertEquals('["Test","Another"]', $dbValue);
225
    }
226
227
    public function testValidationWithArray()
228
    {
229
        // Test with array input
230
        $field = CheckboxSetField::create(
231
            'Test',
232
            'Testing',
233
            array(
234
            "One" => "One",
235
            "Two" => "Two",
236
            "Three" => "Three"
237
            )
238
        );
239
        $validator = new RequiredFields();
240
        $field->setValue(array("One", "Two"));
241
        $this->assertTrue(
242
            $field->validate($validator),
243
            'Field validates values within source array'
244
        );
245
246
        // Non valid value should fail
247
        $field->setValue(array("Four" => "Four"));
248
        $this->assertFalse(
249
            $field->validate($validator),
250
            'Field does not validate values outside of source array'
251
        );
252
253
        // Non valid value, even if included with valid options, should fail
254
        $field->setValue(array("One", "Two", "Four"));
255
        $this->assertFalse(
256
            $field->validate($validator),
257
            'Field does not validate when presented with mixed valid and invalid values'
258
        );
259
    }
260
261
    public function testValidationWithDataList()
262
    {
263
        //test with datalist input
264
        $checkboxTestArticle = $this->objFromFixture(Article::class, 'articlewithtags');
265
        $tag1 = $this->objFromFixture(Tag::class, 'tag1');
266
        $tag2 = $this->objFromFixture(Tag::class, 'tag2');
267
        $tag3 = $this->objFromFixture(Tag::class, 'tag3');
268
        $field = CheckboxSetField::create('Test', 'Testing', $checkboxTestArticle->Tags());
269
        $validator = new RequiredFields();
270
        $field->setValue(array( $tag1->ID, $tag2->ID ));
271
        $isValid = $field->validate($validator);
272
        $this->assertTrue(
273
            $isValid,
274
            'Validates values in source map'
275
        );
276
277
        // Invalid value should fail
278
        $validator = new RequiredFields();
279
        $fakeID = CheckboxSetFieldTest\Tag::get()->max('ID') + 1;
280
        $field->setValue(array($fakeID));
281
        $this->assertFalse(
282
            $field->validate($validator),
283
            'Field does not valid values outside of source map'
284
        );
285
        $errors = $validator->getErrors();
286
        $error = reset($errors);
287
        $this->assertEquals(
288
            _t(
289
                'SilverStripe\\Forms\\MultiSelectField.SOURCE_VALIDATION',
290
                "Please select values within the list provided. Invalid option(s) {value} given",
291
                array('value' => $fakeID)
292
            ),
293
            $error['message']
294
        );
295
296
        // Multiple invalid values should fail
297
        $validator = new RequiredFields();
298
        $fakeID = Tag::get()->max('ID') + 1;
299
        $field->setValue(array($fakeID, $tag3->ID));
300
        $this->assertFalse(
301
            $field->validate($validator),
302
            'Field does not valid values outside of source map'
303
        );
304
        $errors = $validator->getErrors();
305
        $error = reset($errors);
306
        $this->assertEquals(
307
            _t(
308
                'SilverStripe\\Forms\\MultiSelectField.SOURCE_VALIDATION',
309
                "Please select values within the list provided. Invalid option(s) {value} given",
310
                array('value' => implode(',', [$fakeID, $tag3->ID]))
311
            ),
312
            $error['message']
313
        );
314
315
        // Invalid value with non-array value
316
        $validator = new RequiredFields();
317
        $field->setValue($fakeID);
318
        $this->assertFalse(
319
            $field->validate($validator),
320
            'Field does not valid values outside of source map'
321
        );
322
        $errors = $validator->getErrors();
323
        $error = reset($errors);
324
        $this->assertEquals(
325
            _t(
326
                'SilverStripe\\Forms\\MultiSelectField.SOURCE_VALIDATION',
327
                "Please select values within the list provided. Invalid option(s) {value} given",
328
                array('value' => $fakeID)
329
            ),
330
            $error['message']
331
        );
332
333
        //non valid value included with valid options should succeed
334
        $validator = new RequiredFields();
335
        $field->setValue(
336
            array(
337
            $tag1->ID,
338
            $tag2->ID,
339
            $tag3->ID
340
            )
341
        );
342
        $this->assertFalse(
343
            $field->validate($validator),
344
            'Field does not validate when presented with mixed valid and invalid values'
345
        );
346
    }
347
348
    public function testSafelyCast()
349
    {
350
        $member = new Member();
351
        $member->FirstName = '<firstname>';
352
        $member->Surname = '<surname>';
353
        $member->write();
354
        $field1 = new CheckboxSetField(
355
            'Options',
356
            'Options',
357
            array(
358
            'one' => 'One',
359
            'two' => 'Two & Three',
360
            'three' => DBField::create_field('HTMLText', 'Four &amp; Five &amp; Six'),
361
            'four' => $member->FirstName,
362
            )
363
        );
364
        $fieldHTML = (string)$field1->Field();
365
        $this->assertContains('One', $fieldHTML);
366
        $this->assertContains('Two &amp; Three', $fieldHTML);
367
        $this->assertNotContains('Two & Three', $fieldHTML);
368
        $this->assertContains('Four &amp; Five &amp; Six', $fieldHTML);
369
        $this->assertNotContains('Four & Five & Six', $fieldHTML);
370
        $this->assertContains('&lt;firstname&gt;', $fieldHTML);
371
        $this->assertNotContains('<firstname>', $fieldHTML);
372
    }
373
374
    /**
375
     * #2939 CheckboxSetField creates invalid HTML when required
376
     */
377
    public function testNoAriaRequired()
378
    {
379
        $field = new CheckboxSetField('RequiredField', 'myRequiredField');
380
381
        $form = new Form(
382
            Controller::curr(), "form", new FieldList($field), new FieldList(),
383
            new RequiredFields(["RequiredField"])
384
        );
385
        $this->assertTrue($field->Required());
386
387
        $attributes = $field->getAttributes();
388
        $this->assertFalse(array_key_exists("aria-required", $attributes));
389
        $this->assertFalse(array_key_exists("name", $attributes));
390
        $this->assertFalse(array_key_exists("required", $attributes));
391
    }
392
}
393