Last active
February 12, 2022 22:46
-
-
Save Kcko/63d285dcd045b60effa49794f26eea33 to your computer and use it in GitHub Desktop.
This file contains 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 | |
class Memento | |
{ | |
private State $state; | |
public function __construct(State $stateToSave) | |
{ | |
$this->state = $stateToSave; | |
} | |
public function getState(): State | |
{ | |
return $this->state; | |
} | |
} | |
class State | |
{ | |
const STATE_CREATED = 'created'; | |
const STATE_OPENED = 'opened'; | |
const STATE_ASSIGNED = 'assigned'; | |
const STATE_CLOSED = 'closed'; | |
private string $state; | |
/** | |
* @var string[] | |
*/ | |
private static array $validStates = [ | |
self::STATE_CREATED, | |
self::STATE_OPENED, | |
self::STATE_ASSIGNED, | |
self::STATE_CLOSED, | |
]; | |
public function __construct(string $state) | |
{ | |
self::ensureIsValidState($state); | |
$this->state = $state; | |
} | |
private static function ensureIsValidState(string $state) | |
{ | |
if (!in_array($state, self::$validStates)) { | |
throw new InvalidArgumentException('Invalid state given'); | |
} | |
} | |
public function __toString(): string | |
{ | |
return $this->state; | |
} | |
} | |
class Ticket | |
{ | |
private State $currentState; | |
public function __construct() | |
{ | |
$this->currentState = new State(State::STATE_CREATED); | |
} | |
public function open() | |
{ | |
$this->currentState = new State(State::STATE_OPENED); | |
} | |
public function assign() | |
{ | |
$this->currentState = new State(State::STATE_ASSIGNED); | |
} | |
public function close() | |
{ | |
$this->currentState = new State(State::STATE_CLOSED); | |
} | |
public function saveToMemento(): Memento | |
{ | |
return new Memento(clone $this->currentState); | |
} | |
public function restoreFromMemento(Memento $memento) | |
{ | |
$this->currentState = $memento->getState(); | |
} | |
public function getState(): State | |
{ | |
return $this->currentState; | |
} | |
} | |
// USAGE | |
$ticket = new Ticket(); | |
// open the ticket | |
$ticket->open(); | |
$openedState = $ticket->getState(); | |
$memento = $ticket->saveToMemento(); | |
$ticket->assign(); | |
$ticket->restoreFromMemento($memento); | |
$ticket->getState() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment