2017-03-27 04:51:35 +00:00
|
|
|
<?php
|
2017-05-01 19:33:37 +00:00
|
|
|
|
2017-03-27 04:51:35 +00:00
|
|
|
namespace BenBot;
|
|
|
|
|
2017-04-29 22:32:40 +00:00
|
|
|
final class PersistentArray implements \ArrayAccess, \Iterator
|
2017-04-26 03:31:22 +00:00
|
|
|
{
|
2017-03-27 04:51:35 +00:00
|
|
|
protected $data;
|
|
|
|
protected $filepath;
|
|
|
|
|
|
|
|
public function __construct($filepath)
|
|
|
|
{
|
|
|
|
$this->filepath = $filepath;
|
2017-05-01 19:33:37 +00:00
|
|
|
if (!is_file($this->filepath)) {
|
|
|
|
throw new Exception('Invalid filepath');
|
|
|
|
}
|
2017-03-27 04:51:35 +00:00
|
|
|
$rawfiledata = file_get_contents($this->filepath);
|
|
|
|
if (strlen($rawfiledata) > 3) {
|
2017-04-25 23:37:27 +00:00
|
|
|
$this->data = msgpack_unpack($rawfiledata);
|
2017-03-27 04:51:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public function __debugInfo()
|
|
|
|
{
|
|
|
|
return print_r($this->data, true);
|
|
|
|
}
|
|
|
|
|
|
|
|
public function __call($func, $argv)
|
|
|
|
{
|
|
|
|
if (!is_callable($func) || substr($func, 0, 6) !== 'array_') {
|
2017-05-01 19:33:37 +00:00
|
|
|
throw new \BadMethodCallException(__CLASS__."->$func");
|
2017-03-27 04:51:35 +00:00
|
|
|
}
|
2017-04-10 17:53:18 +00:00
|
|
|
$copy = $this->data;
|
2017-05-01 19:33:37 +00:00
|
|
|
|
2017-04-10 17:53:18 +00:00
|
|
|
return call_user_func_array($func, array_merge([$copy], $argv));
|
2017-03-27 04:51:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// array access methods
|
|
|
|
public function offsetGet($offset)
|
|
|
|
{
|
|
|
|
return $this->data[$offset] ?? null;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function offsetSet($offset, $value)
|
|
|
|
{
|
|
|
|
if (is_null($offset)) {
|
|
|
|
$this->data[] = $value;
|
|
|
|
} else {
|
|
|
|
$this->data[$offset] = $value;
|
|
|
|
}
|
|
|
|
$this->save();
|
|
|
|
}
|
|
|
|
|
|
|
|
public function offsetExists($offset)
|
|
|
|
{
|
|
|
|
return isset($this->data[$offset]);
|
|
|
|
}
|
|
|
|
|
|
|
|
public function offsetUnset($offset)
|
|
|
|
{
|
|
|
|
unset($this->data[$offset]);
|
|
|
|
$this->save();
|
|
|
|
}
|
|
|
|
|
|
|
|
// iterator methods
|
|
|
|
public function rewind()
|
|
|
|
{
|
|
|
|
return reset($this->data);
|
|
|
|
}
|
2017-05-01 19:33:37 +00:00
|
|
|
|
2017-03-27 04:51:35 +00:00
|
|
|
public function current()
|
|
|
|
{
|
|
|
|
return current($this->data);
|
|
|
|
}
|
2017-05-01 19:33:37 +00:00
|
|
|
|
2017-03-27 04:51:35 +00:00
|
|
|
public function key()
|
|
|
|
{
|
|
|
|
return key($this->data);
|
|
|
|
}
|
2017-05-01 19:33:37 +00:00
|
|
|
|
2017-03-27 04:51:35 +00:00
|
|
|
public function next()
|
|
|
|
{
|
|
|
|
return next($this->data);
|
|
|
|
}
|
2017-05-01 19:33:37 +00:00
|
|
|
|
2017-03-27 04:51:35 +00:00
|
|
|
public function valid()
|
|
|
|
{
|
|
|
|
return key($this->data) !== null;
|
|
|
|
}
|
|
|
|
|
|
|
|
private function save()
|
|
|
|
{
|
2017-04-25 23:37:27 +00:00
|
|
|
file_put_contents($this->filepath, msgpack_pack($this->data));
|
2017-03-27 04:51:35 +00:00
|
|
|
}
|
|
|
|
}
|