3.9. State
You can also find this code on GitHub
State.php
- <?php
- namespace DesignPatterns\Behavioral\State;
- interface State
- {
- public function proceedToNext(OrderContext $context);
- public function toString(): string;
- }
StateCreated.php
- <?php
- namespace DesignPatterns\Behavioral\State;
- class StateShipped implements State
- {
- public function proceedToNext(OrderContext $context)
- {
- $context->setState(new StateDone());
- public function toString(): string
- {
- return 'shipped';
- }
- }
StateDone.php
Tests/StateTest.php
- <?php
- namespace DesignPatterns\Behavioral\State\Tests;
- use DesignPatterns\Behavioral\State\OrderContext;
- use PHPUnit\Framework\TestCase;
- class StateTest extends TestCase
- {
- public function testIsCreatedWithStateCreated()
- {
- $orderContext = OrderContext::create();
- $this->assertEquals('created', $orderContext->toString());
- }
- public function testCanProceedToStateShipped()
- $contextOrder = OrderContext::create();
- $contextOrder->proceedToNext();
- $this->assertEquals('shipped', $contextOrder->toString());
- }
- public function testCanProceedToStateDone()
- {
- $contextOrder = OrderContext::create();
- $contextOrder->proceedToNext();
- $contextOrder->proceedToNext();
- $this->assertEquals('done', $contextOrder->toString());
- }
- public function testStateDoneIsTheLastPossibleState()
- {
- $contextOrder = OrderContext::create();
- $contextOrder->proceedToNext();
- $contextOrder->proceedToNext();
- $contextOrder->proceedToNext();
- $this->assertEquals('done', $contextOrder->toString());
- }