<?php
 class vB_RelatedText_Persist { use vB_Trait_NoSerialize; private $fp; public function __construct(string $filename, bool $read) { $this->fp = fopen($filename, ($read ? 'r' : 'w')); if (!$this->fp) { throw new Exception ('Could not open file ' . $filename); } } public function __destruct() { if ($this->fp) { fclose($this->fp); } } public function writeIntArray(array $array) : void { $string = ''; foreach ($array AS $key => $value) { $string .= strval($key) . ':' . strval($value) . "\n"; } $string .= "\n"; fwrite($this->fp, $string); } public function readIntArray() : array { $array = []; $line = fgets($this->fp); while ($line != "\n") { [$key, $value] = explode(':', rtrim($line), 2); $array[intval($key)] = intval($value); $line = fgets($this->fp); } return $array; } public function writeStringKeyIntArray(array $array) : void { $string = ''; foreach ($array AS $key => $value) { $string .= strval($value) . ':' . strval($key) . "\n"; } $string .= "\n"; fwrite($this->fp, $string); } public function readStringKeyIntArray() : array { $array = []; $line = fgets($this->fp); while ($line != "\n") { [$value, $key] = explode(':', rtrim($line), 2); $array[strval($key)] = intval($value); $line = fgets($this->fp); } return $array; } public function writeFloatArray(array $array) : void { $string = ''; foreach ($array AS $key => $value) { $string .= strval($key) . ':' . strval($value) . "\n"; } $string .= "\n"; fwrite($this->fp, $string); } public function readFloatArray() : array { $array = []; $line = fgets($this->fp); while ($line != "\n") { [$key, $value] = explode(':', rtrim($line), 2); $array[intval($key)] = floatval($value); $line = fgets($this->fp); } return $array; } public function writeInt(int $integer) : void { fwrite($this->fp, strval($integer) . "\n"); } public function readInt() : int { $line = fgets($this->fp); return intval(rtrim($line)); } } 