FormTest.php 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien.potencier@symfony-project.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/Author.php';
  12. require_once __DIR__ . '/Fixtures/TestField.php';
  13. require_once __DIR__ . '/Fixtures/TestForm.php';
  14. use Symfony\Component\Form\Form;
  15. use Symfony\Component\Form\FormContext;
  16. use Symfony\Component\Form\Field;
  17. use Symfony\Component\Form\FieldError;
  18. use Symfony\Component\Form\DataError;
  19. use Symfony\Component\Form\HiddenField;
  20. use Symfony\Component\Form\PropertyPath;
  21. use Symfony\Component\HttpFoundation\Request;
  22. use Symfony\Component\HttpFoundation\File\UploadedFile;
  23. use Symfony\Component\Validator\ConstraintViolation;
  24. use Symfony\Component\Validator\ConstraintViolationList;
  25. use Symfony\Component\Validator\ExecutionContext;
  26. use Symfony\Tests\Component\Form\Fixtures\Author;
  27. use Symfony\Tests\Component\Form\Fixtures\TestField;
  28. use Symfony\Tests\Component\Form\Fixtures\TestForm;
  29. class FormTest_PreconfiguredForm extends Form
  30. {
  31. protected function configure()
  32. {
  33. $this->add(new Field('firstName'));
  34. parent::configure();
  35. }
  36. }
  37. // behaves like a form with a value transformer that transforms into
  38. // a specific format
  39. class FormTest_FormThatReturns extends Form
  40. {
  41. protected $returnValue;
  42. public function setReturnValue($returnValue)
  43. {
  44. $this->returnValue = $returnValue;
  45. }
  46. public function setData($data)
  47. {
  48. }
  49. public function getData()
  50. {
  51. return $this->returnValue;
  52. }
  53. }
  54. class FormTest_AuthorWithoutRefSetter
  55. {
  56. protected $reference;
  57. protected $referenceCopy;
  58. public function __construct($reference)
  59. {
  60. $this->reference = $reference;
  61. $this->referenceCopy = $reference;
  62. }
  63. // The returned object should be modified by reference without having
  64. // to provide a setReference() method
  65. public function getReference()
  66. {
  67. return $this->reference;
  68. }
  69. // The returned object is a copy, so setReferenceCopy() must be used
  70. // to update it
  71. public function getReferenceCopy()
  72. {
  73. return is_object($this->referenceCopy) ? clone $this->referenceCopy : $this->referenceCopy;
  74. }
  75. public function setReferenceCopy($reference)
  76. {
  77. $this->referenceCopy = $reference;
  78. }
  79. }
  80. class TestSetDataBeforeConfigureForm extends Form
  81. {
  82. protected $testCase;
  83. protected $object;
  84. public function __construct($testCase, $name, $object, $validator)
  85. {
  86. $this->testCase = $testCase;
  87. $this->object = $object;
  88. parent::__construct($name, $object, $validator);
  89. }
  90. protected function configure()
  91. {
  92. $this->testCase->assertEquals($this->object, $this->getData());
  93. parent::configure();
  94. }
  95. }
  96. class FormTest extends \PHPUnit_Framework_TestCase
  97. {
  98. protected $validator;
  99. protected $form;
  100. public static function setUpBeforeClass()
  101. {
  102. @session_start();
  103. }
  104. protected function setUp()
  105. {
  106. $this->validator = $this->createMockValidator();
  107. $this->form = new Form('author', array('validator' => $this->validator));
  108. }
  109. public function testNoCsrfProtectionByDefault()
  110. {
  111. $form = new Form('author');
  112. $this->assertFalse($form->isCsrfProtected());
  113. }
  114. public function testCsrfProtectionCanBeEnabled()
  115. {
  116. $form = new Form('author', array(
  117. 'csrf_provider' => $this->createMockCsrfProvider(),
  118. ));
  119. $this->assertTrue($form->isCsrfProtected());
  120. }
  121. public function testCsrfFieldNameCanBeSet()
  122. {
  123. $form = new Form('author', array(
  124. 'csrf_provider' => $this->createMockCsrfProvider(),
  125. 'csrf_field_name' => 'foobar',
  126. ));
  127. $this->assertEquals('foobar', $form->getCsrfFieldName());
  128. }
  129. public function testCsrfProtectedFormsHaveExtraField()
  130. {
  131. $provider = $this->createMockCsrfProvider();
  132. $provider->expects($this->once())
  133. ->method('generateCsrfToken')
  134. ->with($this->equalTo('Symfony\Component\Form\Form'))
  135. ->will($this->returnValue('ABCDEF'));
  136. $form = new Form('author', array(
  137. 'csrf_provider' => $provider,
  138. ));
  139. $this->assertTrue($form->has($this->form->getCsrfFieldName()));
  140. $field = $form->get($form->getCsrfFieldName());
  141. $this->assertTrue($field instanceof HiddenField);
  142. $this->assertEquals('ABCDEF', $field->getDisplayedData());
  143. }
  144. public function testIsCsrfTokenValidPassesIfCsrfProtectionIsDisabled()
  145. {
  146. $this->form->submit(array());
  147. $this->assertTrue($this->form->isCsrfTokenValid());
  148. }
  149. public function testIsCsrfTokenValidPasses()
  150. {
  151. $provider = $this->createMockCsrfProvider();
  152. $provider->expects($this->once())
  153. ->method('isCsrfTokenValid')
  154. ->with($this->equalTo('Symfony\Component\Form\Form'), $this->equalTo('ABCDEF'))
  155. ->will($this->returnValue(true));
  156. $form = new Form('author', array(
  157. 'csrf_provider' => $provider,
  158. 'validator' => $this->validator,
  159. ));
  160. $field = $form->getCsrfFieldName();
  161. $form->submit(array($field => 'ABCDEF'));
  162. $this->assertTrue($form->isCsrfTokenValid());
  163. }
  164. public function testIsCsrfTokenValidFails()
  165. {
  166. $provider = $this->createMockCsrfProvider();
  167. $provider->expects($this->once())
  168. ->method('isCsrfTokenValid')
  169. ->with($this->equalTo('Symfony\Component\Form\Form'), $this->equalTo('ABCDEF'))
  170. ->will($this->returnValue(false));
  171. $form = new Form('author', array(
  172. 'csrf_provider' => $provider,
  173. 'validator' => $this->validator,
  174. ));
  175. $field = $form->getCsrfFieldName();
  176. $form->submit(array($field => 'ABCDEF'));
  177. $this->assertFalse($form->isCsrfTokenValid());
  178. }
  179. public function testGetValidator()
  180. {
  181. $this->assertSame($this->validator, $this->form->getValidator());
  182. }
  183. public function testValidationGroupNullByDefault()
  184. {
  185. $this->assertNull($this->form->getValidationGroups());
  186. }
  187. public function testValidationGroupsCanBeSetToString()
  188. {
  189. $form = new Form('author', array(
  190. 'validation_groups' => 'group',
  191. ));
  192. $this->assertEquals(array('group'), $form->getValidationGroups());
  193. }
  194. public function testValidationGroupsCanBeSetToArray()
  195. {
  196. $form = new Form('author', array(
  197. 'validation_groups' => array('group1', 'group2'),
  198. ));
  199. $this->assertEquals(array('group1', 'group2'), $form->getValidationGroups());
  200. }
  201. public function testValidationGroupsAreInheritedFromParentIfEmpty()
  202. {
  203. $parentForm = new Form('parent', array(
  204. 'validation_groups' => 'group',
  205. ));
  206. $childForm = new Form('child');
  207. $parentForm->add($childForm);
  208. $this->assertEquals(array('group'), $childForm->getValidationGroups());
  209. }
  210. public function testValidationGroupsAreNotInheritedFromParentIfSet()
  211. {
  212. $parentForm = new Form('parent', array(
  213. 'validation_groups' => 'group1',
  214. ));
  215. $childForm = new Form('child', array(
  216. 'validation_groups' => 'group2',
  217. ));
  218. $parentForm->add($childForm);
  219. $this->assertEquals(array('group2'), $childForm->getValidationGroups());
  220. }
  221. /**
  222. * @expectedException Symfony\Component\Form\Exception\FormException
  223. */
  224. public function testBindThrowsExceptionIfAnonymous()
  225. {
  226. $form = new Form(null, array('validator' => $this->createMockValidator()));
  227. $form->bind($this->createPostRequest());
  228. }
  229. public function testBindValidatesData()
  230. {
  231. $form = new Form('author', array(
  232. 'validation_groups' => 'group',
  233. 'validator' => $this->validator,
  234. ));
  235. $form->add(new TestField('firstName'));
  236. $this->validator->expects($this->once())
  237. ->method('validate')
  238. ->with($this->equalTo($form));
  239. // concrete request is irrelevant
  240. $form->bind($this->createPostRequest());
  241. }
  242. public function testBindDoesNotValidateArrays()
  243. {
  244. $form = new Form('author', array(
  245. 'validator' => $this->validator,
  246. ));
  247. $form->add(new TestField('firstName'));
  248. // only the form is validated
  249. $this->validator->expects($this->once())
  250. ->method('validate')
  251. ->with($this->equalTo($form));
  252. // concrete request is irrelevant
  253. // data is an array
  254. $form->bind($this->createPostRequest(), array());
  255. }
  256. public function testBindThrowsExceptionIfNoValidatorIsSet()
  257. {
  258. $field = $this->createMockField('firstName');
  259. $form = new Form('author');
  260. $form->add($field);
  261. $this->setExpectedException('Symfony\Component\Form\Exception\MissingOptionsException');
  262. // data is irrelevant
  263. $form->bind($this->createPostRequest());
  264. }
  265. public function testBindReadsRequestData()
  266. {
  267. $values = array(
  268. 'author' => array(
  269. 'name' => 'Bernhard',
  270. 'image' => array('filename' => 'foobar.png'),
  271. ),
  272. );
  273. $files = array(
  274. 'author' => array(
  275. 'error' => array('image' => array('file' => UPLOAD_ERR_OK)),
  276. 'name' => array('image' => array('file' => 'upload.png')),
  277. 'size' => array('image' => array('file' => 123)),
  278. 'tmp_name' => array('image' => array('file' => 'abcdef.png')),
  279. 'type' => array('image' => array('file' => 'image/png')),
  280. ),
  281. );
  282. $form = new Form('author', array('validator' => $this->validator));
  283. $form->add(new TestField('name'));
  284. $imageForm = new Form('image');
  285. $imageForm->add(new TestField('file'));
  286. $imageForm->add(new TestField('filename'));
  287. $form->add($imageForm);
  288. $form->bind($this->createPostRequest($values, $files));
  289. $file = new UploadedFile('abcdef.png', 'upload.png', 'image/png', 123, UPLOAD_ERR_OK);
  290. $this->assertEquals('Bernhard', $form['name']->getData());
  291. $this->assertEquals('foobar.png', $form['image']['filename']->getData());
  292. $this->assertEquals($file, $form['image']['file']->getData());
  293. }
  294. public function testBindAcceptsObject()
  295. {
  296. $object = new \stdClass();
  297. $form = new Form('author', array('validator' => $this->validator));
  298. $form->bind(new Request(), $object);
  299. $this->assertSame($object, $form->getData());
  300. }
  301. public function testReadPropertyIsIgnoredIfPropertyPathIsNull()
  302. {
  303. $author = new Author();
  304. $author->child = new Author();
  305. $standaloneChild = new Author();
  306. $form = new Form('child');
  307. $form->setData($standaloneChild);
  308. $form->setPropertyPath(null);
  309. $form->readProperty($author);
  310. // should not be $author->child!!
  311. $this->assertSame($standaloneChild, $form->getData());
  312. }
  313. public function testWritePropertyIsIgnoredIfPropertyPathIsNull()
  314. {
  315. $author = new Author();
  316. $author->child = $child = new Author();
  317. $standaloneChild = new Author();
  318. $form = new Form('child');
  319. $form->setData($standaloneChild);
  320. $form->setPropertyPath(null);
  321. $form->writeProperty($author);
  322. // $author->child was not modified
  323. $this->assertSame($child, $author->child);
  324. }
  325. public function testSupportsArrayAccess()
  326. {
  327. $form = new Form('author');
  328. $form->add($this->createMockField('firstName'));
  329. $this->assertEquals($form->get('firstName'), $form['firstName']);
  330. $this->assertTrue(isset($form['firstName']));
  331. }
  332. public function testSupportsUnset()
  333. {
  334. $form = new Form('author');
  335. $form->add($this->createMockField('firstName'));
  336. unset($form['firstName']);
  337. $this->assertFalse(isset($form['firstName']));
  338. }
  339. public function testDoesNotSupportAddingFields()
  340. {
  341. $form = new Form('author');
  342. $this->setExpectedException('LogicException');
  343. $form[] = $this->createMockField('lastName');
  344. }
  345. public function testSupportsCountable()
  346. {
  347. $form = new Form('group');
  348. $form->add($this->createMockField('firstName'));
  349. $form->add($this->createMockField('lastName'));
  350. $this->assertEquals(2, count($form));
  351. $form->add($this->createMockField('australian'));
  352. $this->assertEquals(3, count($form));
  353. }
  354. public function testSupportsIterable()
  355. {
  356. $form = new Form('group');
  357. $form->add($field1 = $this->createMockField('field1'));
  358. $form->add($field2 = $this->createMockField('field2'));
  359. $form->add($field3 = $this->createMockField('field3'));
  360. $expected = array(
  361. 'field1' => $field1,
  362. 'field2' => $field2,
  363. 'field3' => $field3,
  364. );
  365. $this->assertEquals($expected, iterator_to_array($form));
  366. }
  367. public function testIsSubmitted()
  368. {
  369. $form = new Form('author', array('validator' => $this->validator));
  370. $this->assertFalse($form->isSubmitted());
  371. $form->submit(array('firstName' => 'Bernhard'));
  372. $this->assertTrue($form->isSubmitted());
  373. }
  374. public function testValidIfAllFieldsAreValid()
  375. {
  376. $form = new Form('author', array('validator' => $this->validator));
  377. $form->add($this->createValidMockField('firstName'));
  378. $form->add($this->createValidMockField('lastName'));
  379. $form->submit(array('firstName' => 'Bernhard', 'lastName' => 'Potencier'));
  380. $this->assertTrue($form->isValid());
  381. }
  382. public function testInvalidIfFieldIsInvalid()
  383. {
  384. $form = new Form('author', array('validator' => $this->validator));
  385. $form->add($this->createInvalidMockField('firstName'));
  386. $form->add($this->createValidMockField('lastName'));
  387. $form->submit(array('firstName' => 'Bernhard', 'lastName' => 'Potencier'));
  388. $this->assertFalse($form->isValid());
  389. }
  390. public function testInvalidIfSubmittedWithExtraFields()
  391. {
  392. $form = new Form('author', array('validator' => $this->validator));
  393. $form->add($this->createValidMockField('firstName'));
  394. $form->add($this->createValidMockField('lastName'));
  395. $form->submit(array('foo' => 'bar', 'firstName' => 'Bernhard', 'lastName' => 'Potencier'));
  396. $this->assertTrue($form->isSubmittedWithExtraFields());
  397. }
  398. public function testHasNoErrorsIfOnlyFieldHasErrors()
  399. {
  400. $form = new Form('author', array('validator' => $this->validator));
  401. $form->add($this->createInvalidMockField('firstName'));
  402. $form->submit(array('firstName' => 'Bernhard'));
  403. $this->assertFalse($form->hasErrors());
  404. }
  405. public function testSubmitForwardsPreprocessedData()
  406. {
  407. $field = $this->createMockField('firstName');
  408. $form = $this->getMock(
  409. 'Symfony\Component\Form\Form',
  410. array('preprocessData'), // only mock preprocessData()
  411. array('author', array('validator' => $this->validator))
  412. );
  413. // The data array is prepared directly after binding
  414. $form->expects($this->once())
  415. ->method('preprocessData')
  416. ->with($this->equalTo(array('firstName' => 'Bernhard')))
  417. ->will($this->returnValue(array('firstName' => 'preprocessed[Bernhard]')));
  418. $form->add($field);
  419. // The preprocessed data is then forwarded to the fields
  420. $field->expects($this->once())
  421. ->method('submit')
  422. ->with($this->equalTo('preprocessed[Bernhard]'));
  423. $form->submit(array('firstName' => 'Bernhard'));
  424. }
  425. public function testSubmitForwardsNullIfValueIsMissing()
  426. {
  427. $field = $this->createMockField('firstName');
  428. $field->expects($this->once())
  429. ->method('submit')
  430. ->with($this->equalTo(null));
  431. $form = new Form('author', array('validator' => $this->validator));
  432. $form->add($field);
  433. $form->submit(array());
  434. }
  435. public function testAddErrorMapsFieldValidationErrorsOntoFields()
  436. {
  437. $error = new FieldError('Message');
  438. $field = $this->createMockField('firstName');
  439. $field->expects($this->once())
  440. ->method('addError')
  441. ->with($this->equalTo($error));
  442. $form = new Form('author');
  443. $form->add($field);
  444. $path = new PropertyPath('fields[firstName].data');
  445. $form->addError(new FieldError('Message'), $path->getIterator());
  446. }
  447. public function testAddErrorMapsFieldValidationErrorsOntoFieldsWithinNestedForms()
  448. {
  449. $error = new FieldError('Message');
  450. $field = $this->createMockField('firstName');
  451. $field->expects($this->once())
  452. ->method('addError')
  453. ->with($this->equalTo($error));
  454. $form = new Form('author');
  455. $innerGroup = new Form('names');
  456. $innerGroup->add($field);
  457. $form->add($innerGroup);
  458. $path = new PropertyPath('fields[names].fields[firstName].data');
  459. $form->addError(new FieldError('Message'), $path->getIterator());
  460. }
  461. public function testAddErrorKeepsFieldValidationErrorsIfFieldNotFound()
  462. {
  463. $field = $this->createMockField('foo');
  464. $field->expects($this->never())
  465. ->method('addError');
  466. $form = new Form('author');
  467. $form->add($field);
  468. $path = new PropertyPath('fields[bar].data');
  469. $form->addError(new FieldError('Message'), $path->getIterator());
  470. $this->assertEquals(array(new FieldError('Message')), $form->getErrors());
  471. }
  472. public function testAddErrorKeepsFieldValidationErrorsIfFieldIsHidden()
  473. {
  474. $field = $this->createMockField('firstName');
  475. $field->expects($this->any())
  476. ->method('isHidden')
  477. ->will($this->returnValue(true));
  478. $field->expects($this->never())
  479. ->method('addError');
  480. $form = new Form('author');
  481. $form->add($field);
  482. $path = new PropertyPath('fields[firstName].data');
  483. $form->addError(new FieldError('Message'), $path->getIterator());
  484. $this->assertEquals(array(new FieldError('Message')), $form->getErrors());
  485. }
  486. public function testAddErrorMapsDataValidationErrorsOntoFields()
  487. {
  488. $error = new DataError('Message');
  489. // path is expected to point at "firstName"
  490. $expectedPath = new PropertyPath('firstName');
  491. $expectedPathIterator = $expectedPath->getIterator();
  492. $field = $this->createMockField('firstName');
  493. $field->expects($this->any())
  494. ->method('getPropertyPath')
  495. ->will($this->returnValue(new PropertyPath('firstName')));
  496. $field->expects($this->once())
  497. ->method('addError')
  498. ->with($this->equalTo($error), $this->equalTo($expectedPathIterator));
  499. $form = new Form('author');
  500. $form->add($field);
  501. $path = new PropertyPath('firstName');
  502. $form->addError($error, $path->getIterator());
  503. }
  504. public function testAddErrorKeepsDataValidationErrorsIfFieldNotFound()
  505. {
  506. $field = $this->createMockField('foo');
  507. $field->expects($this->any())
  508. ->method('getPropertyPath')
  509. ->will($this->returnValue(new PropertyPath('foo')));
  510. $field->expects($this->never())
  511. ->method('addError');
  512. $form = new Form('author');
  513. $form->add($field);
  514. $path = new PropertyPath('bar');
  515. $form->addError(new DataError('Message'), $path->getIterator());
  516. }
  517. public function testAddErrorKeepsDataValidationErrorsIfFieldIsHidden()
  518. {
  519. $field = $this->createMockField('firstName');
  520. $field->expects($this->any())
  521. ->method('isHidden')
  522. ->will($this->returnValue(true));
  523. $field->expects($this->any())
  524. ->method('getPropertyPath')
  525. ->will($this->returnValue(new PropertyPath('firstName')));
  526. $field->expects($this->never())
  527. ->method('addError');
  528. $form = new Form('author');
  529. $form->add($field);
  530. $path = new PropertyPath('firstName');
  531. $form->addError(new DataError('Message'), $path->getIterator());
  532. }
  533. public function testAddErrorMapsDataValidationErrorsOntoNestedFields()
  534. {
  535. $error = new DataError('Message');
  536. // path is expected to point at "street"
  537. $expectedPath = new PropertyPath('address.street');
  538. $expectedPathIterator = $expectedPath->getIterator();
  539. $expectedPathIterator->next();
  540. $field = $this->createMockField('address');
  541. $field->expects($this->any())
  542. ->method('getPropertyPath')
  543. ->will($this->returnValue(new PropertyPath('address')));
  544. $field->expects($this->once())
  545. ->method('addError')
  546. ->with($this->equalTo($error), $this->equalTo($expectedPathIterator));
  547. $form = new Form('author');
  548. $form->add($field);
  549. $path = new PropertyPath('address.street');
  550. $form->addError($error, $path->getIterator());
  551. }
  552. public function testAddErrorMapsErrorsOntoFieldsInVirtualGroups()
  553. {
  554. $error = new DataError('Message');
  555. // path is expected to point at "address"
  556. $expectedPath = new PropertyPath('address');
  557. $expectedPathIterator = $expectedPath->getIterator();
  558. $field = $this->createMockField('address');
  559. $field->expects($this->any())
  560. ->method('getPropertyPath')
  561. ->will($this->returnValue(new PropertyPath('address')));
  562. $field->expects($this->once())
  563. ->method('addError')
  564. ->with($this->equalTo($error), $this->equalTo($expectedPathIterator));
  565. $form = new Form('author');
  566. $nestedForm = new Form('nested', array('virtual' => true));
  567. $nestedForm->add($field);
  568. $form->add($nestedForm);
  569. $path = new PropertyPath('address');
  570. $form->addError($error, $path->getIterator());
  571. }
  572. public function testAddThrowsExceptionIfAlreadySubmitted()
  573. {
  574. $form = new Form('author', array('validator' => $this->validator));
  575. $form->add($this->createMockField('firstName'));
  576. $form->submit(array());
  577. $this->setExpectedException('Symfony\Component\Form\Exception\AlreadySubmittedException');
  578. $form->add($this->createMockField('lastName'));
  579. }
  580. public function testAddSetsFieldParent()
  581. {
  582. $form = new Form('author');
  583. $field = $this->createMockField('firstName');
  584. $field->expects($this->once())
  585. ->method('setParent')
  586. ->with($this->equalTo($form));
  587. $form->add($field);
  588. }
  589. public function testRemoveUnsetsFieldParent()
  590. {
  591. $form = new Form('author');
  592. $field = $this->createMockField('firstName');
  593. $field->expects($this->exactly(2))
  594. ->method('setParent');
  595. // PHPUnit fails to compare subsequent method calls with different arguments
  596. $form->add($field);
  597. $form->remove('firstName');
  598. }
  599. public function testAddUpdatesFieldFromTransformedData()
  600. {
  601. $originalAuthor = new Author();
  602. $transformedAuthor = new Author();
  603. // the authors should differ to make sure the test works
  604. $transformedAuthor->firstName = 'Foo';
  605. $form = new TestForm('author');
  606. $transformer = $this->createMockTransformer();
  607. $transformer->expects($this->once())
  608. ->method('transform')
  609. ->with($this->equalTo($originalAuthor))
  610. ->will($this->returnValue($transformedAuthor));
  611. $form->setValueTransformer($transformer);
  612. $form->setData($originalAuthor);
  613. $field = $this->createMockField('firstName');
  614. $field->expects($this->any())
  615. ->method('getPropertyPath')
  616. ->will($this->returnValue(new PropertyPath('firstName')));
  617. $field->expects($this->once())
  618. ->method('readProperty')
  619. ->with($this->equalTo($transformedAuthor));
  620. $form->add($field);
  621. }
  622. public function testAddDoesNotUpdateFieldIfTransformedDataIsEmpty()
  623. {
  624. $originalAuthor = new Author();
  625. $form = new TestForm('author');
  626. $transformer = $this->createMockTransformer();
  627. $transformer->expects($this->once())
  628. ->method('transform')
  629. ->with($this->equalTo($originalAuthor))
  630. ->will($this->returnValue(''));
  631. $form->setValueTransformer($transformer);
  632. $form->setData($originalAuthor);
  633. $field = $this->createMockField('firstName');
  634. $field->expects($this->never())
  635. ->method('readProperty');
  636. $form->add($field);
  637. }
  638. /**
  639. * @expectedException Symfony\Component\Form\Exception\UnexpectedTypeException
  640. */
  641. public function testAddThrowsExceptionIfNoFieldOrString()
  642. {
  643. $form = new Form('author');
  644. $form->add(1234);
  645. }
  646. /**
  647. * @expectedException Symfony\Component\Form\Exception\FieldDefinitionException
  648. */
  649. public function testAddThrowsExceptionIfAnonymousField()
  650. {
  651. $form = new Form('author');
  652. $field = $this->createMockField('');
  653. $form->add($field);
  654. }
  655. /**
  656. * @expectedException Symfony\Component\Form\Exception\FormException
  657. */
  658. public function testAddThrowsExceptionIfStringButNoFieldFactory()
  659. {
  660. $form = new Form('author', array('data_class' => 'Application\Entity'));
  661. $form->add('firstName');
  662. }
  663. /**
  664. * @expectedException Symfony\Component\Form\Exception\FormException
  665. */
  666. public function testAddThrowsExceptionIfStringButNoClass()
  667. {
  668. $form = new Form('author', array('field_factory' => new \stdClass()));
  669. $form->add('firstName');
  670. }
  671. public function testAddUsesFieldFromFactoryIfStringIsGiven()
  672. {
  673. $author = new \stdClass();
  674. $field = $this->createMockField('firstName');
  675. $factory = $this->getMock('Symfony\Component\Form\FieldFactory\FieldFactoryInterface');
  676. $factory->expects($this->once())
  677. ->method('getInstance')
  678. ->with($this->equalTo('stdClass'), $this->equalTo('firstName'), $this->equalTo(array('foo' => 'bar')))
  679. ->will($this->returnValue($field));
  680. $form = new Form('author', array(
  681. 'data' => $author,
  682. 'data_class' => 'stdClass',
  683. 'field_factory' => $factory,
  684. ));
  685. $form->add('firstName', array('foo' => 'bar'));
  686. $this->assertSame($field, $form['firstName']);
  687. }
  688. public function testSetDataUpdatesAllFieldsFromTransformedData()
  689. {
  690. $originalAuthor = new Author();
  691. $transformedAuthor = new Author();
  692. // the authors should differ to make sure the test works
  693. $transformedAuthor->firstName = 'Foo';
  694. $form = new TestForm('author');
  695. $transformer = $this->createMockTransformer();
  696. $transformer->expects($this->once())
  697. ->method('transform')
  698. ->with($this->equalTo($originalAuthor))
  699. ->will($this->returnValue($transformedAuthor));
  700. $form->setValueTransformer($transformer);
  701. $field = $this->createMockField('firstName');
  702. $field->expects($this->once())
  703. ->method('readProperty')
  704. ->with($this->equalTo($transformedAuthor));
  705. $form->add($field);
  706. $field = $this->createMockField('lastName');
  707. $field->expects($this->once())
  708. ->method('readProperty')
  709. ->with($this->equalTo($transformedAuthor));
  710. $form->add($field);
  711. $form->setData($originalAuthor);
  712. }
  713. /**
  714. * The use case for this test are groups whose fields should be mapped
  715. * directly onto properties of the form's object.
  716. *
  717. * Example:
  718. *
  719. * <code>
  720. * $dateRangeField = new Form('dateRange');
  721. * $dateRangeField->add(new DateField('startDate'));
  722. * $dateRangeField->add(new DateField('endDate'));
  723. * $form->add($dateRangeField);
  724. * </code>
  725. *
  726. * If $dateRangeField is not virtual, the property "dateRange" must be
  727. * present on the form's object. In this property, an object or array
  728. * with the properties "startDate" and "endDate" is expected.
  729. *
  730. * If $dateRangeField is virtual though, it's children are mapped directly
  731. * onto the properties "startDate" and "endDate" of the form's object.
  732. */
  733. public function testSetDataSkipsVirtualForms()
  734. {
  735. $author = new Author();
  736. $author->firstName = 'Foo';
  737. $form = new Form('author');
  738. $nestedForm = new Form('personal_data', array(
  739. 'virtual' => true,
  740. ));
  741. // both fields are in the nested group but receive the object of the
  742. // top-level group because the nested group is virtual
  743. $field = $this->createMockField('firstName');
  744. $field->expects($this->once())
  745. ->method('readProperty')
  746. ->with($this->equalTo($author));
  747. $nestedForm->add($field);
  748. $field = $this->createMockField('lastName');
  749. $field->expects($this->once())
  750. ->method('readProperty')
  751. ->with($this->equalTo($author));
  752. $nestedForm->add($field);
  753. $form->add($nestedForm);
  754. $form->setData($author);
  755. }
  756. public function testSetDataThrowsAnExceptionIfArgumentIsNotObjectOrArray()
  757. {
  758. $form = new Form('author');
  759. $this->setExpectedException('InvalidArgumentException');
  760. $form->setData('foobar');
  761. }
  762. /**
  763. * @expectedException Symfony\Component\Form\Exception\FormException
  764. */
  765. public function testSetDataMatchesAgainstDataClass_fails()
  766. {
  767. $form = new Form('author', array(
  768. 'data_class' => 'Symfony\Tests\Component\Form\Fixtures\Author',
  769. ));
  770. $form->setData(new \stdClass());
  771. }
  772. public function testSetDataMatchesAgainstDataClass_succeeds()
  773. {
  774. $form = new Form('author', array(
  775. 'data_class' => 'Symfony\Tests\Component\Form\Fixtures\Author',
  776. ));
  777. $form->setData(new Author());
  778. }
  779. public function testSubmitUpdatesTransformedDataFromAllFields()
  780. {
  781. $originalAuthor = new Author();
  782. $transformedAuthor = new Author();
  783. // the authors should differ to make sure the test works
  784. $transformedAuthor->firstName = 'Foo';
  785. $form = new TestForm('author', array('validator' => $this->validator));
  786. $transformer = $this->createMockTransformer();
  787. $transformer->expects($this->exactly(2))
  788. ->method('transform')
  789. // the method is first called with NULL, then
  790. // with $originalAuthor -> not testable by PHPUnit
  791. // ->with($this->equalTo(null))
  792. // ->with($this->equalTo($originalAuthor))
  793. ->will($this->returnValue($transformedAuthor));
  794. $form->setValueTransformer($transformer);
  795. $form->setData($originalAuthor);
  796. $field = $this->createMockField('firstName');
  797. $field->expects($this->once())
  798. ->method('writeProperty')
  799. ->with($this->equalTo($transformedAuthor));
  800. $form->add($field);
  801. $field = $this->createMockField('lastName');
  802. $field->expects($this->once())
  803. ->method('writeProperty')
  804. ->with($this->equalTo($transformedAuthor));
  805. $form->add($field);
  806. $form->submit(array()); // irrelevant
  807. }
  808. public function testGetDataReturnsObject()
  809. {
  810. $form = new Form('author');
  811. $object = new \stdClass();
  812. $form->setData($object);
  813. $this->assertEquals($object, $form->getData());
  814. }
  815. public function testGetDisplayedDataForwardsCall()
  816. {
  817. $field = $this->createValidMockField('firstName');
  818. $field->expects($this->atLeastOnce())
  819. ->method('getDisplayedData')
  820. ->will($this->returnValue('Bernhard'));
  821. $form = new Form('author');
  822. $form->add($field);
  823. $this->assertEquals(array('firstName' => 'Bernhard'), $form->getDisplayedData());
  824. }
  825. public function testIsMultipartIfAnyFieldIsMultipart()
  826. {
  827. $form = new Form('author');
  828. $form->add($this->createMultipartMockField('firstName'));
  829. $form->add($this->createNonMultipartMockField('lastName'));
  830. $this->assertTrue($form->isMultipart());
  831. }
  832. public function testIsNotMultipartIfNoFieldIsMultipart()
  833. {
  834. $form = new Form('author');
  835. $form->add($this->createNonMultipartMockField('firstName'));
  836. $form->add($this->createNonMultipartMockField('lastName'));
  837. $this->assertFalse($form->isMultipart());
  838. }
  839. public function testSupportsClone()
  840. {
  841. $form = new Form('author');
  842. $form->add($this->createMockField('firstName'));
  843. $clone = clone $form;
  844. $this->assertNotSame($clone['firstName'], $form['firstName']);
  845. }
  846. public function testSubmitWithoutPriorSetData()
  847. {
  848. return; // TODO
  849. $field = $this->createMockField('firstName');
  850. $field->expects($this->any())
  851. ->method('getData')
  852. ->will($this->returnValue('Bernhard'));
  853. $form = new Form('author');
  854. $form->add($field);
  855. $form->submit(array('firstName' => 'Bernhard'));
  856. $this->assertEquals(array('firstName' => 'Bernhard'), $form->getData());
  857. }
  858. public function testGetHiddenFieldsReturnsOnlyHiddenFields()
  859. {
  860. $form = $this->getGroupWithBothVisibleAndHiddenField();
  861. $hiddenFields = $form->getHiddenFields(true, false);
  862. $this->assertSame(array($form['hiddenField']), $hiddenFields);
  863. }
  864. public function testGetVisibleFieldsReturnsOnlyVisibleFields()
  865. {
  866. $form = $this->getGroupWithBothVisibleAndHiddenField();
  867. $visibleFields = $form->getVisibleFields(true, false);
  868. $this->assertSame(array($form['visibleField']), $visibleFields);
  869. }
  870. public function testValidateData()
  871. {
  872. $graphWalker = $this->createMockGraphWalker();
  873. $metadataFactory = $this->createMockMetadataFactory();
  874. $context = new ExecutionContext('Root', $graphWalker, $metadataFactory);
  875. $object = $this->getMock('\stdClass');
  876. $form = new Form('author', array('validation_groups' => array(
  877. 'group1',
  878. 'group2',
  879. )));
  880. $graphWalker->expects($this->exactly(2))
  881. ->method('walkReference')
  882. ->with($object,
  883. // should test for groups - PHPUnit limitation
  884. $this->anything(),
  885. 'data',
  886. true);
  887. $form->setData($object);
  888. $form->validateData($context);
  889. }
  890. public function testValidateDataAppendsPropertyPath()
  891. {
  892. $graphWalker = $this->createMockGraphWalker();
  893. $metadataFactory = $this->createMockMetadataFactory();
  894. $context = new ExecutionContext('Root', $graphWalker, $metadataFactory);
  895. $context->setPropertyPath('path');
  896. $object = $this->getMock('\stdClass');
  897. $form = new Form('author');
  898. $graphWalker->expects($this->once())
  899. ->method('walkReference')
  900. ->with($object,
  901. null,
  902. 'path.data',
  903. true);
  904. $form->setData($object);
  905. $form->validateData($context);
  906. }
  907. public function testValidateDataSetsCurrentPropertyToData()
  908. {
  909. $graphWalker = $this->createMockGraphWalker();
  910. $metadataFactory = $this->createMockMetadataFactory();
  911. $context = new ExecutionContext('Root', $graphWalker, $metadataFactory);
  912. $object = $this->getMock('\stdClass');
  913. $form = new Form('author');
  914. $test = $this;
  915. $graphWalker->expects($this->once())
  916. ->method('walkReference')
  917. ->will($this->returnCallback(function () use ($context, $test) {
  918. $test->assertEquals('data', $context->getCurrentProperty());
  919. }));
  920. $form->setData($object);
  921. $form->validateData($context);
  922. }
  923. public function testValidateDataDoesNotWalkScalars()
  924. {
  925. $graphWalker = $this->createMockGraphWalker();
  926. $metadataFactory = $this->createMockMetadataFactory();
  927. $context = new ExecutionContext('Root', $graphWalker, $metadataFactory);
  928. $valueTransformer = $this->createMockTransformer();
  929. $form = new Form('author', array('value_transformer' => $valueTransformer));
  930. $graphWalker->expects($this->never())
  931. ->method('walkReference');
  932. $valueTransformer->expects($this->atLeastOnce())
  933. ->method('reverseTransform')
  934. ->will($this->returnValue('foobar'));
  935. $form->submit(array('foo' => 'bar')); // reverse transformed to "foobar"
  936. $form->validateData($context);
  937. }
  938. public function testSubformDoesntCallSetters()
  939. {
  940. $author = new FormTest_AuthorWithoutRefSetter(new Author());
  941. $form = new Form('author', array('validator' => $this->createMockValidator()));
  942. $form->setData($author);
  943. $refForm = new Form('reference');
  944. $refForm->add(new TestField('firstName'));
  945. $form->add($refForm);
  946. $form->bind($this->createPostRequest(array(
  947. 'author' => array(
  948. // reference has a getter, but not setter
  949. 'reference' => array(
  950. 'firstName' => 'Foo',
  951. )
  952. )
  953. )));
  954. $this->assertEquals('Foo', $author->getReference()->firstName);
  955. }
  956. public function testSubformCallsSettersIfByReferenceIsFalse()
  957. {
  958. $author = new FormTest_AuthorWithoutRefSetter(new Author());
  959. $form = new Form('author', array('validator' => $this->createMockValidator()));
  960. $form->setData($author);
  961. $refForm = new Form('referenceCopy', array('by_reference' => false));
  962. $refForm->add(new TestField('firstName'));
  963. $form->add($refForm);
  964. $form->bind($this->createPostRequest(array(
  965. 'author' => array(
  966. // referenceCopy has a getter that returns a copy
  967. 'referenceCopy' => array(
  968. 'firstName' => 'Foo',
  969. )
  970. )
  971. )));
  972. // firstName can only be updated if setReferenceCopy() was called
  973. $this->assertEquals('Foo', $author->getReferenceCopy()->firstName);
  974. }
  975. public function testSubformCallsSettersIfReferenceIsScalar()
  976. {
  977. $author = new FormTest_AuthorWithoutRefSetter('scalar');
  978. $form = new Form('author', array('validator' => $this->createMockValidator()));
  979. $form->setData($author);
  980. $refForm = new FormTest_FormThatReturns('referenceCopy');
  981. $refForm->setReturnValue('foobar');
  982. $form->add($refForm);
  983. $form->bind($this->createPostRequest(array(
  984. 'author' => array(
  985. 'referenceCopy' => array(), // doesn't matter actually
  986. )
  987. )));
  988. // firstName can only be updated if setReferenceCopy() was called
  989. $this->assertEquals('foobar', $author->getReferenceCopy());
  990. }
  991. /**
  992. * Create a group containing two fields, "visibleField" and "hiddenField"
  993. *
  994. * @return Form
  995. */
  996. protected function getGroupWithBothVisibleAndHiddenField()
  997. {
  998. $form = new Form('testGroup');
  999. // add a visible field
  1000. $visibleField = $this->createMockField('visibleField');
  1001. $visibleField->expects($this->once())
  1002. ->method('isHidden')
  1003. ->will($this->returnValue(false));
  1004. $form->add($visibleField);
  1005. // add a hidden field
  1006. $hiddenField = $this->createMockField('hiddenField');
  1007. $hiddenField->expects($this->once())
  1008. ->method('isHidden')
  1009. ->will($this->returnValue(true));
  1010. $form->add($hiddenField);
  1011. return $form;
  1012. }
  1013. protected function createMockField($key)
  1014. {
  1015. $field = $this->getMock(
  1016. 'Symfony\Component\Form\FieldInterface',
  1017. array(),
  1018. array(),
  1019. '',
  1020. false, // don't use constructor
  1021. false // don't call parent::__clone
  1022. );
  1023. $field->expects($this->any())
  1024. ->method('getKey')
  1025. ->will($this->returnValue($key));
  1026. return $field;
  1027. }
  1028. protected function createMockForm()
  1029. {
  1030. $form = $this->getMock(
  1031. 'Symfony\Component\Form\Form',
  1032. array(),
  1033. array(),
  1034. '',
  1035. false, // don't use constructor
  1036. false // don't call parent::__clone)
  1037. );
  1038. $form->expects($this->any())
  1039. ->method('getRoot')
  1040. ->will($this->returnValue($form));
  1041. return $form;
  1042. }
  1043. protected function createInvalidMockField($key)
  1044. {
  1045. $field = $this->createMockField($key);
  1046. $field->expects($this->any())
  1047. ->method('isValid')
  1048. ->will($this->returnValue(false));
  1049. return $field;
  1050. }
  1051. protected function createValidMockField($key)
  1052. {
  1053. $field = $this->createMockField($key);
  1054. $field->expects($this->any())
  1055. ->method('isValid')
  1056. ->will($this->returnValue(true));
  1057. return $field;
  1058. }
  1059. protected function createNonMultipartMockField($key)
  1060. {
  1061. $field = $this->createMockField($key);
  1062. $field->expects($this->any())
  1063. ->method('isMultipart')
  1064. ->will($this->returnValue(false));
  1065. return $field;
  1066. }
  1067. protected function createMultipartMockField($key)
  1068. {
  1069. $field = $this->createMockField($key);
  1070. $field->expects($this->any())
  1071. ->method('isMultipart')
  1072. ->will($this->returnValue(true));
  1073. return $field;
  1074. }
  1075. protected function createMockTransformer()
  1076. {
  1077. return $this->getMock('Symfony\Component\Form\ValueTransformer\ValueTransformerInterface', array(), array(), '', false, false);
  1078. }
  1079. protected function createMockValidator()
  1080. {
  1081. return $this->getMock('Symfony\Component\Validator\ValidatorInterface');
  1082. }
  1083. protected function createMockCsrfProvider()
  1084. {
  1085. return $this->getMock('Symfony\Component\Form\CsrfProvider\CsrfProviderInterface');
  1086. }
  1087. protected function createMockGraphWalker()
  1088. {
  1089. return $this->getMockBuilder('Symfony\Component\Validator\GraphWalker')
  1090. ->disableOriginalConstructor()
  1091. ->getMock();
  1092. }
  1093. protected function createMockMetadataFactory()
  1094. {
  1095. return $this->getMock('Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface');
  1096. }
  1097. protected function createPostRequest(array $values = array(), array $files = array())
  1098. {
  1099. $server = array('REQUEST_METHOD' => 'POST');
  1100. return new Request(array(), $values, array(), array(), $files, $server);
  1101. }
  1102. }