diff --git a/src/Forms/UrlField.php b/src/Forms/UrlField.php index 4d5493fc6..4904b79df 100644 --- a/src/Forms/UrlField.php +++ b/src/Forms/UrlField.php @@ -53,12 +53,12 @@ class UrlField extends TextField } /** - * Set which protocols valid URLs are allowed to have + * Set which protocols valid URLs are allowed to have. + * Passing an empty array will result in using configured defaults. */ public function setAllowedProtocols(array $protocols): static { - // Ensure the array isn't associative so we can use 0 index in validate(). - $this->protocols = array_keys($protocols); + $this->protocols = $protocols; return $this; } @@ -67,10 +67,12 @@ class UrlField extends TextField */ public function getAllowedProtocols(): array { - if (empty($this->protocols)) { - return static::config()->get('default_protocols'); + $protocols = $this->protocols; + if (empty($protocols)) { + $protocols = static::config()->get('default_protocols'); } - return $this->protocols; + // Ensure the array isn't associative so we can use 0 index in validate(). + return array_values($protocols); } /** diff --git a/tests/php/Forms/UrlFieldTest.php b/tests/php/Forms/UrlFieldTest.php index 077a85e79..07f9fbfd3 100644 --- a/tests/php/Forms/UrlFieldTest.php +++ b/tests/php/Forms/UrlFieldTest.php @@ -89,4 +89,23 @@ class UrlFieldTest extends SapphireTest $expectedCount = $valid ? 0 : 1; $this->assertEquals($expectedCount, count($validator->getErrors())); } + + public function testAllowedProtocols(): void + { + $field = new UrlField('MyUrl'); + // Defaults should be http and https + $this->assertSame(['https', 'http'], $field->getAllowedProtocols()); + + // Defaults change with config, and ignore keys + UrlField::config()->set('default_protocols', ['my-key' => 'ftp']); + $this->assertSame(['ftp'], $field->getAllowedProtocols()); + + // Can set explicit protocols - again keys are ignored + $field->setAllowedProtocols(['http', 'key' => 'irc', 'nntp']); + $this->assertSame(['http', 'irc', 'nntp'], $field->getAllowedProtocols()); + + // Can reset back to config defaults + $field->setAllowedProtocols([]); + $this->assertSame(['ftp'], $field->getAllowedProtocols()); + } }