Browse Source

[Form] Implemented UrlField

Bernhard Schussek 14 năm trước cách đây
mục cha
commit
733290c112

+ 42 - 0
src/Symfony/Component/Form/UrlField.php

@@ -0,0 +1,42 @@
+<?php
+
+namespace Symfony\Component\Form;
+
+/*
+ * This file is part of the Symfony framework.
+ *
+ * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
+ *
+ * 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 <bernhard.schussek@symfony-project.com>
+ */
+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;
+    }
+}

+ 56 - 0
tests/Symfony/Tests/Component/Form/UrlFieldTest.php

@@ -0,0 +1,56 @@
+<?php
+
+namespace Symfony\Tests\Component\Form;
+
+require_once __DIR__ . '/LocalizedTestCase.php';
+
+use Symfony\Component\Form\UrlField;
+
+class UrlFieldTest extends LocalizedTestCase
+{
+    public function testBindAddsDefaultProtocolIfNoneIsIncluded()
+    {
+        $field = new UrlField('name');
+
+        $field->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());
+    }
+}