FormTest.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  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\Tests\Component\Form;
  11. require_once __DIR__.'/Fixtures/FixedDataTransformer.php';
  12. require_once __DIR__.'/Fixtures/FixedFilterListener.php';
  13. use Symfony\Component\Form\Form;
  14. use Symfony\Component\Form\FormBuilder;
  15. use Symfony\Component\Form\FormError;
  16. use Symfony\Component\Form\DataTransformer\TransformationFailedException;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpFoundation\File\UploadedFile;
  19. use Symfony\Component\EventDispatcher\EventDispatcher;
  20. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  21. use Symfony\Tests\Component\Form\Fixtures\FixedDataTransformer;
  22. use Symfony\Tests\Component\Form\Fixtures\FixedFilterListener;
  23. class FormTest extends \PHPUnit_Framework_TestCase
  24. {
  25. private $dispatcher;
  26. private $builder;
  27. private $form;
  28. protected function setUp()
  29. {
  30. $this->dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
  31. $this->form = $this->getBuilder()->getForm();
  32. }
  33. /**
  34. * @expectedException Symfony\Component\Form\Exception\UnexpectedTypeException
  35. */
  36. public function testConstructExpectsValidValidators()
  37. {
  38. $validators = array(new \stdClass());
  39. new Form('name', $this->dispatcher, array(), null, null, null, $validators);
  40. }
  41. public function testDataIsInitializedEmpty()
  42. {
  43. $norm = new FixedDataTransformer(array(
  44. '' => 'foo',
  45. ));
  46. $client = new FixedDataTransformer(array(
  47. 'foo' => 'bar',
  48. ));
  49. $form = new Form('name', $this->dispatcher, array(), $client, $norm);
  50. $this->assertNull($form->getData());
  51. $this->assertSame('foo', $form->getNormData());
  52. $this->assertSame('bar', $form->getClientData());
  53. }
  54. public function testErrorsBubbleUpIfEnabled()
  55. {
  56. $error = new FormError('Error!');
  57. $parent = $this->form;
  58. $form = $this->getBuilder()->setErrorBubbling(true)->getForm();
  59. $form->setParent($parent);
  60. $form->addError($error);
  61. $this->assertEquals(array(), $form->getErrors());
  62. $this->assertEquals(array($error), $parent->getErrors());
  63. }
  64. public function testErrorsDontBubbleUpIfDisabled()
  65. {
  66. $error = new FormError('Error!');
  67. $parent = $this->form;
  68. $form = $this->getBuilder()->setErrorBubbling(false)->getForm();
  69. $form->setParent($parent);
  70. $form->addError($error);
  71. $this->assertEquals(array($error), $form->getErrors());
  72. $this->assertEquals(array(), $parent->getErrors());
  73. }
  74. public function testValidIfAllChildrenAreValid()
  75. {
  76. $this->form->add($this->getValidForm('firstName'));
  77. $this->form->add($this->getValidForm('lastName'));
  78. $this->form->bind(array(
  79. 'firstName' => 'Bernhard',
  80. 'lastName' => 'Schussek',
  81. ));
  82. $this->assertTrue($this->form->isValid());
  83. }
  84. public function testInvalidIfChildrenIsInvalid()
  85. {
  86. $this->form->add($this->getValidForm('firstName'));
  87. $this->form->add($this->getInvalidForm('lastName'));
  88. $this->form->bind(array(
  89. 'firstName' => 'Bernhard',
  90. 'lastName' => 'Schussek',
  91. ));
  92. $this->assertFalse($this->form->isValid());
  93. }
  94. public function testBind()
  95. {
  96. $child = $this->getMockForm('firstName');
  97. $this->form->add($child);
  98. $child->expects($this->once())
  99. ->method('bind')
  100. ->with($this->equalTo('Bernhard'));
  101. $this->form->bind(array('firstName' => 'Bernhard'));
  102. $this->assertEquals(array('firstName' => 'Bernhard'), $this->form->getData());
  103. }
  104. public function testBindForwardsNullIfValueIsMissing()
  105. {
  106. $child = $this->getMockForm('firstName');
  107. $this->form->add($child);
  108. $child->expects($this->once())
  109. ->method('bind')
  110. ->with($this->equalTo(null));
  111. $this->form->bind(array());
  112. }
  113. public function testBindIsIgnoredIfReadOnly()
  114. {
  115. $form = $this->getBuilder()
  116. ->setReadOnly(true)
  117. ->setData('initial')
  118. ->getForm();
  119. $form->bind('new');
  120. $this->assertEquals('initial', $form->getData());
  121. }
  122. public function testNeverRequiredIfParentNotRequired()
  123. {
  124. $parent = $this->getBuilder()->setRequired(false)->getForm();
  125. $child = $this->getBuilder()->setRequired(true)->getForm();
  126. $child->setParent($parent);
  127. $this->assertFalse($child->isRequired());
  128. }
  129. public function testRequired()
  130. {
  131. $parent = $this->getBuilder()->setRequired(true)->getForm();
  132. $child = $this->getBuilder()->setRequired(true)->getForm();
  133. $child->setParent($parent);
  134. $this->assertTrue($child->isRequired());
  135. }
  136. public function testNotRequired()
  137. {
  138. $parent = $this->getBuilder()->setRequired(true)->getForm();
  139. $child = $this->getBuilder()->setRequired(false)->getForm();
  140. $child->setParent($parent);
  141. $this->assertFalse($child->isRequired());
  142. }
  143. public function testAlwaysReadOnlyIfParentReadOnly()
  144. {
  145. $parent = $this->getBuilder()->setReadOnly(true)->getForm();
  146. $child = $this->getBuilder()->setReadOnly(false)->getForm();
  147. $child->setParent($parent);
  148. $this->assertTrue($child->isReadOnly());
  149. }
  150. public function testReadOnly()
  151. {
  152. $parent = $this->getBuilder()->setReadOnly(false)->getForm();
  153. $child = $this->getBuilder()->setReadOnly(true)->getForm();
  154. $child->setParent($parent);
  155. $this->assertTrue($child->isReadOnly());
  156. }
  157. public function testNotReadOnly()
  158. {
  159. $parent = $this->getBuilder()->setReadOnly(false)->getForm();
  160. $child = $this->getBuilder()->setReadOnly(false)->getForm();
  161. $child->setParent($parent);
  162. $this->assertFalse($child->isReadOnly());
  163. }
  164. public function testCloneChildren()
  165. {
  166. $child = $this->getBuilder('child')->getForm();
  167. $this->form->add($child);
  168. $clone = clone $this->form;
  169. $this->assertNotSame($this->form, $clone);
  170. $this->assertNotSame($child, $clone['child']);
  171. }
  172. public function testGetRootReturnsRootOfParent()
  173. {
  174. $parent = $this->getMockForm();
  175. $parent->expects($this->once())
  176. ->method('getRoot')
  177. ->will($this->returnValue('ROOT'));
  178. $this->form->setParent($parent);
  179. $this->assertEquals('ROOT', $this->form->getRoot());
  180. }
  181. public function testGetRootReturnsSelfIfNoParent()
  182. {
  183. $this->assertSame($this->form, $this->form->getRoot());
  184. }
  185. public function testIsEmptyIfEmptyArray()
  186. {
  187. $this->form->setData(array());
  188. $this->assertTrue($this->form->isEmpty());
  189. }
  190. public function testIsEmptyIfNull()
  191. {
  192. $this->form->setData(null);
  193. $this->assertTrue($this->form->isEmpty());
  194. }
  195. public function testIsEmptyIfEmptyString()
  196. {
  197. $this->form->setData('');
  198. $this->assertTrue($this->form->isEmpty());
  199. }
  200. public function testIsNotEmptyIfText()
  201. {
  202. $this->form->setData('foobar');
  203. $this->assertFalse($this->form->isEmpty());
  204. }
  205. public function testIsNotEmptyIfChildNotEmpty()
  206. {
  207. $child = $this->getMockForm();
  208. $child->expects($this->once())
  209. ->method('isEmpty')
  210. ->will($this->returnValue(false));
  211. $this->form->setData(null);
  212. $this->form->add($child);
  213. $this->assertFalse($this->form->isEmpty());
  214. }
  215. public function testValidIfBound()
  216. {
  217. $this->form->bind('foobar');
  218. $this->assertTrue($this->form->isValid());
  219. }
  220. public function testNotValidIfNotBound()
  221. {
  222. $this->assertFalse($this->form->isValid());
  223. }
  224. public function testNotValidIfErrors()
  225. {
  226. $this->form->bind('foobar');
  227. $this->form->addError(new FormError('Error!'));
  228. $this->assertFalse($this->form->isValid());
  229. }
  230. public function testNotValidIfChildNotValid()
  231. {
  232. $child = $this->getMockForm();
  233. $child->expects($this->once())
  234. ->method('isValid')
  235. ->will($this->returnValue(false));
  236. $this->form->bind('foobar');
  237. $this->form->add($child);
  238. $this->assertFalse($this->form->isValid());
  239. }
  240. public function testHasErrors()
  241. {
  242. $this->form->addError(new FormError('Error!'));
  243. $this->assertTrue($this->form->hasErrors());
  244. }
  245. public function testHasNoErrors()
  246. {
  247. $this->assertFalse($this->form->hasErrors());
  248. }
  249. public function testHasChildren()
  250. {
  251. $this->form->add($this->getBuilder()->getForm());
  252. $this->assertTrue($this->form->hasChildren());
  253. }
  254. public function testHasNoChildren()
  255. {
  256. $this->assertFalse($this->form->hasChildren());
  257. }
  258. public function testAdd()
  259. {
  260. $child = $this->getBuilder('foo')->getForm();
  261. $this->form->add($child);
  262. $this->assertSame($this->form, $child->getParent());
  263. $this->assertSame(array('foo' => $child), $this->form->getChildren());
  264. }
  265. public function testRemove()
  266. {
  267. $child = $this->getBuilder('foo')->getForm();
  268. $this->form->add($child);
  269. $this->form->remove('foo');
  270. $this->assertNull($child->getParent());
  271. $this->assertFalse($this->form->hasChildren());
  272. }
  273. public function testRemoveIgnoresUnknownName()
  274. {
  275. $this->form->remove('notexisting');
  276. }
  277. public function testArrayAccess()
  278. {
  279. $child = $this->getBuilder('foo')->getForm();
  280. $this->form[] = $child;
  281. $this->assertTrue(isset($this->form['foo']));
  282. $this->assertSame($child, $this->form['foo']);
  283. unset($this->form['foo']);
  284. $this->assertFalse(isset($this->form['foo']));
  285. }
  286. public function testCountable()
  287. {
  288. $this->form->add($this->getBuilder('foo')->getForm());
  289. $this->form->add($this->getBuilder('bar')->getForm());
  290. $this->assertEquals(2, count($this->form));
  291. }
  292. public function testIterator()
  293. {
  294. $this->form->add($this->getBuilder('foo')->getForm());
  295. $this->form->add($this->getBuilder('bar')->getForm());
  296. $this->assertSame($this->form->getChildren(), iterator_to_array($this->form));
  297. }
  298. public function testIsBound()
  299. {
  300. $this->form->bind('foobar');
  301. $this->assertTrue($this->form->isBound());
  302. }
  303. public function testIsNotBound()
  304. {
  305. $this->assertFalse($this->form->isBound());
  306. }
  307. public function testSetDataExecutesTransformationChain()
  308. {
  309. // use real event dispatcher now
  310. $form = $this->getBuilder('name', new EventDispatcher())
  311. ->addEventSubscriber(new FixedFilterListener(array(
  312. 'filterSetData' => array(
  313. 'app' => 'filtered',
  314. ),
  315. )))
  316. ->setNormTransformer(new FixedDataTransformer(array(
  317. '' => '',
  318. 'filtered' => 'norm',
  319. )))
  320. ->setClientTransformer(new FixedDataTransformer(array(
  321. '' => '',
  322. 'norm' => 'client',
  323. )))
  324. ->getForm();
  325. $form->setData('app');
  326. $this->assertEquals('filtered', $form->getData());
  327. $this->assertEquals('norm', $form->getNormData());
  328. $this->assertEquals('client', $form->getClientData());
  329. }
  330. public function testBindExecutesTransformationChain()
  331. {
  332. // use real event dispatcher now
  333. $form = $this->getBuilder('name', new EventDispatcher())
  334. ->addEventSubscriber(new FixedFilterListener(array(
  335. 'filterBoundClientData' => array(
  336. 'client' => 'filteredclient',
  337. ),
  338. 'filterBoundNormData' => array(
  339. 'norm' => 'filterednorm',
  340. ),
  341. )))
  342. ->setClientTransformer(new FixedDataTransformer(array(
  343. '' => '',
  344. // direction is reversed!
  345. 'norm' => 'filteredclient',
  346. 'filterednorm' => 'cleanedclient'
  347. )))
  348. ->setNormTransformer(new FixedDataTransformer(array(
  349. '' => '',
  350. // direction is reversed!
  351. 'app' => 'filterednorm',
  352. )))
  353. ->getForm();
  354. $form->setData('app');
  355. $this->assertEquals('app', $form->getData());
  356. $this->assertEquals('filterednorm', $form->getNormData());
  357. $this->assertEquals('cleanedclient', $form->getClientData());
  358. }
  359. public function testIsSynchronizedByDefault()
  360. {
  361. $this->assertTrue($this->form->isSynchronized());
  362. }
  363. public function testIsSynchronizedAfterBinding()
  364. {
  365. $this->form->bind('foobar');
  366. $this->assertTrue($this->form->isSynchronized());
  367. }
  368. public function testIsNotSynchronizedIfTransformationFailed()
  369. {
  370. $transformer = $this->getDataTransformer();
  371. $transformer->expects($this->once())
  372. ->method('reverseTransform')
  373. ->will($this->throwException(new TransformationFailedException()));
  374. $form = $this->getBuilder()
  375. ->setClientTransformer($transformer)
  376. ->getForm();
  377. $form->bind('foobar');
  378. $this->assertFalse($form->isSynchronized());
  379. }
  380. public function testEmptyDataCreatedBeforeTransforming()
  381. {
  382. $form = $this->getBuilder()
  383. ->setEmptyData('foo')
  384. ->setClientTransformer(new FixedDataTransformer(array(
  385. '' => '',
  386. // direction is reversed!
  387. 'bar' => 'foo',
  388. )))
  389. ->getForm();
  390. $form->bind('');
  391. $this->assertEquals('bar', $form->getData());
  392. }
  393. public function testEmptyDataFromClosure()
  394. {
  395. $test = $this;
  396. $form = $this->getBuilder()
  397. ->setEmptyData(function ($form) use ($test) {
  398. // the form instance is passed to the closure to allow use
  399. // of form data when creating the empty value
  400. $test->assertInstanceOf('Symfony\Component\Form\FormInterface', $form);
  401. return 'foo';
  402. })
  403. ->setClientTransformer(new FixedDataTransformer(array(
  404. '' => '',
  405. // direction is reversed!
  406. 'bar' => 'foo',
  407. )))
  408. ->getForm();
  409. $form->bind('');
  410. $this->assertEquals('bar', $form->getData());
  411. }
  412. public function testAddMapsClientDataToForm()
  413. {
  414. $mapper = $this->getDataMapper();
  415. $form = $this->getBuilder()
  416. ->setDataMapper($mapper)
  417. ->setClientTransformer(new FixedDataTransformer(array(
  418. '' => '',
  419. 'foo' => 'bar',
  420. )))
  421. ->setData('foo')
  422. ->getForm();
  423. $child = $this->getBuilder()->getForm();
  424. $mapper->expects($this->once())
  425. ->method('mapDataToForm')
  426. ->with('bar', $child);
  427. $form->add($child);
  428. }
  429. public function testSetDataMapsClientDataToChildren()
  430. {
  431. $mapper = $this->getDataMapper();
  432. $form = $this->getBuilder()
  433. ->setDataMapper($mapper)
  434. ->setClientTransformer(new FixedDataTransformer(array(
  435. '' => '',
  436. 'foo' => 'bar',
  437. )))
  438. ->getForm();
  439. $form->add($child1 = $this->getBuilder('firstName')->getForm());
  440. $form->add($child2 = $this->getBuilder('lastName')->getForm());
  441. $mapper->expects($this->once())
  442. ->method('mapDataToForms')
  443. ->with('bar', array('firstName' => $child1, 'lastName' => $child2));
  444. $form->setData('foo');
  445. }
  446. public function testBindMapsBoundChildrenOntoExistingClientData()
  447. {
  448. $test = $this;
  449. $mapper = $this->getDataMapper();
  450. $form = $this->getBuilder()
  451. ->setDataMapper($mapper)
  452. ->setClientTransformer(new FixedDataTransformer(array(
  453. '' => '',
  454. 'foo' => 'bar',
  455. )))
  456. ->setData('foo')
  457. ->getForm();
  458. $form->add($child1 = $this->getBuilder('firstName')->getForm());
  459. $form->add($child2 = $this->getBuilder('lastName')->getForm());
  460. $mapper->expects($this->once())
  461. ->method('mapFormsToData')
  462. ->with(array('firstName' => $child1, 'lastName' => $child2), 'bar')
  463. ->will($this->returnCallback(function ($children, $bar) use ($test) {
  464. $test->assertEquals('Bernhard', $children['firstName']->getData());
  465. $test->assertEquals('Schussek', $children['lastName']->getData());
  466. }));
  467. $form->bind(array(
  468. 'firstName' => 'Bernhard',
  469. 'lastName' => 'Schussek',
  470. ));
  471. }
  472. public function testBindMapsBoundChildrenOntoEmptyData()
  473. {
  474. $test = $this;
  475. $mapper = $this->getDataMapper();
  476. $object = new \stdClass();
  477. $form = $this->getBuilder()
  478. ->setDataMapper($mapper)
  479. ->setEmptyData($object)
  480. ->setData(null)
  481. ->getForm();
  482. $form->add($child = $this->getBuilder('name')->getForm());
  483. $mapper->expects($this->once())
  484. ->method('mapFormsToData')
  485. ->with(array('name' => $child), $object);
  486. $form->bind(array(
  487. 'name' => 'Bernhard',
  488. ));
  489. }
  490. public function testBindValidatesAfterTransformation()
  491. {
  492. $test = $this;
  493. $validator = $this->getFormValidator();
  494. $form = $this->getBuilder()
  495. ->addValidator($validator)
  496. ->getForm();
  497. $validator->expects($this->once())
  498. ->method('validate')
  499. ->with($form)
  500. ->will($this->returnCallback(function ($form) use ($test) {
  501. $test->assertEquals('foobar', $form->getData());
  502. }));
  503. $form->bind('foobar');
  504. }
  505. public function requestMethodProvider()
  506. {
  507. return array(
  508. array('POST'),
  509. array('PUT'),
  510. );
  511. }
  512. /**
  513. * @dataProvider requestMethodProvider
  514. */
  515. public function testBindPostOrPutRequest($method)
  516. {
  517. $path = tempnam(sys_get_temp_dir(), 'sf2');
  518. touch($path);
  519. $values = array(
  520. 'author' => array(
  521. 'name' => 'Bernhard',
  522. 'image' => array('filename' => 'foobar.png'),
  523. ),
  524. );
  525. $files = array(
  526. 'author' => array(
  527. 'error' => array('image' => UPLOAD_ERR_OK),
  528. 'name' => array('image' => 'upload.png'),
  529. 'size' => array('image' => 123),
  530. 'tmp_name' => array('image' => $path),
  531. 'type' => array('image' => 'image/png'),
  532. ),
  533. );
  534. $request = new Request(array(), $values, array(), array(), $files, array(
  535. 'REQUEST_METHOD' => $method,
  536. ));
  537. $form = $this->getBuilder('author')->getForm();
  538. $form->add($this->getBuilder('name')->getForm());
  539. $form->add($this->getBuilder('image')->getForm());
  540. $form->bindRequest($request);
  541. $file = new UploadedFile($path, 'upload.png', 'image/png', 123, UPLOAD_ERR_OK);
  542. $this->assertEquals('Bernhard', $form['name']->getData());
  543. $this->assertEquals($file, $form['image']->getData());
  544. unlink($path);
  545. }
  546. public function testBindGetRequest()
  547. {
  548. $values = array(
  549. 'author' => array(
  550. 'firstName' => 'Bernhard',
  551. 'lastName' => 'Schussek',
  552. ),
  553. );
  554. $request = new Request($values, array(), array(), array(), array(), array(
  555. 'REQUEST_METHOD' => 'GET',
  556. ));
  557. $form = $this->getBuilder('author')->getForm();
  558. $form->add($this->getBuilder('firstName')->getForm());
  559. $form->add($this->getBuilder('lastName')->getForm());
  560. $form->bindRequest($request);
  561. $this->assertEquals('Bernhard', $form['firstName']->getData());
  562. $this->assertEquals('Schussek', $form['lastName']->getData());
  563. }
  564. protected function getBuilder($name = 'name', EventDispatcherInterface $dispatcher = null)
  565. {
  566. return new FormBuilder($name, $dispatcher ?: $this->dispatcher);
  567. }
  568. protected function getMockForm($name = 'name')
  569. {
  570. $form = $this->getMock('Symfony\Tests\Component\Form\FormInterface');
  571. $form->expects($this->any())
  572. ->method('getName')
  573. ->will($this->returnValue($name));
  574. return $form;
  575. }
  576. protected function getValidForm($name)
  577. {
  578. $form = $this->getMockForm($name);
  579. $form->expects($this->any())
  580. ->method('isValid')
  581. ->will($this->returnValue(true));
  582. return $form;
  583. }
  584. protected function getInvalidForm($name)
  585. {
  586. $form = $this->getMockForm($name);
  587. $form->expects($this->any())
  588. ->method('isValid')
  589. ->will($this->returnValue(false));
  590. return $form;
  591. }
  592. protected function getDataMapper()
  593. {
  594. return $this->getMock('Symfony\Component\Form\DataMapper\DataMapperInterface');
  595. }
  596. protected function getDataTransformer()
  597. {
  598. return $this->getMock('Symfony\Component\Form\DataTransformer\DataTransformerInterface');
  599. }
  600. protected function getFormValidator()
  601. {
  602. return $this->getMock('Symfony\Component\Form\Validator\FormValidatorInterface');
  603. }
  604. }