Completed
Push — master ( 43d0b8...1d1227 )
by Daniel
16:45
created

OptionsetFieldTest::testSafelyCast()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 4 Features 0
Metric Value
cc 1
eloc 11
nc 1
nop 0
dl 0
loc 13
rs 9.4285
c 4
b 4
f 0
1
<?php
2
3
use SilverStripe\ORM\FieldType\DBField;
4
5
/**
6
 * @package framework
7
 * @subpackage tests
8
 */
9
class OptionsetFieldTest extends SapphireTest {
10
	public function testSetDisabledItems() {
11
		$f = new OptionsetField(
12
			'Test',
13
			false,
14
			array(0 => 'Zero', 1 => 'One')
15
		);
16
17
		$f->setDisabledItems(array(0));
18
		$p = new CSSContentParser($f->Field());
19
		$item0 = $p->getBySelector('#Test_0');
20
		$item1 = $p->getBySelector('#Test_1');
21
		$this->assertEquals(
22
			(string)$item0[0]['disabled'],
23
			'disabled'
24
		);
25
		$this->assertEquals(
26
			(string)$item1[0]['disabled'],
27
			''
28
		);
29
	}
30
31
	public function testValidation() {
32
		$field = OptionsetField::create('Test', 'Testing', array(
33
			"One" => "One",
34
			"Two" => "Two",
35
			"Five" => "Five"
36
		));
37
		$validator = new RequiredFields('Test');
38
		$form = new Form($this, 'Form', new FieldList($field), new FieldList(), $validator);
39
40
		$field->setValue("One");
41
		$this->assertTrue($field->validate($validator));
42
43
		//non-existent value should make the field invalid
44
		$field->setValue("Three");
45
		$this->assertFalse($field->validate($validator));
46
47
		//empty string should pass field-level validation...
48
		$field->setValue('');
49
		$this->assertTrue($field->validate($validator));
50
51
		// ... but should not pass "RequiredFields" validation
52
		$this->assertFalse($form->validate());
53
54
		//disabled items shouldn't validate
55
		$field->setDisabledItems(array('Five'));
56
		$field->setValue('Five');
57
		$this->assertFalse($field->validate($validator));
58
	}
59
60
	public function testReadonlyField() {
61
		$sourceArray = array(0 => 'No', 1 => 'Yes');
62
		$field = new OptionsetField('FeelingOk', 'are you feeling ok?', $sourceArray, 1);
63
		$field->setEmptyString('(Select one)');
64
		$field->setValue(1);
65
		$readonlyField = $field->performReadonlyTransformation();
66
		preg_match('/Yes/', $field->Field(), $matches);
67
		$this->assertEquals($matches[0], 'Yes');
68
	}
69
70
	public function testSafelyCast() {
71
		$field1 = new OptionsetField('Options', 'Options', array(
72
			1 => 'One',
73
			2 => 'Two & Three',
74
			3 => DBField::create_field('HTMLText', 'Four &amp; Five &amp; Six')
75
		));
76
		$fieldHTML = (string)$field1->Field();
77
		$this->assertContains('One', $fieldHTML);
78
		$this->assertContains('Two &amp; Three', $fieldHTML);
79
		$this->assertNotContains('Two & Three', $fieldHTML);
80
		$this->assertContains('Four &amp; Five &amp; Six', $fieldHTML);
81
		$this->assertNotContains('Four & Five & Six', $fieldHTML);
82
	}
83
}
84