FormTest.php 43 KB

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