FormTest.php 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178
  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\HiddenField;
  19. use Symfony\Component\Form\PropertyPath;
  20. use Symfony\Component\HttpFoundation\Request;
  21. use Symfony\Component\HttpFoundation\File\UploadedFile;
  22. use Symfony\Component\Validator\ConstraintViolation;
  23. use Symfony\Component\Validator\ConstraintViolationList;
  24. use Symfony\Tests\Component\Form\Fixtures\Author;
  25. use Symfony\Tests\Component\Form\Fixtures\TestField;
  26. use Symfony\Tests\Component\Form\Fixtures\TestForm;
  27. class FormTest_PreconfiguredForm extends Form
  28. {
  29. protected function configure()
  30. {
  31. $this->add(new Field('firstName'));
  32. parent::configure();
  33. }
  34. }
  35. class TestSetDataBeforeConfigureForm extends Form
  36. {
  37. protected $testCase;
  38. protected $object;
  39. public function __construct($testCase, $name, $object, $validator)
  40. {
  41. $this->testCase = $testCase;
  42. $this->object = $object;
  43. parent::__construct($name, $object, $validator);
  44. }
  45. protected function configure()
  46. {
  47. $this->testCase->assertEquals($this->object, $this->getData());
  48. parent::configure();
  49. }
  50. }
  51. class FormTest extends \PHPUnit_Framework_TestCase
  52. {
  53. protected $validator;
  54. protected $form;
  55. public static function setUpBeforeClass()
  56. {
  57. @session_start();
  58. }
  59. protected function setUp()
  60. {
  61. $this->validator = $this->createMockValidator();
  62. $this->form = new Form('author', array('validator' => $this->validator));
  63. }
  64. public function testNoCsrfProtectionByDefault()
  65. {
  66. $form = new Form('author');
  67. $this->assertFalse($form->isCsrfProtected());
  68. }
  69. public function testCsrfProtectionCanBeEnabled()
  70. {
  71. $form = new Form('author', array(
  72. 'csrf_provider' => $this->createMockCsrfProvider(),
  73. ));
  74. $this->assertTrue($form->isCsrfProtected());
  75. }
  76. public function testCsrfFieldNameCanBeSet()
  77. {
  78. $form = new Form('author', array(
  79. 'csrf_provider' => $this->createMockCsrfProvider(),
  80. 'csrf_field_name' => 'foobar',
  81. ));
  82. $this->assertEquals('foobar', $form->getCsrfFieldName());
  83. }
  84. public function testCsrfProtectedFormsHaveExtraField()
  85. {
  86. $provider = $this->createMockCsrfProvider();
  87. $provider->expects($this->once())
  88. ->method('generateCsrfToken')
  89. ->with($this->equalTo('Symfony\Component\Form\Form'))
  90. ->will($this->returnValue('ABCDEF'));
  91. $form = new Form('author', array(
  92. 'csrf_provider' => $provider,
  93. ));
  94. $this->assertTrue($form->has($this->form->getCsrfFieldName()));
  95. $field = $form->get($form->getCsrfFieldName());
  96. $this->assertTrue($field instanceof HiddenField);
  97. $this->assertEquals('ABCDEF', $field->getDisplayedData());
  98. }
  99. public function testIsCsrfTokenValidPassesIfCsrfProtectionIsDisabled()
  100. {
  101. $this->form->submit(array());
  102. $this->assertTrue($this->form->isCsrfTokenValid());
  103. }
  104. public function testIsCsrfTokenValidPasses()
  105. {
  106. $provider = $this->createMockCsrfProvider();
  107. $provider->expects($this->once())
  108. ->method('isCsrfTokenValid')
  109. ->with($this->equalTo('Symfony\Component\Form\Form'), $this->equalTo('ABCDEF'))
  110. ->will($this->returnValue(true));
  111. $form = new Form('author', array(
  112. 'csrf_provider' => $provider,
  113. 'validator' => $this->validator,
  114. ));
  115. $field = $form->getCsrfFieldName();
  116. $form->submit(array($field => 'ABCDEF'));
  117. $this->assertTrue($form->isCsrfTokenValid());
  118. }
  119. public function testIsCsrfTokenValidFails()
  120. {
  121. $provider = $this->createMockCsrfProvider();
  122. $provider->expects($this->once())
  123. ->method('isCsrfTokenValid')
  124. ->with($this->equalTo('Symfony\Component\Form\Form'), $this->equalTo('ABCDEF'))
  125. ->will($this->returnValue(false));
  126. $form = new Form('author', array(
  127. 'csrf_provider' => $provider,
  128. 'validator' => $this->validator,
  129. ));
  130. $field = $form->getCsrfFieldName();
  131. $form->submit(array($field => 'ABCDEF'));
  132. $this->assertFalse($form->isCsrfTokenValid());
  133. }
  134. public function testGetValidator()
  135. {
  136. $this->assertSame($this->validator, $this->form->getValidator());
  137. }
  138. public function testValidationGroupNullByDefault()
  139. {
  140. $this->assertNull($this->form->getValidationGroups());
  141. }
  142. public function testValidationGroupsCanBeSetToString()
  143. {
  144. $form = new Form('author', array(
  145. 'validation_groups' => 'group',
  146. ));
  147. $this->assertEquals(array('group'), $form->getValidationGroups());
  148. }
  149. public function testValidationGroupsCanBeSetToArray()
  150. {
  151. $form = new Form('author', array(
  152. 'validation_groups' => array('group1', 'group2'),
  153. ));
  154. $this->assertEquals(array('group1', 'group2'), $form->getValidationGroups());
  155. }
  156. public function testBindUsesValidationGroups()
  157. {
  158. $field = $this->createMockField('firstName');
  159. $form = new Form('author', array(
  160. 'validation_groups' => 'group',
  161. 'validator' => $this->validator,
  162. ));
  163. $form->add($field);
  164. $this->validator->expects($this->once())
  165. ->method('validate')
  166. ->with($this->equalTo($form), $this->equalTo(array('group')));
  167. // data is irrelevant
  168. $form->bind($this->createPostRequest());
  169. }
  170. public function testBindThrowsExceptionIfNoValidatorIsSet()
  171. {
  172. $field = $this->createMockField('firstName');
  173. $form = new Form('author');
  174. $form->add($field);
  175. $this->setExpectedException('Symfony\Component\Form\Exception\FormException');
  176. // data is irrelevant
  177. $form->bind($this->createPostRequest());
  178. }
  179. public function testBindReadsRequestData()
  180. {
  181. $values = array(
  182. 'author' => array(
  183. 'name' => 'Bernhard',
  184. 'image' => array('filename' => 'foobar.png'),
  185. ),
  186. );
  187. $files = array(
  188. 'author' => array(
  189. 'error' => array('image' => array('file' => UPLOAD_ERR_OK)),
  190. 'name' => array('image' => array('file' => 'upload.png')),
  191. 'size' => array('image' => array('file' => 123)),
  192. 'tmp_name' => array('image' => array('file' => 'abcdef.png')),
  193. 'type' => array('image' => array('file' => 'image/png')),
  194. ),
  195. );
  196. $form = new Form('author', array('validator' => $this->validator));
  197. $form->add(new TestField('name'));
  198. $imageForm = new Form('image');
  199. $imageForm->add(new TestField('file'));
  200. $imageForm->add(new TestField('filename'));
  201. $form->add($imageForm);
  202. $form->bind($this->createPostRequest($values, $files));
  203. $file = new UploadedFile('abcdef.png', 'upload.png', 'image/png', 123, UPLOAD_ERR_OK);
  204. $this->assertEquals('Bernhard', $form['name']->getData());
  205. $this->assertEquals('foobar.png', $form['image']['filename']->getData());
  206. $this->assertEquals($file, $form['image']['file']->getData());
  207. }
  208. public function testBindAcceptsObject()
  209. {
  210. $object = new \stdClass();
  211. $form = new Form('author', array('validator' => $this->validator));
  212. $form->bind(new Request(), $object);
  213. $this->assertSame($object, $form->getData());
  214. }
  215. public function testBindGlobals()
  216. {
  217. $_POST = array(
  218. 'author' => array(
  219. 'name' => 'Bernhard',
  220. 'image' => array('filename' => 'foobar.png'),
  221. ),
  222. );
  223. $_FILES = array(
  224. 'author' => array(
  225. 'error' => array('image' => array('file' => UPLOAD_ERR_OK)),
  226. 'name' => array('image' => array('file' => 'upload.png')),
  227. 'size' => array('image' => array('file' => 123)),
  228. 'tmp_name' => array('image' => array('file' => 'abcdef.png')),
  229. 'type' => array('image' => array('file' => 'image/png')),
  230. ),
  231. );
  232. // don't erase other variables
  233. $_SERVER['REQUEST_METHOD'] = 'POST';
  234. $form = new Form('author', array('validator' => $this->validator));
  235. $form->add(new TestField('name'));
  236. $imageForm = new Form('image');
  237. $imageForm->add(new TestField('file'));
  238. $imageForm->add(new TestField('filename'));
  239. $form->add($imageForm);
  240. $form->bindGlobals();
  241. $file = new UploadedFile('abcdef.png', 'upload.png', 'image/png', 123, UPLOAD_ERR_OK);
  242. $this->assertEquals('Bernhard', $form['name']->getData());
  243. $this->assertEquals('foobar.png', $form['image']['filename']->getData());
  244. $this->assertEquals($file, $form['image']['file']->getData());
  245. }
  246. public function testReadPropertyIsIgnoredIfPropertyPathIsNull()
  247. {
  248. $author = new Author();
  249. $author->child = new Author();
  250. $standaloneChild = new Author();
  251. $form = new Form('child');
  252. $form->setData($standaloneChild);
  253. $form->setPropertyPath(null);
  254. $form->readProperty($author);
  255. // should not be $author->child!!
  256. $this->assertSame($standaloneChild, $form->getData());
  257. }
  258. public function testWritePropertyIsIgnoredIfPropertyPathIsNull()
  259. {
  260. $author = new Author();
  261. $author->child = $child = new Author();
  262. $standaloneChild = new Author();
  263. $form = new Form('child');
  264. $form->setData($standaloneChild);
  265. $form->setPropertyPath(null);
  266. $form->writeProperty($author);
  267. // $author->child was not modified
  268. $this->assertSame($child, $author->child);
  269. }
  270. public function testSupportsArrayAccess()
  271. {
  272. $form = new Form('author');
  273. $form->add($this->createMockField('firstName'));
  274. $this->assertEquals($form->get('firstName'), $form['firstName']);
  275. $this->assertTrue(isset($form['firstName']));
  276. }
  277. public function testSupportsUnset()
  278. {
  279. $form = new Form('author');
  280. $form->add($this->createMockField('firstName'));
  281. unset($form['firstName']);
  282. $this->assertFalse(isset($form['firstName']));
  283. }
  284. public function testDoesNotSupportAddingFields()
  285. {
  286. $form = new Form('author');
  287. $this->setExpectedException('LogicException');
  288. $form[] = $this->createMockField('lastName');
  289. }
  290. public function testSupportsCountable()
  291. {
  292. $form = new Form('group');
  293. $form->add($this->createMockField('firstName'));
  294. $form->add($this->createMockField('lastName'));
  295. $this->assertEquals(2, count($form));
  296. $form->add($this->createMockField('australian'));
  297. $this->assertEquals(3, count($form));
  298. }
  299. public function testSupportsIterable()
  300. {
  301. $form = new Form('group');
  302. $form->add($field1 = $this->createMockField('field1'));
  303. $form->add($field2 = $this->createMockField('field2'));
  304. $form->add($field3 = $this->createMockField('field3'));
  305. $expected = array(
  306. 'field1' => $field1,
  307. 'field2' => $field2,
  308. 'field3' => $field3,
  309. );
  310. $this->assertEquals($expected, iterator_to_array($form));
  311. }
  312. public function testIsSubmitted()
  313. {
  314. $form = new Form('author', array('validator' => $this->validator));
  315. $this->assertFalse($form->isSubmitted());
  316. $form->submit(array('firstName' => 'Bernhard'));
  317. $this->assertTrue($form->isSubmitted());
  318. }
  319. public function testValidIfAllFieldsAreValid()
  320. {
  321. $form = new Form('author', array('validator' => $this->validator));
  322. $form->add($this->createValidMockField('firstName'));
  323. $form->add($this->createValidMockField('lastName'));
  324. $form->submit(array('firstName' => 'Bernhard', 'lastName' => 'Potencier'));
  325. $this->assertTrue($form->isValid());
  326. }
  327. public function testInvalidIfFieldIsInvalid()
  328. {
  329. $form = new Form('author', array('validator' => $this->validator));
  330. $form->add($this->createInvalidMockField('firstName'));
  331. $form->add($this->createValidMockField('lastName'));
  332. $form->submit(array('firstName' => 'Bernhard', 'lastName' => 'Potencier'));
  333. $this->assertFalse($form->isValid());
  334. }
  335. public function testInvalidIfSubmittedWithExtraFields()
  336. {
  337. $form = new Form('author', array('validator' => $this->validator));
  338. $form->add($this->createValidMockField('firstName'));
  339. $form->add($this->createValidMockField('lastName'));
  340. $form->submit(array('foo' => 'bar', 'firstName' => 'Bernhard', 'lastName' => 'Potencier'));
  341. $this->assertTrue($form->isSubmittedWithExtraFields());
  342. }
  343. public function testHasNoErrorsIfOnlyFieldHasErrors()
  344. {
  345. $form = new Form('author', array('validator' => $this->validator));
  346. $form->add($this->createInvalidMockField('firstName'));
  347. $form->submit(array('firstName' => 'Bernhard'));
  348. $this->assertFalse($form->hasErrors());
  349. }
  350. public function testSubmitForwardsPreprocessedData()
  351. {
  352. $field = $this->createMockField('firstName');
  353. $form = $this->getMock(
  354. 'Symfony\Component\Form\Form',
  355. array('preprocessData'), // only mock preprocessData()
  356. array('author', array('validator' => $this->validator))
  357. );
  358. // The data array is prepared directly after binding
  359. $form->expects($this->once())
  360. ->method('preprocessData')
  361. ->with($this->equalTo(array('firstName' => 'Bernhard')))
  362. ->will($this->returnValue(array('firstName' => 'preprocessed[Bernhard]')));
  363. $form->add($field);
  364. // The preprocessed data is then forwarded to the fields
  365. $field->expects($this->once())
  366. ->method('submit')
  367. ->with($this->equalTo('preprocessed[Bernhard]'));
  368. $form->submit(array('firstName' => 'Bernhard'));
  369. }
  370. public function testSubmitForwardsNullIfValueIsMissing()
  371. {
  372. $field = $this->createMockField('firstName');
  373. $field->expects($this->once())
  374. ->method('submit')
  375. ->with($this->equalTo(null));
  376. $form = new Form('author', array('validator' => $this->validator));
  377. $form->add($field);
  378. $form->submit(array());
  379. }
  380. public function testAddErrorMapsFieldValidationErrorsOntoFields()
  381. {
  382. $error = new FieldError('Message');
  383. $field = $this->createMockField('firstName');
  384. $field->expects($this->once())
  385. ->method('addError')
  386. ->with($this->equalTo($error));
  387. $form = new Form('author');
  388. $form->add($field);
  389. $path = new PropertyPath('fields[firstName].data');
  390. $form->addError($error, $path->getIterator(), Form::FIELD_ERROR);
  391. }
  392. public function testAddErrorMapsFieldValidationErrorsOntoFieldsWithinNestedForms()
  393. {
  394. $error = new FieldError('Message');
  395. $field = $this->createMockField('firstName');
  396. $field->expects($this->once())
  397. ->method('addError')
  398. ->with($this->equalTo($error));
  399. $form = new Form('author');
  400. $innerGroup = new Form('names');
  401. $innerGroup->add($field);
  402. $form->add($innerGroup);
  403. $path = new PropertyPath('fields[names].fields[firstName].data');
  404. $form->addError($error, $path->getIterator(), Form::FIELD_ERROR);
  405. }
  406. public function testAddErrorKeepsFieldValidationErrorsIfFieldNotFound()
  407. {
  408. $error = new FieldError('Message');
  409. $field = $this->createMockField('foo');
  410. $field->expects($this->never())
  411. ->method('addError');
  412. $form = new Form('author');
  413. $form->add($field);
  414. $path = new PropertyPath('fields[bar].data');
  415. $form->addError($error, $path->getIterator(), Form::FIELD_ERROR);
  416. $this->assertEquals(array($error), $form->getErrors());
  417. }
  418. public function testAddErrorKeepsFieldValidationErrorsIfFieldIsHidden()
  419. {
  420. $error = new FieldError('Message');
  421. $field = $this->createMockField('firstName');
  422. $field->expects($this->any())
  423. ->method('isHidden')
  424. ->will($this->returnValue(true));
  425. $field->expects($this->never())
  426. ->method('addError');
  427. $form = new Form('author');
  428. $form->add($field);
  429. $path = new PropertyPath('fields[firstName].data');
  430. $form->addError($error, $path->getIterator(), Form::FIELD_ERROR);
  431. $this->assertEquals(array($error), $form->getErrors());
  432. }
  433. public function testAddErrorMapsDataValidationErrorsOntoFields()
  434. {
  435. $error = new FieldError('Message');
  436. // path is expected to point at "firstName"
  437. $expectedPath = new PropertyPath('firstName');
  438. $expectedPathIterator = $expectedPath->getIterator();
  439. $field = $this->createMockField('firstName');
  440. $field->expects($this->any())
  441. ->method('getPropertyPath')
  442. ->will($this->returnValue(new PropertyPath('firstName')));
  443. $field->expects($this->once())
  444. ->method('addError')
  445. ->with($this->equalTo($error), $this->equalTo($expectedPathIterator), $this->equalTo(Form::DATA_ERROR));
  446. $form = new Form('author');
  447. $form->add($field);
  448. $path = new PropertyPath('firstName');
  449. $form->addError($error, $path->getIterator(), Form::DATA_ERROR);
  450. }
  451. public function testAddErrorKeepsDataValidationErrorsIfFieldNotFound()
  452. {
  453. $error = new FieldError('Message');
  454. $field = $this->createMockField('foo');
  455. $field->expects($this->any())
  456. ->method('getPropertyPath')
  457. ->will($this->returnValue(new PropertyPath('foo')));
  458. $field->expects($this->never())
  459. ->method('addError');
  460. $form = new Form('author');
  461. $form->add($field);
  462. $path = new PropertyPath('bar');
  463. $form->addError($error, $path->getIterator(), Form::DATA_ERROR);
  464. }
  465. public function testAddErrorKeepsDataValidationErrorsIfFieldIsHidden()
  466. {
  467. $error = new FieldError('Message');
  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($error, $path->getIterator(), Form::DATA_ERROR);
  481. }
  482. public function testAddErrorMapsDataValidationErrorsOntoNestedFields()
  483. {
  484. $error = new FieldError('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), $this->equalTo(Form::DATA_ERROR));
  496. $form = new Form('author');
  497. $form->add($field);
  498. $path = new PropertyPath('address.street');
  499. $form->addError($error, $path->getIterator(), Form::DATA_ERROR);
  500. }
  501. public function testAddErrorMapsErrorsOntoFieldsInVirtualGroups()
  502. {
  503. $error = new FieldError('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), $this->equalTo(Form::DATA_ERROR));
  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(), Form::DATA_ERROR);
  520. }
  521. public function testAddThrowsExceptionIfAlreadyBound()
  522. {
  523. $form = new Form('author', array('validator' => $this->validator));
  524. $form->add($this->createMockField('firstName'));
  525. $form->bind(new Request());
  526. $this->setExpectedException('Symfony\Component\Form\Exception\AlreadyBoundException');
  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. /**
  820. * Create a group containing two fields, "visibleField" and "hiddenField"
  821. *
  822. * @return Form
  823. */
  824. protected function getGroupWithBothVisibleAndHiddenField()
  825. {
  826. $form = new Form('testGroup');
  827. // add a visible field
  828. $visibleField = $this->createMockField('visibleField');
  829. $visibleField->expects($this->once())
  830. ->method('isHidden')
  831. ->will($this->returnValue(false));
  832. $form->add($visibleField);
  833. // add a hidden field
  834. $hiddenField = $this->createMockField('hiddenField');
  835. $hiddenField->expects($this->once())
  836. ->method('isHidden')
  837. ->will($this->returnValue(true));
  838. $form->add($hiddenField);
  839. return $form;
  840. }
  841. protected function createMockField($key)
  842. {
  843. $field = $this->getMock(
  844. 'Symfony\Component\Form\FieldInterface',
  845. array(),
  846. array(),
  847. '',
  848. false, // don't use constructor
  849. false // don't call parent::__clone
  850. );
  851. $field->expects($this->any())
  852. ->method('getKey')
  853. ->will($this->returnValue($key));
  854. return $field;
  855. }
  856. protected function createMockForm()
  857. {
  858. $form = $this->getMock(
  859. 'Symfony\Component\Form\Form',
  860. array(),
  861. array(),
  862. '',
  863. false, // don't use constructor
  864. false // don't call parent::__clone)
  865. );
  866. $form->expects($this->any())
  867. ->method('getRoot')
  868. ->will($this->returnValue($form));
  869. return $form;
  870. }
  871. protected function createInvalidMockField($key)
  872. {
  873. $field = $this->createMockField($key);
  874. $field->expects($this->any())
  875. ->method('isValid')
  876. ->will($this->returnValue(false));
  877. return $field;
  878. }
  879. protected function createValidMockField($key)
  880. {
  881. $field = $this->createMockField($key);
  882. $field->expects($this->any())
  883. ->method('isValid')
  884. ->will($this->returnValue(true));
  885. return $field;
  886. }
  887. protected function createNonMultipartMockField($key)
  888. {
  889. $field = $this->createMockField($key);
  890. $field->expects($this->any())
  891. ->method('isMultipart')
  892. ->will($this->returnValue(false));
  893. return $field;
  894. }
  895. protected function createMultipartMockField($key)
  896. {
  897. $field = $this->createMockField($key);
  898. $field->expects($this->any())
  899. ->method('isMultipart')
  900. ->will($this->returnValue(true));
  901. return $field;
  902. }
  903. protected function createMockTransformer()
  904. {
  905. return $this->getMock('Symfony\Component\Form\ValueTransformer\ValueTransformerInterface', array(), array(), '', false, false);
  906. }
  907. protected function createMockValidator()
  908. {
  909. return $this->getMock('Symfony\Component\Validator\ValidatorInterface');
  910. }
  911. protected function createMockCsrfProvider()
  912. {
  913. return $this->getMock('Symfony\Component\Form\CsrfProvider\CsrfProviderInterface');
  914. }
  915. protected function createPostRequest(array $values = array(), array $files = array())
  916. {
  917. $server = array('REQUEST_METHOD' => 'POST');
  918. return new Request(array(), $values, array(), array(), $files, $server);
  919. }
  920. }