diff --git a/src/Symfony/Component/Form/UrlField.php b/src/Symfony/Component/Form/UrlField.php new file mode 100644 index 000000000000..fb1b2bc9b574 --- /dev/null +++ b/src/Symfony/Component/Form/UrlField.php @@ -0,0 +1,42 @@ + + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +/** + * Field for entering URLs + * + * @author Bernhard Schussek + */ +class UrlField extends InputField +{ + /** + * {@inheritDoc} + */ + protected function configure() + { + $this->addOption('default_protocol', 'http'); + } + + /** + * {@inheritDoc} + */ + protected function processData($data) + { + $protocol = $this->getOption('default_protocol'); + + if ($protocol && $data && !preg_match('~^\w+://~', $data)) { + $data = $protocol . '://' . $data; + } + + return $data; + } +} diff --git a/tests/Symfony/Tests/Component/Form/UrlFieldTest.php b/tests/Symfony/Tests/Component/Form/UrlFieldTest.php new file mode 100644 index 000000000000..c3e560f3e5f4 --- /dev/null +++ b/tests/Symfony/Tests/Component/Form/UrlFieldTest.php @@ -0,0 +1,56 @@ +bind('www.domain.com'); + + $this->assertSame('http://www.domain.com', $field->getData()); + $this->assertSame('http://www.domain.com', $field->getDisplayedData()); + } + + public function testBindAddsNoDefaultProtocolIfAlreadyIncluded() + { + $field = new UrlField('name', array( + 'default_protocol' => 'http', + )); + + $field->bind('ftp://www.domain.com'); + + $this->assertSame('ftp://www.domain.com', $field->getData()); + $this->assertSame('ftp://www.domain.com', $field->getDisplayedData()); + } + + public function testBindAddsNoDefaultProtocolIfEmpty() + { + $field = new UrlField('name', array( + 'default_protocol' => 'http', + )); + + $field->bind(''); + + $this->assertSame(null, $field->getData()); + $this->assertSame('', $field->getDisplayedData()); + } + + public function testBindAddsNoDefaultProtocolIfSetToNull() + { + $field = new UrlField('name', array( + 'default_protocol' => null, + )); + + $field->bind('www.domain.com'); + + $this->assertSame('www.domain.com', $field->getData()); + $this->assertSame('www.domain.com', $field->getDisplayedData()); + } +} \ No newline at end of file