50 lines
959 B
PHP
50 lines
959 B
PHP
|
<?php
|
||
|
|
||
|
namespace State;
|
||
|
|
||
|
use Machine\CNC6600;
|
||
|
use RuntimeException;
|
||
|
|
||
|
class Persister
|
||
|
{
|
||
|
private const WORKING_DIR = __DIR__ . '/../../var';
|
||
|
|
||
|
|
||
|
public function persist(string $identifier, CNC6600 $CNC6600): void
|
||
|
{
|
||
|
$filename = $this->getFilename($identifier);
|
||
|
$state = serialize($CNC6600);
|
||
|
$state = gzcompress($state, 6);
|
||
|
@file_put_contents($filename, $state);
|
||
|
}
|
||
|
|
||
|
|
||
|
public function load(string $identifier): CNC6600
|
||
|
{
|
||
|
$filename = $this->getFilename($identifier);
|
||
|
$this->guardStateFileDoesNotExist($filename);
|
||
|
$state = file_get_contents($filename);
|
||
|
$state = gzuncompress($state);
|
||
|
|
||
|
return unserialize($state);
|
||
|
}
|
||
|
|
||
|
|
||
|
public function getFilename(string $identifier): string
|
||
|
{
|
||
|
$identifier = md5("machine_state_$identifier");
|
||
|
|
||
|
return self::WORKING_DIR . "/$identifier";
|
||
|
}
|
||
|
|
||
|
|
||
|
private function guardStateFileDoesNotExist(string $filename): void
|
||
|
{
|
||
|
if (!file_exists($filename)) {
|
||
|
throw new RuntimeException('State not found');
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
|