0a4cd7201e1bb8e59e30b696ba75fb8fdf6fcc47
[yaffs-website] / vendor / symfony / dom-crawler / Tests / FormTest.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Symfony\Component\DomCrawler\Tests;
13
14 use PHPUnit\Framework\TestCase;
15 use Symfony\Component\DomCrawler\Form;
16 use Symfony\Component\DomCrawler\FormFieldRegistry;
17
18 class FormTest extends TestCase
19 {
20     public static function setUpBeforeClass()
21     {
22         // Ensure that the private helper class FormFieldRegistry is loaded
23         class_exists('Symfony\\Component\\DomCrawler\\Form');
24     }
25
26     public function testConstructorThrowsExceptionIfTheNodeHasNoFormAncestor()
27     {
28         $dom = new \DOMDocument();
29         $dom->loadHTML('
30             <html>
31                 <input type="submit" />
32                 <form>
33                     <input type="foo" />
34                 </form>
35                 <button />
36             </html>
37         ');
38
39         $nodes = $dom->getElementsByTagName('input');
40
41         try {
42             $form = new Form($nodes->item(0), 'http://example.com');
43             $this->fail('__construct() throws a \\LogicException if the node has no form ancestor');
44         } catch (\LogicException $e) {
45             $this->assertTrue(true, '__construct() throws a \\LogicException if the node has no form ancestor');
46         }
47
48         try {
49             $form = new Form($nodes->item(1), 'http://example.com');
50             $this->fail('__construct() throws a \\LogicException if the input type is not submit, button, or image');
51         } catch (\LogicException $e) {
52             $this->assertTrue(true, '__construct() throws a \\LogicException if the input type is not submit, button, or image');
53         }
54
55         $nodes = $dom->getElementsByTagName('button');
56
57         try {
58             $form = new Form($nodes->item(0), 'http://example.com');
59             $this->fail('__construct() throws a \\LogicException if the node has no form ancestor');
60         } catch (\LogicException $e) {
61             $this->assertTrue(true, '__construct() throws a \\LogicException if the node has no form ancestor');
62         }
63     }
64
65     /**
66      * __construct() should throw \\LogicException if the form attribute is invalid.
67      *
68      * @expectedException \LogicException
69      */
70     public function testConstructorThrowsExceptionIfNoRelatedForm()
71     {
72         $dom = new \DOMDocument();
73         $dom->loadHTML('
74             <html>
75                 <form id="bar">
76                     <input type="submit" form="nonexistent" />
77                 </form>
78                 <input type="text" form="nonexistent" />
79                 <button />
80             </html>
81         ');
82
83         $nodes = $dom->getElementsByTagName('input');
84
85         $form = new Form($nodes->item(0), 'http://example.com');
86         $form = new Form($nodes->item(1), 'http://example.com');
87     }
88
89     public function testConstructorLoadsOnlyFieldsOfTheRightForm()
90     {
91         $dom = $this->createTestMultipleForm();
92
93         $nodes = $dom->getElementsByTagName('form');
94         $buttonElements = $dom->getElementsByTagName('button');
95
96         $form = new Form($nodes->item(0), 'http://example.com');
97         $this->assertCount(3, $form->all());
98
99         $form = new Form($buttonElements->item(1), 'http://example.com');
100         $this->assertCount(5, $form->all());
101     }
102
103     public function testConstructorHandlesFormAttribute()
104     {
105         $dom = $this->createTestHtml5Form();
106
107         $inputElements = $dom->getElementsByTagName('input');
108         $buttonElements = $dom->getElementsByTagName('button');
109
110         // Tests if submit buttons are correctly assigned to forms
111         $form1 = new Form($buttonElements->item(1), 'http://example.com');
112         $this->assertSame($dom->getElementsByTagName('form')->item(0), $form1->getFormNode(), 'HTML5-compliant form attribute handled incorrectly');
113
114         $form1 = new Form($inputElements->item(3), 'http://example.com');
115         $this->assertSame($dom->getElementsByTagName('form')->item(0), $form1->getFormNode(), 'HTML5-compliant form attribute handled incorrectly');
116
117         $form2 = new Form($buttonElements->item(0), 'http://example.com');
118         $this->assertSame($dom->getElementsByTagName('form')->item(1), $form2->getFormNode(), 'HTML5-compliant form attribute handled incorrectly');
119     }
120
121     public function testConstructorHandlesFormValues()
122     {
123         $dom = $this->createTestHtml5Form();
124
125         $inputElements = $dom->getElementsByTagName('input');
126         $buttonElements = $dom->getElementsByTagName('button');
127
128         $form1 = new Form($inputElements->item(3), 'http://example.com');
129         $form2 = new Form($buttonElements->item(0), 'http://example.com');
130
131         // Tests if form values are correctly assigned to forms
132         $values1 = array(
133             'apples' => array('1', '2'),
134             'form_name' => 'form-1',
135             'button_1' => 'Capture fields',
136             'outer_field' => 'success',
137         );
138         $values2 = array(
139             'oranges' => array('1', '2', '3'),
140             'form_name' => 'form_2',
141             'button_2' => '',
142             'app_frontend_form_type_contact_form_type' => array('contactType' => '', 'firstName' => 'John'),
143         );
144
145         $this->assertEquals($values1, $form1->getPhpValues(), 'HTML5-compliant form attribute handled incorrectly');
146         $this->assertEquals($values2, $form2->getPhpValues(), 'HTML5-compliant form attribute handled incorrectly');
147     }
148
149     public function testMultiValuedFields()
150     {
151         $form = $this->createForm('<form>
152             <input type="text" name="foo[4]" value="foo" disabled="disabled" />
153             <input type="text" name="foo" value="foo" disabled="disabled" />
154             <input type="text" name="foo[2]" value="foo" disabled="disabled" />
155             <input type="text" name="foo[]" value="foo" disabled="disabled" />
156             <input type="text" name="bar[foo][]" value="foo" disabled="disabled" />
157             <input type="text" name="bar[foo][foobar]" value="foo" disabled="disabled" />
158             <input type="submit" />
159         </form>
160         ');
161
162         $this->assertEquals(
163             array_keys($form->all()),
164             array('foo[2]', 'foo[3]', 'bar[foo][0]', 'bar[foo][foobar]')
165         );
166
167         $this->assertEquals($form->get('foo[2]')->getValue(), 'foo');
168         $this->assertEquals($form->get('foo[3]')->getValue(), 'foo');
169         $this->assertEquals($form->get('bar[foo][0]')->getValue(), 'foo');
170         $this->assertEquals($form->get('bar[foo][foobar]')->getValue(), 'foo');
171
172         $form['foo[2]'] = 'bar';
173         $form['foo[3]'] = 'bar';
174
175         $this->assertEquals($form->get('foo[2]')->getValue(), 'bar');
176         $this->assertEquals($form->get('foo[3]')->getValue(), 'bar');
177
178         $form['bar'] = array('foo' => array('0' => 'bar', 'foobar' => 'foobar'));
179
180         $this->assertEquals($form->get('bar[foo][0]')->getValue(), 'bar');
181         $this->assertEquals($form->get('bar[foo][foobar]')->getValue(), 'foobar');
182     }
183
184     /**
185      * @dataProvider provideInitializeValues
186      */
187     public function testConstructor($message, $form, $values)
188     {
189         $form = $this->createForm('<form>'.$form.'</form>');
190         $this->assertEquals(
191             $values,
192             array_map(
193                 function ($field) {
194                     $class = get_class($field);
195
196                     return array(substr($class, strrpos($class, '\\') + 1), $field->getValue());
197                 },
198                 $form->all()
199             ),
200             '->getDefaultValues() '.$message
201         );
202     }
203
204     public function provideInitializeValues()
205     {
206         return array(
207             array(
208                 'does not take into account input fields without a name attribute',
209                 '<input type="text" value="foo" />
210                  <input type="submit" />',
211                 array(),
212             ),
213             array(
214                 'does not take into account input fields with an empty name attribute value',
215                 '<input type="text" name="" value="foo" />
216                  <input type="submit" />',
217                 array(),
218             ),
219             array(
220                 'takes into account disabled input fields',
221                 '<input type="text" name="foo" value="foo" disabled="disabled" />
222                  <input type="submit" />',
223                 array('foo' => array('InputFormField', 'foo')),
224             ),
225             array(
226                 'appends the submitted button value',
227                 '<input type="submit" name="bar" value="bar" />',
228                 array('bar' => array('InputFormField', 'bar')),
229             ),
230             array(
231                 'appends the submitted button value for Button element',
232                 '<button type="submit" name="bar" value="bar">Bar</button>',
233                 array('bar' => array('InputFormField', 'bar')),
234             ),
235             array(
236                 'appends the submitted button value but not other submit buttons',
237                 '<input type="submit" name="bar" value="bar" />
238                  <input type="submit" name="foobar" value="foobar" />',
239                  array('foobar' => array('InputFormField', 'foobar')),
240             ),
241             array(
242                 'turns an image input into x and y fields',
243                 '<input type="image" name="bar" />',
244                 array('bar.x' => array('InputFormField', '0'), 'bar.y' => array('InputFormField', '0')),
245             ),
246             array(
247                 'returns textareas',
248                 '<textarea name="foo">foo</textarea>
249                  <input type="submit" />',
250                  array('foo' => array('TextareaFormField', 'foo')),
251             ),
252             array(
253                 'returns inputs',
254                 '<input type="text" name="foo" value="foo" />
255                  <input type="submit" />',
256                  array('foo' => array('InputFormField', 'foo')),
257             ),
258             array(
259                 'returns checkboxes',
260                 '<input type="checkbox" name="foo" value="foo" checked="checked" />
261                  <input type="submit" />',
262                  array('foo' => array('ChoiceFormField', 'foo')),
263             ),
264             array(
265                 'returns not-checked checkboxes',
266                 '<input type="checkbox" name="foo" value="foo" />
267                  <input type="submit" />',
268                  array('foo' => array('ChoiceFormField', false)),
269             ),
270             array(
271                 'returns radio buttons',
272                 '<input type="radio" name="foo" value="foo" />
273                  <input type="radio" name="foo" value="bar" checked="bar" />
274                  <input type="submit" />',
275                  array('foo' => array('ChoiceFormField', 'bar')),
276             ),
277             array(
278                 'returns file inputs',
279                 '<input type="file" name="foo" />
280                  <input type="submit" />',
281                  array('foo' => array('FileFormField', array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => 4, 'size' => 0))),
282             ),
283         );
284     }
285
286     public function testGetFormNode()
287     {
288         $dom = new \DOMDocument();
289         $dom->loadHTML('<html><form><input type="submit" /></form></html>');
290
291         $form = new Form($dom->getElementsByTagName('input')->item(0), 'http://example.com');
292
293         $this->assertSame($dom->getElementsByTagName('form')->item(0), $form->getFormNode(), '->getFormNode() returns the form node associated with this form');
294     }
295
296     public function testGetFormNodeFromNamedForm()
297     {
298         $dom = new \DOMDocument();
299         $dom->loadHTML('<html><form name="my_form"><input type="submit" /></form></html>');
300
301         $form = new Form($dom->getElementsByTagName('form')->item(0), 'http://example.com');
302
303         $this->assertSame($dom->getElementsByTagName('form')->item(0), $form->getFormNode(), '->getFormNode() returns the form node associated with this form');
304     }
305
306     public function testGetMethod()
307     {
308         $form = $this->createForm('<form><input type="submit" /></form>');
309         $this->assertEquals('GET', $form->getMethod(), '->getMethod() returns get if no method is defined');
310
311         $form = $this->createForm('<form method="post"><input type="submit" /></form>');
312         $this->assertEquals('POST', $form->getMethod(), '->getMethod() returns the method attribute value of the form');
313
314         $form = $this->createForm('<form method="post"><input type="submit" /></form>', 'put');
315         $this->assertEquals('PUT', $form->getMethod(), '->getMethod() returns the method defined in the constructor if provided');
316
317         $form = $this->createForm('<form method="post"><input type="submit" /></form>', 'delete');
318         $this->assertEquals('DELETE', $form->getMethod(), '->getMethod() returns the method defined in the constructor if provided');
319
320         $form = $this->createForm('<form method="post"><input type="submit" /></form>', 'patch');
321         $this->assertEquals('PATCH', $form->getMethod(), '->getMethod() returns the method defined in the constructor if provided');
322     }
323
324     public function testGetSetValue()
325     {
326         $form = $this->createForm('<form><input type="text" name="foo" value="foo" /><input type="submit" /></form>');
327
328         $this->assertEquals('foo', $form['foo']->getValue(), '->offsetGet() returns the value of a form field');
329
330         $form['foo'] = 'bar';
331
332         $this->assertEquals('bar', $form['foo']->getValue(), '->offsetSet() changes the value of a form field');
333
334         try {
335             $form['foobar'] = 'bar';
336             $this->fail('->offsetSet() throws an \InvalidArgumentException exception if the field does not exist');
337         } catch (\InvalidArgumentException $e) {
338             $this->assertTrue(true, '->offsetSet() throws an \InvalidArgumentException exception if the field does not exist');
339         }
340
341         try {
342             $form['foobar'];
343             $this->fail('->offsetSet() throws an \InvalidArgumentException exception if the field does not exist');
344         } catch (\InvalidArgumentException $e) {
345             $this->assertTrue(true, '->offsetSet() throws an \InvalidArgumentException exception if the field does not exist');
346         }
347     }
348
349     public function testDisableValidation()
350     {
351         $form = $this->createForm('<form>
352             <select name="foo[bar]">
353                 <option value="bar">bar</option>
354             </select>
355             <select name="foo[baz]">
356                 <option value="foo">foo</option>
357             </select>
358             <input type="submit" />
359         </form>');
360
361         $form->disableValidation();
362
363         $form['foo[bar]']->select('foo');
364         $form['foo[baz]']->select('bar');
365         $this->assertEquals('foo', $form['foo[bar]']->getValue(), '->disableValidation() disables validation of all ChoiceFormField.');
366         $this->assertEquals('bar', $form['foo[baz]']->getValue(), '->disableValidation() disables validation of all ChoiceFormField.');
367     }
368
369     public function testOffsetUnset()
370     {
371         $form = $this->createForm('<form><input type="text" name="foo" value="foo" /><input type="submit" /></form>');
372         unset($form['foo']);
373         $this->assertFalse(isset($form['foo']), '->offsetUnset() removes a field');
374     }
375
376     public function testOffsetExists()
377     {
378         $form = $this->createForm('<form><input type="text" name="foo" value="foo" /><input type="submit" /></form>');
379
380         $this->assertTrue(isset($form['foo']), '->offsetExists() return true if the field exists');
381         $this->assertFalse(isset($form['bar']), '->offsetExists() return false if the field does not exist');
382     }
383
384     public function testGetValues()
385     {
386         $form = $this->createForm('<form><input type="text" name="foo[bar]" value="foo" /><input type="text" name="bar" value="bar" /><select multiple="multiple" name="baz[]"></select><input type="submit" /></form>');
387         $this->assertEquals(array('foo[bar]' => 'foo', 'bar' => 'bar', 'baz' => array()), $form->getValues(), '->getValues() returns all form field values');
388
389         $form = $this->createForm('<form><input type="checkbox" name="foo" value="foo" /><input type="text" name="bar" value="bar" /><input type="submit" /></form>');
390         $this->assertEquals(array('bar' => 'bar'), $form->getValues(), '->getValues() does not include not-checked checkboxes');
391
392         $form = $this->createForm('<form><input type="file" name="foo" value="foo" /><input type="text" name="bar" value="bar" /><input type="submit" /></form>');
393         $this->assertEquals(array('bar' => 'bar'), $form->getValues(), '->getValues() does not include file input fields');
394
395         $form = $this->createForm('<form><input type="text" name="foo" value="foo" disabled="disabled" /><input type="text" name="bar" value="bar" /><input type="submit" /></form>');
396         $this->assertEquals(array('bar' => 'bar'), $form->getValues(), '->getValues() does not include disabled fields');
397     }
398
399     public function testSetValues()
400     {
401         $form = $this->createForm('<form><input type="checkbox" name="foo" value="foo" checked="checked" /><input type="text" name="bar" value="bar" /><input type="submit" /></form>');
402         $form->setValues(array('foo' => false, 'bar' => 'foo'));
403         $this->assertEquals(array('bar' => 'foo'), $form->getValues(), '->setValues() sets the values of fields');
404     }
405
406     public function testMultiselectSetValues()
407     {
408         $form = $this->createForm('<form><select multiple="multiple" name="multi"><option value="foo">foo</option><option value="bar">bar</option></select><input type="submit" /></form>');
409         $form->setValues(array('multi' => array('foo', 'bar')));
410         $this->assertEquals(array('multi' => array('foo', 'bar')), $form->getValues(), '->setValue() sets the values of select');
411     }
412
413     public function testGetPhpValues()
414     {
415         $form = $this->createForm('<form><input type="text" name="foo[bar]" value="foo" /><input type="text" name="bar" value="bar" /><input type="submit" /></form>');
416         $this->assertEquals(array('foo' => array('bar' => 'foo'), 'bar' => 'bar'), $form->getPhpValues(), '->getPhpValues() converts keys with [] to arrays');
417
418         $form = $this->createForm('<form><input type="text" name="fo.o[ba.r]" value="foo" /><input type="text" name="ba r" value="bar" /><input type="submit" /></form>');
419         $this->assertEquals(array('fo.o' => array('ba.r' => 'foo'), 'ba r' => 'bar'), $form->getPhpValues(), '->getPhpValues() preserves periods and spaces in names');
420
421         $form = $this->createForm('<form><input type="text" name="fo.o[ba.r][]" value="foo" /><input type="text" name="fo.o[ba.r][ba.z]" value="bar" /><input type="submit" /></form>');
422         $this->assertEquals(array('fo.o' => array('ba.r' => array('foo', 'ba.z' => 'bar'))), $form->getPhpValues(), '->getPhpValues() preserves periods and spaces in names recursively');
423
424         $form = $this->createForm('<form><input type="text" name="foo[bar]" value="foo" /><input type="text" name="bar" value="bar" /><select multiple="multiple" name="baz[]"></select><input type="submit" /></form>');
425         $this->assertEquals(array('foo' => array('bar' => 'foo'), 'bar' => 'bar'), $form->getPhpValues(), "->getPhpValues() doesn't return empty values");
426     }
427
428     public function testGetFiles()
429     {
430         $form = $this->createForm('<form><input type="file" name="foo[bar]" /><input type="text" name="bar" value="bar" /><input type="submit" /></form>');
431         $this->assertEquals(array(), $form->getFiles(), '->getFiles() returns an empty array if method is get');
432
433         $form = $this->createForm('<form method="post"><input type="file" name="foo[bar]" /><input type="text" name="bar" value="bar" /><input type="submit" /></form>');
434         $this->assertEquals(array('foo[bar]' => array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => 4, 'size' => 0)), $form->getFiles(), '->getFiles() only returns file fields for POST');
435
436         $form = $this->createForm('<form method="post"><input type="file" name="foo[bar]" /><input type="text" name="bar" value="bar" /><input type="submit" /></form>', 'put');
437         $this->assertEquals(array('foo[bar]' => array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => 4, 'size' => 0)), $form->getFiles(), '->getFiles() only returns file fields for PUT');
438
439         $form = $this->createForm('<form method="post"><input type="file" name="foo[bar]" /><input type="text" name="bar" value="bar" /><input type="submit" /></form>', 'delete');
440         $this->assertEquals(array('foo[bar]' => array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => 4, 'size' => 0)), $form->getFiles(), '->getFiles() only returns file fields for DELETE');
441
442         $form = $this->createForm('<form method="post"><input type="file" name="foo[bar]" /><input type="text" name="bar" value="bar" /><input type="submit" /></form>', 'patch');
443         $this->assertEquals(array('foo[bar]' => array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => 4, 'size' => 0)), $form->getFiles(), '->getFiles() only returns file fields for PATCH');
444
445         $form = $this->createForm('<form method="post"><input type="file" name="foo[bar]" disabled="disabled" /><input type="submit" /></form>');
446         $this->assertEquals(array(), $form->getFiles(), '->getFiles() does not include disabled file fields');
447     }
448
449     public function testGetPhpFiles()
450     {
451         $form = $this->createForm('<form method="post"><input type="file" name="foo[bar]" /><input type="text" name="bar" value="bar" /><input type="submit" /></form>');
452         $this->assertEquals(array('foo' => array('bar' => array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => 4, 'size' => 0))), $form->getPhpFiles(), '->getPhpFiles() converts keys with [] to arrays');
453
454         $form = $this->createForm('<form method="post"><input type="file" name="f.o o[bar]" /><input type="text" name="bar" value="bar" /><input type="submit" /></form>');
455         $this->assertEquals(array('f.o o' => array('bar' => array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => 4, 'size' => 0))), $form->getPhpFiles(), '->getPhpFiles() preserves periods and spaces in names');
456
457         $form = $this->createForm('<form method="post"><input type="file" name="f.o o[bar][ba.z]" /><input type="file" name="f.o o[bar][]" /><input type="text" name="bar" value="bar" /><input type="submit" /></form>');
458         $this->assertEquals(array('f.o o' => array('bar' => array('ba.z' => array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => 4, 'size' => 0), array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => 4, 'size' => 0)))), $form->getPhpFiles(), '->getPhpFiles() preserves periods and spaces in names recursively');
459     }
460
461     /**
462      * @dataProvider provideGetUriValues
463      */
464     public function testGetUri($message, $form, $values, $uri, $method = null)
465     {
466         $form = $this->createForm($form, $method);
467         $form->setValues($values);
468
469         $this->assertEquals('http://example.com'.$uri, $form->getUri(), '->getUri() '.$message);
470     }
471
472     public function testGetBaseUri()
473     {
474         $dom = new \DOMDocument();
475         $dom->loadHTML('<form method="post" action="foo.php"><input type="text" name="bar" value="bar" /><input type="submit" /></form>');
476
477         $nodes = $dom->getElementsByTagName('input');
478         $form = new Form($nodes->item($nodes->length - 1), 'http://www.foo.com/');
479         $this->assertEquals('http://www.foo.com/foo.php', $form->getUri());
480     }
481
482     public function testGetUriWithAnchor()
483     {
484         $form = $this->createForm('<form action="#foo"><input type="submit" /></form>', null, 'http://example.com/id/123');
485
486         $this->assertEquals('http://example.com/id/123#foo', $form->getUri());
487     }
488
489     public function testGetUriActionAbsolute()
490     {
491         $formHtml = '<form id="login_form" action="https://login.foo.com/login.php?login_attempt=1" method="POST"><input type="text" name="foo" value="foo" /><input type="submit" /></form>';
492
493         $form = $this->createForm($formHtml);
494         $this->assertEquals('https://login.foo.com/login.php?login_attempt=1', $form->getUri(), '->getUri() returns absolute URIs set in the action form');
495
496         $form = $this->createForm($formHtml, null, 'https://login.foo.com');
497         $this->assertEquals('https://login.foo.com/login.php?login_attempt=1', $form->getUri(), '->getUri() returns absolute URIs set in the action form');
498
499         $form = $this->createForm($formHtml, null, 'https://login.foo.com/bar/');
500         $this->assertEquals('https://login.foo.com/login.php?login_attempt=1', $form->getUri(), '->getUri() returns absolute URIs set in the action form');
501
502         // The action URI haven't the same domain Host have an another domain as Host
503         $form = $this->createForm($formHtml, null, 'https://www.foo.com');
504         $this->assertEquals('https://login.foo.com/login.php?login_attempt=1', $form->getUri(), '->getUri() returns absolute URIs set in the action form');
505
506         $form = $this->createForm($formHtml, null, 'https://www.foo.com/bar/');
507         $this->assertEquals('https://login.foo.com/login.php?login_attempt=1', $form->getUri(), '->getUri() returns absolute URIs set in the action form');
508     }
509
510     public function testGetUriAbsolute()
511     {
512         $form = $this->createForm('<form action="foo"><input type="submit" /></form>', null, 'http://localhost/foo/');
513         $this->assertEquals('http://localhost/foo/foo', $form->getUri(), '->getUri() returns absolute URIs');
514
515         $form = $this->createForm('<form action="/foo"><input type="submit" /></form>', null, 'http://localhost/foo/');
516         $this->assertEquals('http://localhost/foo', $form->getUri(), '->getUri() returns absolute URIs');
517     }
518
519     public function testGetUriWithOnlyQueryString()
520     {
521         $form = $this->createForm('<form action="?get=param"><input type="submit" /></form>', null, 'http://localhost/foo/bar');
522         $this->assertEquals('http://localhost/foo/bar?get=param', $form->getUri(), '->getUri() returns absolute URIs only if the host has been defined in the constructor');
523     }
524
525     public function testGetUriWithoutAction()
526     {
527         $form = $this->createForm('<form><input type="submit" /></form>', null, 'http://localhost/foo/bar');
528         $this->assertEquals('http://localhost/foo/bar', $form->getUri(), '->getUri() returns path if no action defined');
529     }
530
531     public function provideGetUriValues()
532     {
533         return array(
534             array(
535                 'returns the URI of the form',
536                 '<form action="/foo"><input type="submit" /></form>',
537                 array(),
538                 '/foo',
539             ),
540             array(
541                 'appends the form values if the method is get',
542                 '<form action="/foo"><input type="text" name="foo" value="foo" /><input type="submit" /></form>',
543                 array(),
544                 '/foo?foo=foo',
545             ),
546             array(
547                 'appends the form values and merges the submitted values',
548                 '<form action="/foo"><input type="text" name="foo" value="foo" /><input type="submit" /></form>',
549                 array('foo' => 'bar'),
550                 '/foo?foo=bar',
551             ),
552             array(
553                 'does not append values if the method is post',
554                 '<form action="/foo" method="post"><input type="text" name="foo" value="foo" /><input type="submit" /></form>',
555                 array(),
556                 '/foo',
557             ),
558             array(
559                 'does not append values if the method is patch',
560                 '<form action="/foo" method="post"><input type="text" name="foo" value="foo" /><input type="submit" /></form>',
561                 array(),
562                 '/foo',
563                 'PUT',
564             ),
565             array(
566                 'does not append values if the method is delete',
567                 '<form action="/foo" method="post"><input type="text" name="foo" value="foo" /><input type="submit" /></form>',
568                 array(),
569                 '/foo',
570                 'DELETE',
571             ),
572             array(
573                 'does not append values if the method is put',
574                 '<form action="/foo" method="post"><input type="text" name="foo" value="foo" /><input type="submit" /></form>',
575                 array(),
576                 '/foo',
577                 'PATCH',
578             ),
579             array(
580                 'appends the form values to an existing query string',
581                 '<form action="/foo?bar=bar"><input type="text" name="foo" value="foo" /><input type="submit" /></form>',
582                 array(),
583                 '/foo?bar=bar&foo=foo',
584             ),
585             array(
586                 'replaces query values with the form values',
587                 '<form action="/foo?bar=bar"><input type="text" name="bar" value="foo" /><input type="submit" /></form>',
588                 array(),
589                 '/foo?bar=foo',
590             ),
591             array(
592                 'returns an empty URI if the action is empty',
593                 '<form><input type="submit" /></form>',
594                 array(),
595                 '/',
596             ),
597             array(
598                 'appends the form values even if the action is empty',
599                 '<form><input type="text" name="foo" value="foo" /><input type="submit" /></form>',
600                 array(),
601                 '/?foo=foo',
602             ),
603             array(
604                 'chooses the path if the action attribute value is a sharp (#)',
605                 '<form action="#" method="post"><input type="text" name="foo" value="foo" /><input type="submit" /></form>',
606                 array(),
607                 '/#',
608             ),
609         );
610     }
611
612     public function testHas()
613     {
614         $form = $this->createForm('<form method="post"><input type="text" name="bar" value="bar" /><input type="submit" /></form>');
615
616         $this->assertFalse($form->has('foo'), '->has() returns false if a field is not in the form');
617         $this->assertTrue($form->has('bar'), '->has() returns true if a field is in the form');
618     }
619
620     public function testRemove()
621     {
622         $form = $this->createForm('<form method="post"><input type="text" name="bar" value="bar" /><input type="submit" /></form>');
623         $form->remove('bar');
624         $this->assertFalse($form->has('bar'), '->remove() removes a field');
625     }
626
627     public function testGet()
628     {
629         $form = $this->createForm('<form method="post"><input type="text" name="bar" value="bar" /><input type="submit" /></form>');
630
631         $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Field\\InputFormField', $form->get('bar'), '->get() returns the field object associated with the given name');
632
633         try {
634             $form->get('foo');
635             $this->fail('->get() throws an \InvalidArgumentException if the field does not exist');
636         } catch (\InvalidArgumentException $e) {
637             $this->assertTrue(true, '->get() throws an \InvalidArgumentException if the field does not exist');
638         }
639     }
640
641     public function testAll()
642     {
643         $form = $this->createForm('<form method="post"><input type="text" name="bar" value="bar" /><input type="submit" /></form>');
644
645         $fields = $form->all();
646         $this->assertCount(1, $fields, '->all() return an array of form field objects');
647         $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Field\\InputFormField', $fields['bar'], '->all() return an array of form field objects');
648     }
649
650     public function testSubmitWithoutAFormButton()
651     {
652         $dom = new \DOMDocument();
653         $dom->loadHTML('
654             <html>
655                 <form>
656                     <input type="foo" />
657                 </form>
658             </html>
659         ');
660
661         $nodes = $dom->getElementsByTagName('form');
662         $form = new Form($nodes->item(0), 'http://example.com');
663         $this->assertSame($nodes->item(0), $form->getFormNode(), '->getFormNode() returns the form node associated with this form');
664     }
665
666     public function testTypeAttributeIsCaseInsensitive()
667     {
668         $form = $this->createForm('<form method="post"><input type="IMAGE" name="example" /></form>');
669         $this->assertTrue($form->has('example.x'), '->has() returns true if the image input was correctly turned into an x and a y fields');
670         $this->assertTrue($form->has('example.y'), '->has() returns true if the image input was correctly turned into an x and a y fields');
671     }
672
673     public function testFormFieldRegistryAcceptAnyNames()
674     {
675         $field = $this->getFormFieldMock('[t:dbt%3adate;]data_daterange_enddate_value');
676
677         $registry = new FormFieldRegistry();
678         $registry->add($field);
679         $this->assertEquals($field, $registry->get('[t:dbt%3adate;]data_daterange_enddate_value'));
680         $registry->set('[t:dbt%3adate;]data_daterange_enddate_value', null);
681
682         $form = $this->createForm('<form><input type="text" name="[t:dbt%3adate;]data_daterange_enddate_value" value="bar" /><input type="submit" /></form>');
683         $form['[t:dbt%3adate;]data_daterange_enddate_value'] = 'bar';
684
685         $registry->remove('[t:dbt%3adate;]data_daterange_enddate_value');
686     }
687
688     /**
689      * @expectedException \InvalidArgumentException
690      */
691     public function testFormFieldRegistryGetThrowAnExceptionWhenTheFieldDoesNotExist()
692     {
693         $registry = new FormFieldRegistry();
694         $registry->get('foo');
695     }
696
697     /**
698      * @expectedException \InvalidArgumentException
699      */
700     public function testFormFieldRegistrySetThrowAnExceptionWhenTheFieldDoesNotExist()
701     {
702         $registry = new FormFieldRegistry();
703         $registry->set('foo', null);
704     }
705
706     public function testFormFieldRegistryHasReturnsTrueWhenTheFQNExists()
707     {
708         $registry = new FormFieldRegistry();
709         $registry->add($this->getFormFieldMock('foo[bar]'));
710
711         $this->assertTrue($registry->has('foo'));
712         $this->assertTrue($registry->has('foo[bar]'));
713         $this->assertFalse($registry->has('bar'));
714         $this->assertFalse($registry->has('foo[foo]'));
715     }
716
717     public function testFormRegistryFieldsCanBeRemoved()
718     {
719         $registry = new FormFieldRegistry();
720         $registry->add($this->getFormFieldMock('foo'));
721         $registry->remove('foo');
722         $this->assertFalse($registry->has('foo'));
723     }
724
725     public function testFormRegistrySupportsMultivaluedFields()
726     {
727         $registry = new FormFieldRegistry();
728         $registry->add($this->getFormFieldMock('foo[]'));
729         $registry->add($this->getFormFieldMock('foo[]'));
730         $registry->add($this->getFormFieldMock('bar[5]'));
731         $registry->add($this->getFormFieldMock('bar[]'));
732         $registry->add($this->getFormFieldMock('bar[baz]'));
733
734         $this->assertEquals(
735             array('foo[0]', 'foo[1]', 'bar[5]', 'bar[6]', 'bar[baz]'),
736             array_keys($registry->all())
737         );
738     }
739
740     public function testFormRegistrySetValues()
741     {
742         $registry = new FormFieldRegistry();
743         $registry->add($f2 = $this->getFormFieldMock('foo[2]'));
744         $registry->add($f3 = $this->getFormFieldMock('foo[3]'));
745         $registry->add($fbb = $this->getFormFieldMock('foo[bar][baz]'));
746
747         $f2
748             ->expects($this->exactly(2))
749             ->method('setValue')
750             ->with(2)
751         ;
752
753         $f3
754             ->expects($this->exactly(2))
755             ->method('setValue')
756             ->with(3)
757         ;
758
759         $fbb
760             ->expects($this->exactly(2))
761             ->method('setValue')
762             ->with('fbb')
763         ;
764
765         $registry->set('foo[2]', 2);
766         $registry->set('foo[3]', 3);
767         $registry->set('foo[bar][baz]', 'fbb');
768
769         $registry->set('foo', array(
770             2 => 2,
771             3 => 3,
772             'bar' => array(
773                 'baz' => 'fbb',
774              ),
775         ));
776     }
777
778     /**
779      * @expectedException \InvalidArgumentException
780      * @expectedExceptionMessage Cannot set value on a compound field "foo[bar]".
781      */
782     public function testFormRegistrySetValueOnCompoundField()
783     {
784         $registry = new FormFieldRegistry();
785         $registry->add($this->getFormFieldMock('foo[bar][baz]'));
786
787         $registry->set('foo[bar]', 'fbb');
788     }
789
790     /**
791      * @expectedException \InvalidArgumentException
792      * @expectedExceptionMessage Unreachable field "0"
793      */
794     public function testFormRegistrySetArrayOnNotCompoundField()
795     {
796         $registry = new FormFieldRegistry();
797         $registry->add($this->getFormFieldMock('bar'));
798
799         $registry->set('bar', array('baz'));
800     }
801
802     public function testDifferentFieldTypesWithSameName()
803     {
804         $dom = new \DOMDocument();
805         $dom->loadHTML('
806             <html>
807                 <body>
808                     <form action="/">
809                         <input type="hidden" name="option" value="default">
810                         <input type="radio" name="option" value="A">
811                         <input type="radio" name="option" value="B">
812                         <input type="hidden" name="settings[1]" value="0">
813                         <input type="checkbox" name="settings[1]" value="1" id="setting-1">
814                         <button>klickme</button>
815                     </form>
816                 </body>
817             </html>
818         ');
819         $form = new Form($dom->getElementsByTagName('form')->item(0), 'http://example.com');
820
821         $this->assertInstanceOf('Symfony\Component\DomCrawler\Field\ChoiceFormField', $form->get('option'));
822     }
823
824     protected function getFormFieldMock($name, $value = null)
825     {
826         $field = $this
827             ->getMockBuilder('Symfony\\Component\\DomCrawler\\Field\\FormField')
828             ->setMethods(array('getName', 'getValue', 'setValue', 'initialize'))
829             ->disableOriginalConstructor()
830             ->getMock()
831         ;
832
833         $field
834             ->expects($this->any())
835             ->method('getName')
836             ->will($this->returnValue($name))
837         ;
838
839         $field
840             ->expects($this->any())
841             ->method('getValue')
842             ->will($this->returnValue($value))
843         ;
844
845         return $field;
846     }
847
848     protected function createForm($form, $method = null, $currentUri = null)
849     {
850         $dom = new \DOMDocument();
851         $dom->loadHTML('<html>'.$form.'</html>');
852
853         $xPath = new \DOMXPath($dom);
854         $nodes = $xPath->query('//input | //button');
855
856         if (null === $currentUri) {
857             $currentUri = 'http://example.com/';
858         }
859
860         return new Form($nodes->item($nodes->length - 1), $currentUri, $method);
861     }
862
863     protected function createTestHtml5Form()
864     {
865         $dom = new \DOMDocument();
866         $dom->loadHTML('
867         <html>
868             <h1>Hello form</h1>
869             <form id="form-1" action="" method="POST">
870                 <div><input type="checkbox" name="apples[]" value="1" checked /></div>
871                 <input form="form_2" type="checkbox" name="oranges[]" value="1" checked />
872                 <div><label></label><input form="form-1" type="hidden" name="form_name" value="form-1" /></div>
873                 <input form="form-1" type="submit" name="button_1" value="Capture fields" />
874                 <button form="form_2" type="submit" name="button_2">Submit form_2</button>
875             </form>
876             <input form="form-1" type="checkbox" name="apples[]" value="2" checked />
877             <form id="form_2" action="" method="POST">
878                 <div><div><input type="checkbox" name="oranges[]" value="2" checked />
879                 <input type="checkbox" name="oranges[]" value="3" checked /></div></div>
880                 <input form="form_2" type="hidden" name="form_name" value="form_2" />
881                 <input form="form-1" type="hidden" name="outer_field" value="success" />
882                 <button form="form-1" type="submit" name="button_3">Submit from outside the form</button>
883                 <div>
884                     <label for="app_frontend_form_type_contact_form_type_contactType">Message subject</label>
885                     <div>
886                         <select name="app_frontend_form_type_contact_form_type[contactType]" id="app_frontend_form_type_contact_form_type_contactType"><option selected="selected" value="">Please select subject</option><option id="1">Test type</option></select>
887                     </div>
888                 </div>
889                 <div>
890                     <label for="app_frontend_form_type_contact_form_type_firstName">Firstname</label>
891                     <input type="text" name="app_frontend_form_type_contact_form_type[firstName]" value="John" id="app_frontend_form_type_contact_form_type_firstName"/>
892                 </div>
893             </form>
894             <button />
895         </html>');
896
897         return $dom;
898     }
899
900     protected function createTestMultipleForm()
901     {
902         $dom = new \DOMDocument();
903         $dom->loadHTML('
904         <html>
905             <h1>Hello form</h1>
906             <form action="" method="POST">
907                 <div><input type="checkbox" name="apples[]" value="1" checked /></div>
908                 <input type="checkbox" name="oranges[]" value="1" checked />
909                 <div><label></label><input type="hidden" name="form_name" value="form-1" /></div>
910                 <input type="submit" name="button_1" value="Capture fields" />
911                 <button type="submit" name="button_2">Submit form_2</button>
912             </form>
913             <form action="" method="POST">
914                 <div><div><input type="checkbox" name="oranges[]" value="2" checked />
915                 <input type="checkbox" name="oranges[]" value="3" checked /></div></div>
916                 <input type="hidden" name="form_name" value="form_2" />
917                 <input type="hidden" name="outer_field" value="success" />
918                 <button type="submit" name="button_3">Submit from outside the form</button>
919             </form>
920             <button />
921         </html>');
922
923         return $dom;
924     }
925
926     public function testgetPhpValuesWithEmptyTextarea()
927     {
928         $dom = new \DOMDocument();
929         $dom->loadHTML('
930               <html>
931                   <form>
932                       <textarea name="example"></textarea>
933                   </form>
934               </html>
935           ');
936
937         $nodes = $dom->getElementsByTagName('form');
938         $form = new Form($nodes->item(0), 'http://example.com');
939         $this->assertEquals($form->getPhpValues(), array('example' => ''));
940     }
941 }