FormTest.php 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268
  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. public function testValidateDataDoesNotWalkScalars()
  873. {
  874. $graphWalker = $this->createMockGraphWalker();
  875. $metadataFactory = $this->createMockMetadataFactory();
  876. $context = new ExecutionContext('Root', $graphWalker, $metadataFactory);
  877. $valueTransformer = $this->createMockTransformer();
  878. $form = new Form('author', array('value_transformer' => $valueTransformer));
  879. $graphWalker->expects($this->never())
  880. ->method('walkReference');
  881. $valueTransformer->expects($this->atLeastOnce())
  882. ->method('reverseTransform')
  883. ->will($this->returnValue('foobar'));
  884. $form->submit(array('foo' => 'bar')); // reverse transformed to "foobar"
  885. $form->validateData($context);
  886. }
  887. /**
  888. * Create a group containing two fields, "visibleField" and "hiddenField"
  889. *
  890. * @return Form
  891. */
  892. protected function getGroupWithBothVisibleAndHiddenField()
  893. {
  894. $form = new Form('testGroup');
  895. // add a visible field
  896. $visibleField = $this->createMockField('visibleField');
  897. $visibleField->expects($this->once())
  898. ->method('isHidden')
  899. ->will($this->returnValue(false));
  900. $form->add($visibleField);
  901. // add a hidden field
  902. $hiddenField = $this->createMockField('hiddenField');
  903. $hiddenField->expects($this->once())
  904. ->method('isHidden')
  905. ->will($this->returnValue(true));
  906. $form->add($hiddenField);
  907. return $form;
  908. }
  909. protected function createMockField($key)
  910. {
  911. $field = $this->getMock(
  912. 'Symfony\Component\Form\FieldInterface',
  913. array(),
  914. array(),
  915. '',
  916. false, // don't use constructor
  917. false // don't call parent::__clone
  918. );
  919. $field->expects($this->any())
  920. ->method('getKey')
  921. ->will($this->returnValue($key));
  922. return $field;
  923. }
  924. protected function createMockForm()
  925. {
  926. $form = $this->getMock(
  927. 'Symfony\Component\Form\Form',
  928. array(),
  929. array(),
  930. '',
  931. false, // don't use constructor
  932. false // don't call parent::__clone)
  933. );
  934. $form->expects($this->any())
  935. ->method('getRoot')
  936. ->will($this->returnValue($form));
  937. return $form;
  938. }
  939. protected function createInvalidMockField($key)
  940. {
  941. $field = $this->createMockField($key);
  942. $field->expects($this->any())
  943. ->method('isValid')
  944. ->will($this->returnValue(false));
  945. return $field;
  946. }
  947. protected function createValidMockField($key)
  948. {
  949. $field = $this->createMockField($key);
  950. $field->expects($this->any())
  951. ->method('isValid')
  952. ->will($this->returnValue(true));
  953. return $field;
  954. }
  955. protected function createNonMultipartMockField($key)
  956. {
  957. $field = $this->createMockField($key);
  958. $field->expects($this->any())
  959. ->method('isMultipart')
  960. ->will($this->returnValue(false));
  961. return $field;
  962. }
  963. protected function createMultipartMockField($key)
  964. {
  965. $field = $this->createMockField($key);
  966. $field->expects($this->any())
  967. ->method('isMultipart')
  968. ->will($this->returnValue(true));
  969. return $field;
  970. }
  971. protected function createMockTransformer()
  972. {
  973. return $this->getMock('Symfony\Component\Form\ValueTransformer\ValueTransformerInterface', array(), array(), '', false, false);
  974. }
  975. protected function createMockValidator()
  976. {
  977. return $this->getMock('Symfony\Component\Validator\ValidatorInterface');
  978. }
  979. protected function createMockCsrfProvider()
  980. {
  981. return $this->getMock('Symfony\Component\Form\CsrfProvider\CsrfProviderInterface');
  982. }
  983. protected function createMockGraphWalker()
  984. {
  985. return $this->getMockBuilder('Symfony\Component\Validator\GraphWalker')
  986. ->disableOriginalConstructor()
  987. ->getMock();
  988. }
  989. protected function createMockMetadataFactory()
  990. {
  991. return $this->getMock('Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface');
  992. }
  993. protected function createPostRequest(array $values = array(), array $files = array())
  994. {
  995. $server = array('REQUEST_METHOD' => 'POST');
  996. return new Request(array(), $values, array(), array(), $files, $server);
  997. }
  998. }