Better name validation code.

This commit is contained in:
Pachira 2024-06-03 22:12:37 +00:00
parent e40e393b0c
commit 572b46580a
2 changed files with 18 additions and 3 deletions

View file

@ -34,8 +34,16 @@ class DbConfig implements IConfig {
}
public static function validateName(string $name): bool {
// this should better validate the format, this allows for a lot of shittery
return preg_match('#^([a-z][a-zA-Z0-9._]+)$#', $name) === 1;
$parts = explode('.', $name);
foreach($parts as $part) {
if($part === '' || trim($part) !== $part)
return false;
if(preg_match('#^([a-z][a-zA-Z0-9_]+)$#', $part) !== 1)
return false;
}
return true;
}
/**
@ -221,6 +229,5 @@ class DbConfig implements IConfig {
$stmt->addParameter(2, serialize($value));
$stmt->execute();
}
}
}

View file

@ -144,4 +144,12 @@ final class DbConfigTest extends TestCase {
$this->assertEquals([1234, 56.789, 'Mewow!', true, 'jeff'], $this->config->getArray('test.array'));
$this->assertEquals(false, $this->config->getBoolean('test.array'));
}
public function testNameValidation(): void {
$this->assertTrue(\Syokuhou\DbConfig::validateName('th1s.iS.vAL1d'));
$this->assertFalse(\Syokuhou\DbConfig::validateName(''));
$this->assertFalse(\Syokuhou\DbConfig::validateName('this..is.not.valid'));
$this->assertFalse(\Syokuhou\DbConfig::validateName('this..is.not.valid'));
$this->assertFalse(\Syokuhou\DbConfig::validateName('First.may.Not.be.uppercase'));
}
}