123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197 |
- <?php
- /*
- * This file is part of the Symfony package.
- *
- * (c) Fabien Potencier <fabien@symfony.com>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
- namespace Symfony\Tests\Component\Form;
- require_once __DIR__ . '/TestCase.php';
- require_once __DIR__ . '/Fixtures/Author.php';
- require_once __DIR__ . '/Fixtures/TestForm.php';
- use Symfony\Component\Form\Form;
- use Symfony\Component\Form\FormContext;
- use Symfony\Component\Form\Field;
- use Symfony\Component\Form\FieldError;
- use Symfony\Component\Form\DataError;
- use Symfony\Component\Form\HiddenField;
- use Symfony\Component\Form\PropertyPath;
- use Symfony\Component\Form\DataTransformer\CallbackTransformer;
- use Symfony\Component\HttpFoundation\Request;
- use Symfony\Component\HttpFoundation\File\UploadedFile;
- use Symfony\Component\Validator\ConstraintViolation;
- use Symfony\Component\Validator\ConstraintViolationList;
- use Symfony\Component\Validator\ExecutionContext;
- use Symfony\Tests\Component\Form\Fixtures\Author;
- use Symfony\Tests\Component\Form\Fixtures\TestForm;
- class FormTest_PreconfiguredForm extends Form
- {
- protected function configure()
- {
- $this->add($this->factory->create('field', 'firstName'));
- parent::configure();
- }
- }
- class FormTest_AuthorWithoutRefSetter
- {
- protected $reference;
- protected $referenceCopy;
- public function __construct($reference)
- {
- $this->reference = $reference;
- $this->referenceCopy = $reference;
- }
- // The returned object should be modified by reference without having
- // to provide a setReference() method
- public function getReference()
- {
- return $this->reference;
- }
- // The returned object is a copy, so setReferenceCopy() must be used
- // to update it
- public function getReferenceCopy()
- {
- return is_object($this->referenceCopy) ? clone $this->referenceCopy : $this->referenceCopy;
- }
- public function setReferenceCopy($reference)
- {
- $this->referenceCopy = $reference;
- }
- }
- class TestSetDataBeforeConfigureForm extends Form
- {
- protected $testCase;
- protected $object;
- public function __construct($testCase, $name, $object, $validator)
- {
- $this->testCase = $testCase;
- $this->object = $object;
- parent::__construct($name, $object, $validator);
- }
- protected function configure()
- {
- $this->testCase->assertEquals($this->object, $this->getData());
- parent::configure();
- }
- }
- class FormTest extends TestCase
- {
- protected $form;
- public static function setUpBeforeClass()
- {
- @session_start();
- }
- protected function setUp()
- {
- parent::setUp();
- $this->form = $this->factory->create('form', 'author');
- }
- public function testCsrfProtectionByDefault()
- {
- $builder = $this->factory->createBuilder('form', 'author');
- $form = $builder->getInstance();
- $this->assertTrue($builder->hasCsrfProtection());
- $this->assertTrue($form->has($builder->getCsrfFieldName()));
- }
- public function testCsrfProtectionCanBeDisabled()
- {
- $form = $this->factory->create('form', 'author', array(
- 'csrf_protection' => false,
- ));
- $this->assertEquals(0, count($form));
- }
- public function testCsrfFieldNameCanBeSet()
- {
- $form = $this->factory->create('form', 'author', array(
- 'csrf_field_name' => 'foobar',
- ));
- $this->assertTrue($form->has('foobar'));
- $this->assertEquals(1, count($form));
- }
- public function testCsrfProtectedFormsHaveExtraField()
- {
- $this->markTestSkipped('CSRF protection needs to be fixed');
- $provider = $this->createMockCsrfProvider();
- $provider->expects($this->once())
- ->method('generateCsrfToken')
- ->with($this->equalTo('Symfony\Component\Form\Form'))
- ->will($this->returnValue('ABCDEF'));
- $form = $this->factory->create('form', 'author', array(
- 'csrf_provider' => $provider,
- ));
- $this->assertTrue($form->has($this->form->getCsrfFieldName()));
- $field = $form->get($form->getCsrfFieldName());
- $this->assertTrue($field instanceof HiddenField);
- $this->assertEquals('ABCDEF', $field->getTransformedData());
- }
- public function testIsCsrfTokenValidPassesIfCsrfProtectionIsDisabled()
- {
- $this->markTestSkipped('CSRF protection needs to be fixed');
- $this->form->bind(array());
- $this->assertTrue($this->form->isCsrfTokenValid());
- }
- public function testIsCsrfTokenValidPasses()
- {
- $this->markTestSkipped('CSRF protection needs to be fixed');
- $provider = $this->createMockCsrfProvider();
- $provider->expects($this->once())
- ->method('isCsrfTokenValid')
- ->with($this->equalTo('Symfony\Component\Form\Form'), $this->equalTo('ABCDEF'))
- ->will($this->returnValue(true));
- $form = $this->factory->create('form', 'author', array(
- 'csrf_provider' => $provider,
- 'validator' => $this->validator,
- ));
- $field = $form->getCsrfFieldName();
- $form->bind(array($field => 'ABCDEF'));
- $this->assertTrue($form->isCsrfTokenValid());
- }
- public function testIsCsrfTokenValidFails()
- {
- $this->markTestSkipped('CSRF protection needs to be fixed');
- $provider = $this->createMockCsrfProvider();
- $provider->expects($this->once())
- ->method('isCsrfTokenValid')
- ->with($this->equalTo('Symfony\Component\Form\Form'), $this->equalTo('ABCDEF'))
- ->will($this->returnValue(false));
- $form = $this->factory->create('form', 'author', array(
- 'csrf_provider' => $provider,
- 'validator' => $this->validator,
- ));
- $field = $form->getCsrfFieldName();
- $form->bind(array($field => 'ABCDEF'));
- $this->assertFalse($form->isCsrfTokenValid());
- }
- public function testValidationGroupNullByDefault()
- {
- $this->assertNull($this->form->getAttribute('validation_groups'));
- }
- public function testValidationGroupsCanBeSetToString()
- {
- $form = $this->factory->create('form', 'author', array(
- 'validation_groups' => 'group',
- ));
- $this->assertEquals(array('group'), $form->getAttribute('validation_groups'));
- }
- public function testValidationGroupsCanBeSetToArray()
- {
- $form = $this->factory->create('form', 'author', array(
- 'validation_groups' => array('group1', 'group2'),
- ));
- $this->assertEquals(array('group1', 'group2'), $form->getAttribute('validation_groups'));
- }
- public function testBindValidatesData()
- {
- $builder = $this->factory->createBuilder('form', 'author', array(
- 'validation_groups' => 'group',
- ));
- $builder->add('field', 'firstName');
- $form = $builder->getInstance();
- $this->validator->expects($this->once())
- ->method('validate')
- ->with($this->equalTo($form));
- // specific data is irrelevant
- $form->bind(array());
- }
- public function testBindDoesNotValidateArrays()
- {
- $builder = $this->factory->createBuilder('form', 'author');
- $builder->add('field', 'firstName');
- $form = $builder->getInstance();
- // only the form is validated
- $this->validator->expects($this->once())
- ->method('validate')
- ->with($this->equalTo($form));
- // specific data is irrelevant
- $form->bind(array());
- }
- public function testBindReadsRequestData()
- {
- $path = tempnam(sys_get_temp_dir(), 'sf2');
- touch($path);
- $values = array(
- 'author' => array(
- 'name' => 'Bernhard',
- 'image' => array('filename' => 'foobar.png'),
- ),
- );
- $files = array(
- 'author' => array(
- 'error' => array('image' => array('file' => UPLOAD_ERR_OK)),
- 'name' => array('image' => array('file' => 'upload.png')),
- 'size' => array('image' => array('file' => 123)),
- 'tmp_name' => array('image' => array('file' => $path)),
- 'type' => array('image' => array('file' => 'image/png')),
- ),
- );
- $builder = $this->factory->createBuilder('form', 'author');
- $builder->add('field', 'name');
- $builder->add('form', 'image');
- $builder->get('image')->add('field', 'file');
- $builder->get('image')->add('field', 'filename');
- $form = $builder->getInstance();
- $form->bindRequest($this->createPostRequest($values, $files));
- $file = new UploadedFile($path, 'upload.png', 'image/png', 123, UPLOAD_ERR_OK);
- $this->assertEquals('Bernhard', $form['name']->getData());
- $this->assertEquals('foobar.png', $form['image']['filename']->getData());
- $this->assertEquals($file, $form['image']['file']->getData());
- }
- public function testSupportsArrayAccess()
- {
- $builder = $this->factory->createBuilder('form', 'author');
- $builder->add('field', 'firstName');
- $form = $builder->getInstance();
- $this->assertEquals($form->get('firstName'), $form['firstName']);
- $this->assertTrue(isset($form['firstName']));
- }
- /**
- * @expectedException BadMethodCallException
- */
- public function testSupportsUnset()
- {
- $form = $this->factory->create('form', 'author');
- unset($form['firstName']);
- }
- public function testDoesNotSupportAddingFields()
- {
- $form = $this->factory->create('form', 'author');
- $this->setExpectedException('LogicException');
- $form[] = $this->createMockField('lastName');
- }
- public function testSupportsCountable()
- {
- $builder = $this->factory->createBuilder('form', 'group', array(
- 'csrf_protection' => false,
- ));
- $builder->add('field', 'firstName');
- $builder->add('field', 'lastName');
- $form = $builder->getInstance();
- $this->assertEquals(2, count($form));
- }
- public function testSupportsIterable()
- {
- $builder = $this->factory->createBuilder('form', 'group', array(
- 'csrf_protection' => false,
- ));
- $builder->add('field', 'field1');
- $builder->add('field', 'field2');
- $builder->add('field', 'field3');
- $form = $builder->getInstance();
- $expected = array(
- 'field1' => $form->get('field1'),
- 'field2' => $form->get('field2'),
- 'field3' => $form->get('field3'),
- );
- $this->assertEquals($expected, iterator_to_array($form));
- }
- public function testIsBound()
- {
- $form = $this->factory->create('form', 'author');
- $this->assertFalse($form->isBound());
- $form->bind(array('firstName' => 'Bernhard'));
- $this->assertTrue($form->isBound());
- }
- public function testValidIfAllFieldsAreValid()
- {
- $builder = $this->factory->createBuilder('form', 'author');
- $builder->add('field', 'firstName');
- $builder->add('field', 'lastName');
- $form = $builder->getInstance();
- $form->bind(array('firstName' => 'Bernhard', 'lastName' => 'Potencier'));
- $this->assertTrue($form->isValid());
- }
- public function testInvalidIfFieldIsInvalid()
- {
- $this->markTestSkipped('How to force an invalid field?');
- $builder = $this->factory->createBuilder('form', 'author');
- $builder->add('field', 'firstName');
- $builder->add('field', 'lastName'); // how to make invalid?
- $form = $builder->getInstance();
- $form->bind(array('firstName' => 'Bernhard', 'lastName' => 'Potencier'));
- $this->assertFalse($form->isValid());
- }
- public function testInvalidIfBoundWithExtraFields()
- {
- $builder = $this->factory->createBuilder('form', 'author');
- $builder->add('field', 'firstName');
- $builder->add('field', 'lastName');
- $form = $builder->getInstance();
- $form->bind(array('foo' => 'bar', 'firstName' => 'Bernhard', 'lastName' => 'Potencier'));
- $this->assertTrue($form->isBoundWithExtraFields());
- }
- public function testHasNoErrorsIfOnlyFieldHasErrors()
- {
- $builder = $this->factory->createBuilder('form', 'author');
- $builder->add('field', 'firstName');
- $form = $builder->getInstance();
- $form->bind(array('firstName' => 'Bernhard'));
- $this->assertFalse($form->hasErrors());
- }
- public function testSubmitForwardsNullIfValueIsMissing()
- {
- $this->markTestSkipped('Currently does not work');
- $field = $this->createMockField('firstName');
- $field->expects($this->once())
- ->method('bind')
- ->with($this->equalTo(null));
- $form = $this->factory->create('form', 'author');
- $form->add($field);
- $form->bind(array());
- }
- public function testAddErrorMapsFieldValidationErrorsOntoFields()
- {
- $this->markTestSkipped('Currently does not work');
- $error = new FieldError('Message');
- $field = $this->createMockField('firstName');
- $field->expects($this->once())
- ->method('addError')
- ->with($this->equalTo($error));
- $form = $this->factory->create('form', 'author');
- $form->add($field);
- $path = new PropertyPath('fields[firstName].data');
- $form->addError(new FieldError('Message'), $path->getIterator());
- }
- public function testAddErrorMapsFieldValidationErrorsOntoFieldsWithinNestedForms()
- {
- $this->markTestSkipped('Currently does not work');
- $error = new FieldError('Message');
- $field = $this->createMockField('firstName');
- $field->expects($this->once())
- ->method('addError')
- ->with($this->equalTo($error));
- $form = $this->factory->create('form', 'author');
- $innerGroup = $this->factory->create('form', 'names');
- $innerGroup->add($field);
- $form->add($innerGroup);
- $path = new PropertyPath('fields[names].fields[firstName].data');
- $form->addError(new FieldError('Message'), $path->getIterator());
- }
- public function testAddErrorKeepsFieldValidationErrorsIfFieldNotFound()
- {
- $this->markTestSkipped('Currently does not work');
- $field = $this->createMockField('foo');
- $field->expects($this->never())
- ->method('addError');
- $form = $this->factory->create('form', 'author');
- $form->add($field);
- $path = new PropertyPath('fields[bar].data');
- $form->addError(new FieldError('Message'), $path->getIterator());
- $this->assertEquals(array(new FieldError('Message')), $form->getErrors());
- }
- public function testAddErrorKeepsFieldValidationErrorsIfFieldIsHidden()
- {
- $this->markTestSkipped('Currently does not work');
- $field = $this->createMockField('firstName');
- $field->expects($this->any())
- ->method('isHidden')
- ->will($this->returnValue(true));
- $field->expects($this->never())
- ->method('addError');
- $form = $this->factory->create('form', 'author');
- $form->add($field);
- $path = new PropertyPath('fields[firstName].data');
- $form->addError(new FieldError('Message'), $path->getIterator());
- $this->assertEquals(array(new FieldError('Message')), $form->getErrors());
- }
- public function testAddErrorMapsDataValidationErrorsOntoFields()
- {
- $this->markTestSkipped('Currently does not work');
- $error = new DataError('Message');
- // path is expected to point at "firstName"
- $expectedPath = new PropertyPath('firstName');
- $expectedPathIterator = $expectedPath->getIterator();
- $field = $this->createMockField('firstName');
- $field->expects($this->any())
- ->method('getPropertyPath')
- ->will($this->returnValue(new PropertyPath('firstName')));
- $field->expects($this->once())
- ->method('addError')
- ->with($this->equalTo($error), $this->equalTo($expectedPathIterator));
- $form = $this->factory->create('form', 'author');
- $form->add($field);
- $path = new PropertyPath('firstName');
- $form->addError($error, $path->getIterator());
- }
- public function testAddErrorKeepsDataValidationErrorsIfFieldNotFound()
- {
- $this->markTestSkipped('Currently does not work');
- $field = $this->createMockField('foo');
- $field->expects($this->any())
- ->method('getPropertyPath')
- ->will($this->returnValue(new PropertyPath('foo')));
- $field->expects($this->never())
- ->method('addError');
- $form = $this->factory->create('form', 'author');
- $form->add($field);
- $path = new PropertyPath('bar');
- $form->addError(new DataError('Message'), $path->getIterator());
- }
- public function testAddErrorKeepsDataValidationErrorsIfFieldIsHidden()
- {
- $this->markTestSkipped('Currently does not work');
- $field = $this->createMockField('firstName');
- $field->expects($this->any())
- ->method('isHidden')
- ->will($this->returnValue(true));
- $field->expects($this->any())
- ->method('getPropertyPath')
- ->will($this->returnValue(new PropertyPath('firstName')));
- $field->expects($this->never())
- ->method('addError');
- $form = $this->factory->create('form', 'author');
- $form->add($field);
- $path = new PropertyPath('firstName');
- $form->addError(new DataError('Message'), $path->getIterator());
- }
- public function testAddErrorMapsDataValidationErrorsOntoNestedFields()
- {
- $this->markTestSkipped('Currently does not work');
- $error = new DataError('Message');
- // path is expected to point at "street"
- $expectedPath = new PropertyPath('address.street');
- $expectedPathIterator = $expectedPath->getIterator();
- $expectedPathIterator->next();
- $field = $this->createMockField('address');
- $field->expects($this->any())
- ->method('getPropertyPath')
- ->will($this->returnValue(new PropertyPath('address')));
- $field->expects($this->once())
- ->method('addError')
- ->with($this->equalTo($error), $this->equalTo($expectedPathIterator));
- $form = $this->factory->create('form', 'author');
- $form->add($field);
- $path = new PropertyPath('address.street');
- $form->addError($error, $path->getIterator());
- }
- public function testAddErrorMapsErrorsOntoFieldsInVirtualGroups()
- {
- $this->markTestSkipped('Currently does not work');
- $error = new DataError('Message');
- // path is expected to point at "address"
- $expectedPath = new PropertyPath('address');
- $expectedPathIterator = $expectedPath->getIterator();
- $field = $this->createMockField('address');
- $field->expects($this->any())
- ->method('getPropertyPath')
- ->will($this->returnValue(new PropertyPath('address')));
- $field->expects($this->once())
- ->method('addError')
- ->with($this->equalTo($error), $this->equalTo($expectedPathIterator));
- $form = $this->factory->create('form', 'author');
- $nestedForm = $this->factory->create('form', 'nested', array('virtual' => true));
- $nestedForm->add($field);
- $form->add($nestedForm);
- $path = new PropertyPath('address');
- $form->addError($error, $path->getIterator());
- }
- public function testAddSetsFieldParent()
- {
- $this->markTestSkipped('Currently does not work');
- $form = $this->factory->create('form', 'author');
- $field = $this->createMockField('firstName');
- $field->expects($this->once())
- ->method('setParent')
- ->with($this->equalTo($form));
- $form->add($field);
- }
- public function testSetDataUpdatesAllFieldsFromTransformedData()
- {
- $originalAuthor = new Author();
- $transformedAuthor = new Author();
- $transformedAuthor->firstName = 'Foo';
- $transformedAuthor->setLastName('Bar');
- $transformer = $this->createMockTransformer();
- $transformer->expects($this->at(0))
- ->method('transform')
- ->with($this->equalTo(null))
- ->will($this->returnValue(''));
- $transformer->expects($this->at(1))
- ->method('transform')
- ->with($this->equalTo($originalAuthor))
- ->will($this->returnValue($transformedAuthor));
- $builder = $this->factory->createBuilder('form', 'author');
- $builder->setDataTransformer($transformer);
- $builder->setData($originalAuthor);
- $builder->add('field', 'firstName');
- $builder->add('field', 'lastName');
- $form = $builder->getInstance();
- $this->assertEquals('Foo', $form['firstName']->getData());
- $this->assertEquals('Bar', $form['lastName']->getData());
- }
- /**
- * The use case for this test are groups whose fields should be mapped
- * directly onto properties of the form's object.
- *
- * Example:
- *
- * <code>
- * $dateRangeField = $this->factory->create('form', 'dateRange');
- * $dateRangeField->add(new DateField('startDate'));
- * $dateRangeField->add(new DateField('endDate'));
- * $form->add($dateRangeField);
- * </code>
- *
- * If $dateRangeField is not virtual, the property "dateRange" must be
- * present on the form's object. In this property, an object or array
- * with the properties "startDate" and "endDate" is expected.
- *
- * If $dateRangeField is virtual though, it's children are mapped directly
- * onto the properties "startDate" and "endDate" of the form's object.
- */
- public function testSetDataSkipsVirtualForms()
- {
- $author = new Author();
- $author->firstName = 'Foo';
- $author->setLastName('Bar');
- $builder = $this->factory->createBuilder('form', 'author');
- $builder->setData($author);
- $builder->add('form', 'personalData', array(
- 'virtual' => true,
- ));
- // both fields are in the nested group but receive the object of the
- // top-level group because the nested group is virtual
- $builder->get('personalData')->add('field', 'firstName');
- $builder->get('personalData')->add('field', 'lastName');
- $form = $builder->getInstance();
- $this->assertEquals('Foo', $form['personalData']['firstName']->getData());
- $this->assertEquals('Bar', $form['personalData']['lastName']->getData());
- }
- public function testSetDataThrowsAnExceptionIfArgumentIsNotObjectOrArray()
- {
- $form = $this->factory->create('form', 'author');
- $this->setExpectedException('InvalidArgumentException');
- $form->setData('foobar');
- }
- /**
- * @expectedException Symfony\Component\Form\Exception\FormException
- */
- public function testSetDataMatchesAgainstDataClass_fails()
- {
- $form = $this->factory->create('form', 'author', array(
- 'data_class' => 'Symfony\Tests\Component\Form\Fixtures\Author',
- ));
- $form->setData(new \stdClass());
- }
- public function testSetDataMatchesAgainstDataClass_succeeds()
- {
- $form = $this->factory->create('form', 'author', array(
- 'data_class' => 'Symfony\Tests\Component\Form\Fixtures\Author',
- ));
- $form->setData(new Author());
- }
- public function testSetDataToNullCreatesObjectIfClassAvailable()
- {
- $form = $this->factory->create('form', 'author', array(
- 'data_class' => 'Symfony\Tests\Component\Form\Fixtures\Author',
- ));
- $form->setData(null);
- $this->assertEquals(new Author(), $form->getData());
- }
- public function testSetDataToNullUsesDataConstructorOption()
- {
- $author = new Author();
- $form = $this->factory->create('form', 'author', array(
- 'data_constructor' => function () use ($author) {
- return $author;
- }
- ));
- $form->setData(null);
- $this->assertSame($author, $form->getData());
- }
- /*
- * We need something to write the field values into
- */
- public function testSetDataToNullCreatesArrayIfNoDataClassOrConstructor()
- {
- $author = new Author();
- $form = $this->factory->create('form', 'author');
- $form->setData(null);
- $this->assertSame(array(), $form->getData());
- }
- public function testSubmitUpdatesTransformedDataFromAllFields()
- {
- $originalAuthor = new Author();
- $transformedAuthor = new Author();
- $transformer = $this->createMockTransformer();
- $transformer->expects($this->at(0))
- ->method('transform')
- ->with($this->equalTo(null))
- ->will($this->returnValue(''));
- $transformer->expects($this->at(1))
- ->method('transform')
- ->with($this->equalTo($originalAuthor))
- ->will($this->returnValue($transformedAuthor));
- $builder = $this->factory->createBuilder('form', 'author');
- $builder->setDataTransformer($transformer);
- $builder->add('field', 'firstName');
- $builder->add('field', 'lastName');
- $builder->setData($originalAuthor);
- $form = $builder->getInstance();
- $form->bind(array(
- 'firstName' => 'Foo',
- 'lastName' => 'Bar',
- ));
- $this->assertEquals('Foo', $transformedAuthor->firstName);
- $this->assertEquals('Bar', $transformedAuthor->getLastName());
- }
- public function testGetDataReturnsObject()
- {
- $form = $this->factory->create('form', 'author');
- $object = new \stdClass();
- $form->setData($object);
- $this->assertEquals($object, $form->getData());
- }
- public function testSubmitWithoutPriorSetData()
- {
- $this->markTestSkipped('Currently does not work');
- $field = $this->createMockField('firstName');
- $field->expects($this->any())
- ->method('getData')
- ->will($this->returnValue('Bernhard'));
- $form = $this->factory->create('form', 'author');
- $form->add($field);
- $form->bind(array('firstName' => 'Bernhard'));
- $this->assertEquals(array('firstName' => 'Bernhard'), $form->getData());
- }
- public function testValidateData()
- {
- $graphWalker = $this->createMockGraphWalker();
- $metadataFactory = $this->createMockMetadataFactory();
- $context = new ExecutionContext('Root', $graphWalker, $metadataFactory);
- $object = $this->getMock('\stdClass');
- $form = $this->factory->create('form', 'author', array('validation_groups' => array(
- 'group1',
- 'group2',
- )));
- $graphWalker->expects($this->exactly(2))
- ->method('walkReference')
- ->with($object,
- // should test for groups - PHPUnit limitation
- $this->anything(),
- 'data',
- true);
- $form->setData($object);
- $form->validateData($context);
- }
- public function testValidateDataAppendsPropertyPath()
- {
- $graphWalker = $this->createMockGraphWalker();
- $metadataFactory = $this->createMockMetadataFactory();
- $context = new ExecutionContext('Root', $graphWalker, $metadataFactory);
- $context->setPropertyPath('path');
- $object = $this->getMock('\stdClass');
- $form = $this->factory->create('form', 'author');
- $graphWalker->expects($this->once())
- ->method('walkReference')
- ->with($object, null, 'path.data', true);
- $form->setData($object);
- $form->validateData($context);
- }
- public function testValidateDataSetsCurrentPropertyToData()
- {
- $graphWalker = $this->createMockGraphWalker();
- $metadataFactory = $this->createMockMetadataFactory();
- $context = new ExecutionContext('Root', $graphWalker, $metadataFactory);
- $object = $this->getMock('\stdClass');
- $form = $this->factory->create('form', 'author');
- $test = $this;
- $graphWalker->expects($this->once())
- ->method('walkReference')
- ->will($this->returnCallback(function () use ($context, $test) {
- $test->assertEquals('data', $context->getCurrentProperty());
- }));
- $form->setData($object);
- $form->validateData($context);
- }
- public function testValidateDataDoesNotWalkScalars()
- {
- $graphWalker = $this->createMockGraphWalker();
- $metadataFactory = $this->createMockMetadataFactory();
- $context = new ExecutionContext('Root', $graphWalker, $metadataFactory);
- $dataTransformer = $this->createMockTransformer();
- $builder = $this->factory->createBuilder('form', 'author');
- $builder->setDataTransformer($dataTransformer);
- $form = $builder->getInstance();
- $graphWalker->expects($this->never())
- ->method('walkReference');
- $dataTransformer->expects($this->atLeastOnce())
- ->method('reverseTransform')
- ->will($this->returnValue('foobar'));
- $form->bind(array('foo' => 'bar')); // reverse transformed to "foobar"
- $form->validateData($context);
- }
- public function testSubformDoesntCallSetters()
- {
- $author = new FormTest_AuthorWithoutRefSetter(new Author());
- $builder = $this->factory->createBuilder('form', 'author');
- $builder->add('form', 'reference');
- $builder->get('reference')->add('field', 'firstName');
- $builder->setData($author);
- $form = $builder->getInstance();
- $form->bind(array(
- // reference has a getter, but not setter
- 'reference' => array(
- 'firstName' => 'Foo',
- )
- ));
- $this->assertEquals('Foo', $author->getReference()->firstName);
- }
- public function testSubformCallsSettersIfTheObjectChanged()
- {
- // no reference
- $author = new FormTest_AuthorWithoutRefSetter(null);
- $newReference = new Author();
- $builder = $this->factory->createBuilder('form', 'author');
- $builder->add('form', 'referenceCopy');
- $builder->get('referenceCopy')->add('field', 'firstName');
- $builder->setData($author);
- $form = $builder->getInstance();
- $form['referenceCopy']->setData($newReference); // new author object
- $form->bind(array(
- // referenceCopy has a getter that returns a copy
- 'referenceCopy' => array(
- 'firstName' => 'Foo',
- )
- ));
- $this->assertEquals('Foo', $author->getReferenceCopy()->firstName);
- }
- public function testSubformCallsSettersIfByReferenceIsFalse()
- {
- $author = new FormTest_AuthorWithoutRefSetter(new Author());
- $builder = $this->factory->createBuilder('form', 'author');
- $builder->add('form', 'referenceCopy', array('by_reference' => false));
- $builder->get('referenceCopy')->add('field', 'firstName');
- $builder->setData($author);
- $form = $builder->getInstance();
- $form->bind(array(
- // referenceCopy has a getter that returns a copy
- 'referenceCopy' => array(
- 'firstName' => 'Foo',
- )
- ));
- // firstName can only be updated if setReferenceCopy() was called
- $this->assertEquals('Foo', $author->getReferenceCopy()->firstName);
- }
- public function testSubformCallsSettersIfReferenceIsScalar()
- {
- $author = new FormTest_AuthorWithoutRefSetter('scalar');
- $builder = $this->factory->createBuilder('form', 'author');
- $builder->add('form', 'referenceCopy');
- $builder->get('referenceCopy')->setDataTransformer(new CallbackTransformer(
- function () {},
- function ($value) { // reverseTransform
- return 'foobar';
- }
- ));
- $builder->setData($author);
- $form = $builder->getInstance();
- $form->bind(array(
- 'referenceCopy' => array(), // doesn't matter actually
- ));
- // firstName can only be updated if setReferenceCopy() was called
- $this->assertEquals('foobar', $author->getReferenceCopy());
- }
- public function testSubformAlwaysInsertsIntoArrays()
- {
- $ref1 = new Author();
- $ref2 = new Author();
- $author = array('referenceCopy' => $ref1);
- $builder = $this->factory->createBuilder('form', 'author');
- $builder->setData($author);
- $builder->add('form', 'referenceCopy', array(
- 'value_transformer' => new CallbackTransformer(
- function () {},
- function ($value) use ($ref2) { // reverseTransform
- return $ref2;
- }
- )
- ));
- $form = $builder->getInstance();
- $form->bind(array(
- 'referenceCopy' => array('a' => 'b'), // doesn't matter actually
- ));
- // the new reference was inserted into the array
- $author = $form->getData();
- $this->assertSame($ref2, $author['referenceCopy']);
- }
- public function testIsEmptyReturnsTrueIfAllFieldsAreEmpty()
- {
- $builder = $this->factory->createBuilder('form', 'name');
- $builder->add('field', 'foo', array('data' => ''));
- $builder->add('field', 'bar', array('data' => null));
- $form = $builder->getInstance();
- $this->assertTrue($form->isEmpty());
- }
- public function testIsEmptyReturnsFalseIfAnyFieldIsFilled()
- {
- $builder = $this->factory->createBuilder('form', 'name');
- $builder->add('field', 'foo', array('data' => 'baz'));
- $builder->add('field', 'bar', array('data' => null));
- $form = $builder->getInstance();
- $this->assertFalse($form->isEmpty());
- }
- /**
- * Create a group containing two fields, "visibleField" and "hiddenField"
- *
- * @return Form
- */
- protected function getGroupWithBothVisibleAndHiddenField()
- {
- $form = $this->factory->create('form', 'testGroup');
- // add a visible field
- $visibleField = $this->createMockField('visibleField');
- $visibleField->expects($this->once())
- ->method('isHidden')
- ->will($this->returnValue(false));
- $form->add($visibleField);
- // add a hidden field
- $hiddenField = $this->createMockField('hiddenField');
- $hiddenField->expects($this->once())
- ->method('isHidden')
- ->will($this->returnValue(true));
- $form->add($hiddenField);
- return $form;
- }
- protected function createMockField($key)
- {
- $field = $this->getMock(
- 'Symfony\Component\Form\FieldInterface',
- array(),
- array(),
- '',
- false, // don't use constructor
- false // don't call parent::__clone
- );
- $field->expects($this->any())
- ->method('getName')
- ->will($this->returnValue($key));
- return $field;
- }
- protected function createMockForm()
- {
- $form = $this->getMock(
- 'Symfony\Component\Form\Form',
- array(),
- array(),
- '',
- false, // don't use constructor
- false // don't call parent::__clone)
- );
- $form->expects($this->any())
- ->method('getRoot')
- ->will($this->returnValue($form));
- return $form;
- }
- protected function createInvalidMockField($key)
- {
- $field = $this->createMockField($key);
- $field->expects($this->any())
- ->method('isValid')
- ->will($this->returnValue(false));
- return $field;
- }
- protected function createValidMockField($key)
- {
- $field = $this->createMockField($key);
- $field->expects($this->any())
- ->method('isValid')
- ->will($this->returnValue(true));
- return $field;
- }
- protected function createNonMultipartMockField($key)
- {
- $field = $this->createMockField($key);
- $field->expects($this->any())
- ->method('isMultipart')
- ->will($this->returnValue(false));
- return $field;
- }
- protected function createMultipartMockField($key)
- {
- $field = $this->createMockField($key);
- $field->expects($this->any())
- ->method('isMultipart')
- ->will($this->returnValue(true));
- return $field;
- }
- protected function createMockTransformer()
- {
- return $this->getMock('Symfony\Component\Form\DataTransformer\DataTransformerInterface', array(), array(), '', false, false);
- }
- protected function createMockValidator()
- {
- return $this->getMock('Symfony\Component\Validator\ValidatorInterface');
- }
- protected function createMockCsrfProvider()
- {
- return $this->getMock('Symfony\Component\Form\CsrfProvider\CsrfProviderInterface');
- }
- protected function createMockGraphWalker()
- {
- return $this->getMockBuilder('Symfony\Component\Validator\GraphWalker')
- ->disableOriginalConstructor()
- ->getMock();
- }
- protected function createMockMetadataFactory()
- {
- return $this->getMock('Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface');
- }
- protected function createPostRequest(array $values = array(), array $files = array())
- {
- $server = array('REQUEST_METHOD' => 'POST');
- return new Request(array(), $values, array(), array(), $files, $server);
- }
- }
|