Last active
February 1, 2019 00:23
-
-
Save AnrDaemon/fa8c1e76b2a8e06fbcc587bc06b16114 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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