FormTest.php 37 KB

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