Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
namespace AnrDaemon;
class Xxx
implements \JsonSerializable, \Serializable
{
public static function createFromState(array $state)
{
$self = new static();
$self->params = array_replace($self->params, array_intersect_key($state, $self->params));
$self->repair();
return $self;
}
public static function createFromJson(/*TODO:PHP7 string */$json)
{
$state = json_decode($json, true);
if(json_last_error() !== JSON_ERROR_NONE)
throw new Exceptions\InvalidObjectStateException(json_last_error_msg(), json_last_error());
if(!is_array($state))
throw new Exceptions\InvalidObjectStateException("Saved state must be an array or an object");
return static::createFromState($state);
}
public function saveState()
{
return $this->params;
}
// Magic
private function __construct()
{
// Stuff that shouldn't happen out of context
}
public static function __set_state(array $state)
{
return static::createFromState($state['params']);
}
// JsonSerializable
public function jsonSerialize()
{
return (object)$this->params;
}
// Serializable
public function serialize()
{
return serialize($this->params);
}
public function unserialize($state)
{
$self = static::createFromState(unserialize($state));
$this->params = $self->params;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.