RegionLoader: Switch to using named constructors

this makes the code more self-descriptive, and also helps to detect potential bugs.
This commit is contained in:
Dylan K. Taylor
2021-04-15 21:57:23 +01:00
parent e8dd4de5c8
commit 5d83f4670a
4 changed files with 56 additions and 22 deletions

View File

@ -83,30 +83,45 @@ class RegionLoader{
/**
* @throws CorruptedRegionException
*/
public function __construct(string $filePath){
private function __construct(string $filePath){
$this->filePath = $filePath;
$this->garbageTable = new RegionGarbageMap([]);
clearstatcache(false, $this->filePath);
$exists = file_exists($this->filePath);
if(!$exists){
touch($this->filePath);
}elseif(filesize($this->filePath) % 4096 !== 0){
throw new CorruptedRegionException("Region file should be padded to a multiple of 4KiB");
}
$this->lastUsed = time();
$filePointer = fopen($this->filePath, "r+b");
if($filePointer === false) throw new AssumptionFailedError("fopen() should not fail here");
$this->filePointer = $filePointer;
stream_set_read_buffer($this->filePointer, 1024 * 16); //16KB
stream_set_write_buffer($this->filePointer, 1024 * 16); //16KB
if(!$exists){
$this->createBlank();
}else{
$this->loadLocationTable();
}
/**
* @throws CorruptedRegionException
*/
public static function loadExisting(string $filePath) : self{
clearstatcache(false, $filePath);
if(!file_exists($filePath)){
throw new \RuntimeException("File $filePath does not exist");
}
if(filesize($filePath) % 4096 !== 0){
throw new CorruptedRegionException("Region file should be padded to a multiple of 4KiB");
}
$this->lastUsed = time();
$result = new self($filePath);
$result->loadLocationTable();
return $result;
}
public static function createNew(string $filePath) : self{
clearstatcache(false, $filePath);
if(file_exists($filePath)){
throw new \RuntimeException("Region file $filePath already exists");
}
touch($filePath);
$result = new self($filePath);
$result->createBlank();
return $result;
}
public function __destruct(){

View File

@ -114,7 +114,7 @@ abstract class RegionWorldProvider extends BaseWorldProvider{
$path = $this->pathToRegion($regionX, $regionZ);
try{
$this->regions[$index] = new RegionLoader($path);
$this->regions[$index] = RegionLoader::loadExisting($path);
}catch(CorruptedRegionException $e){
$logger = \GlobalLogger::get();
$logger->error("Corrupted region file detected: " . $e->getMessage());
@ -123,7 +123,7 @@ abstract class RegionWorldProvider extends BaseWorldProvider{
rename($path, $backupPath);
$logger->error("Corrupted region file has been backed up to " . $backupPath);
$this->regions[$index] = new RegionLoader($path); //this will create a new empty region to replace the corrupted one
$this->regions[$index] = RegionLoader::createNew($path);
}
}
return $this->regions[$index];