-
-
Save mrsimonbennett/5e152802783c1872e5c2 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 namespace KBC\Accounts; | |
use KBC\Accounts\Events\AccountWasDeleted; | |
use KBC\Accounts\Events\AccountWasOpened; | |
use KBC\Accounts\Events\MoneyWasWithdrawn; | |
use KBC\Accounts\Events\MoneyWasDeposited; | |
use KBC\Core\BaseModel; | |
final class Account extends BaseModel | |
{ | |
private $name; | |
private $balance; | |
private $id; | |
private $closed; | |
public static function open($id, Name $name) | |
{ | |
$me = new static(); | |
$me->apply(new AccountWasOpened($id, $name, 0)); | |
} | |
public function delete() | |
{ | |
$this->apply(new AccountWasDeleted($this->id)); | |
} | |
public function deposit($amount) | |
{ | |
if(!$this->closed) | |
throw new AccountClosed(); | |
$this->apply(new MoneyWasDeposited($this->id, $amount)); | |
} | |
public function withdraw($amount) | |
{ | |
if(!$this->closed) | |
throw new AccountClosed(); | |
$this->apply(new MoneyWasWithdrawn($this->id, $amount)); | |
} | |
/* Respond to events */ | |
public function applyAccountWasOpened(AccountWasOpened $event) | |
{ | |
$state->id = $event->id; | |
$state->balance = $event->balance; | |
$state->name = $event->name; | |
} | |
public function applyMoneyWasDeposited(MoneyWasDeposited $event) | |
{ | |
$this->balance += $event->amount; | |
} | |
public function applyMoneyWasWithdrawn(MoneyWasWithdrawn $event) | |
{ | |
$state->balance -= $event->amount; | |
} | |
public function applyAccountWasDeleted(AccountWasDeleted $event) | |
{ | |
$this->closed = true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment