FormTest.php 39 KB

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