Issue #3056454 by Krzysztof Domański, John Cook, johndevman: Hexadecimal validation returns true if the color contains multiple hashes (e.g. '###FF0')

merge-requests/1119/head
Lee Rowlands 2019-06-28 06:43:27 +10:00
parent 006e17944f
commit de56b25930
No known key found for this signature in database
GPG Key ID: 2B829A3DF9204DC4
2 changed files with 58 additions and 10 deletions

View File

@ -18,16 +18,10 @@ class Color {
* TRUE if $hex is valid or FALSE if it is not.
*/
public static function validateHex($hex) {
// Must be a string.
$valid = is_string($hex);
// Hash prefix is optional.
$hex = ltrim($hex, '#');
// Must be either RGB or RRGGBB.
$length = mb_strlen($hex);
$valid = $valid && ($length === 3 || $length === 6);
// Must be a valid hex value.
$valid = $valid && ctype_xdigit($hex);
return $valid;
if (!is_string($hex)) {
return FALSE;
}
return preg_match('/^[#]?([0-9a-fA-F]{3}){1,2}$/', $hex) === 1;
}
/**

View File

@ -12,6 +12,60 @@ use PHPUnit\Framework\TestCase;
*/
class ColorTest extends TestCase {
/**
* @covers \Drupal\Component\Utility\Color::validateHex
*
* @param bool $expected
* The expected result of validation.
* @param string $value
* The hex color value.
*
* @dataProvider providerTestValidateHex()
*/
public function testValidateHex($expected, $value) {
$this->assertSame($expected, Color::validateHex($value));
}
/**
* Provides data for testValidateHex().
*/
public function providerTestValidateHex() {
return [
// Tests length.
[FALSE, ''],
[FALSE, '#'],
[FALSE, '1'],
[FALSE, '#1'],
[FALSE, '12'],
[FALSE, '#12'],
[TRUE, '123'],
[TRUE, '#123'],
[FALSE, '1234'],
[FALSE, '#1234'],
[FALSE, '12345'],
[FALSE, '#12345'],
[TRUE, '123456'],
[TRUE, '#123456'],
[FALSE, '1234567'],
[FALSE, '#1234567'],
// Tests valid hex value.
[TRUE, 'abcdef'],
[TRUE, 'ABCDEF'],
[TRUE, 'A0F1B1'],
[FALSE, 'WWW'],
[FALSE, '#123##'],
[FALSE, '@a0055'],
// Tests the data type.
[FALSE, 123456],
// Tests multiple hash prefix.
[FALSE, '###F00'],
// Tests spaces.
[FALSE, ' #123456'],
[FALSE, '123456 '],
[FALSE, '#12 3456'],
];
}
/**
* Tests Color::hexToRgb().
*