FormTest.php 43 KB

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