FIX Get array values, not keys (#11414)

This commit is contained in:
Guy Sartorelli 2024-10-03 10:30:18 +13:00 committed by GitHub
parent 7f11bf3587
commit 33929e2992
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 27 additions and 6 deletions

View File

@ -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 public function setAllowedProtocols(array $protocols): static
{ {
// Ensure the array isn't associative so we can use 0 index in validate(). $this->protocols = $protocols;
$this->protocols = array_keys($protocols);
return $this; return $this;
} }
@ -67,10 +67,12 @@ class UrlField extends TextField
*/ */
public function getAllowedProtocols(): array public function getAllowedProtocols(): array
{ {
if (empty($this->protocols)) { $protocols = $this->protocols;
return static::config()->get('default_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);
} }
/** /**

View File

@ -89,4 +89,23 @@ class UrlFieldTest extends SapphireTest
$expectedCount = $valid ? 0 : 1; $expectedCount = $valid ? 0 : 1;
$this->assertEquals($expectedCount, count($validator->getErrors())); $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());
}
} }