Config: Properly prevent keys getting transformed into bools

The original regex almost completely failed at its objective, because it a) only worked if there was no value for the key, and b) did not prevent all such occurrences getting transformed, while quoting patterns that would not get transformed anyway.
This commit is contained in:
Dylan K. Taylor 2018-08-18 16:35:39 +01:00
parent b4694092b7
commit 3892f2f404
2 changed files with 72 additions and 1 deletions

View File

@ -111,7 +111,7 @@ class Config{
* @return string
*/
public static function fixYAMLIndexes(string $str) : string{
return preg_replace("#^([ ]*)([a-zA-Z_]{1}[ ]*)\\:$#m", "$1\"$2\":", $str);
return preg_replace("#^( *)(y|Y|yes|Yes|YES|n|N|no|No|NO|true|True|TRUE|false|False|FALSE|on|On|ON|off|Off|OFF)( *)\:#m", "$1\"$2\"$3:", $str);
}
/**

View File

@ -0,0 +1,71 @@
<?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
declare(strict_types=1);
namespace pocketmine\utils;
use PHPUnit\Framework\TestCase;
class ConfigTest extends TestCase{
/**
* @return \Generator
*/
public function fixYamlIndexesProvider() : \Generator{
yield ["x: 1\ny: 2\nz: 3\n", [
"x" => 1,
"y" => 2,
"z" => 3
]];
yield [" x : 1\n y : 2\n z : 3\n", [
"x" => 1,
"y" => 2,
"z" => 3
]];
yield ["parent:\n x: 1\n y: 2\n z: 3\n", [
"parent" => [
"x" => 1,
"y" => 2,
"z" => 3
]
]];
yield ["yes: notransform", [
"yes" => "notransform"
]];
yield ["on: 1\nyes: true", [ //this would previously have resulted in a key collision
"on" => 1,
"yes" => true
]];
}
/**
* @dataProvider fixYamlIndexesProvider
*
* @param string $test
* @param array $expected
*/
public function testFixYamlIndexes(string $test, array $expected) : void{
$fixed = Config::fixYAMLIndexes($test);
$decoded = yaml_parse($fixed);
self::assertEquals($expected, $decoded);
}
}