FormTest.php 45 KB

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