3.9. State

    You can also find this code on GitHub

    State.php

    1. <?php
    2.  
    3. namespace DesignPatterns\Behavioral\State;
    4.  
    5. interface State
    6. {
    7. public function proceedToNext(OrderContext $context);
    8.  
    9. public function toString(): string;
    10. }

    StateCreated.php

    1. <?php
    2.  
    3. namespace DesignPatterns\Behavioral\State;
    4.  
    5. class StateShipped implements State
    6. {
    7. public function proceedToNext(OrderContext $context)
    8. {
    9. $context->setState(new StateDone());
    10.  
    11. public function toString(): string
    12. {
    13. return 'shipped';
    14. }
    15. }

    StateDone.php

    Tests/StateTest.php

    1. <?php
    2.  
    3. namespace DesignPatterns\Behavioral\State\Tests;
    4.  
    5. use DesignPatterns\Behavioral\State\OrderContext;
    6. use PHPUnit\Framework\TestCase;
    7.  
    8. class StateTest extends TestCase
    9. {
    10. public function testIsCreatedWithStateCreated()
    11. {
    12. $orderContext = OrderContext::create();
    13.  
    14. $this->assertEquals('created', $orderContext->toString());
    15. }
    16.  
    17. public function testCanProceedToStateShipped()
    18. $contextOrder = OrderContext::create();
    19. $contextOrder->proceedToNext();
    20.  
    21. $this->assertEquals('shipped', $contextOrder->toString());
    22. }
    23.  
    24. public function testCanProceedToStateDone()
    25. {
    26. $contextOrder = OrderContext::create();
    27. $contextOrder->proceedToNext();
    28. $contextOrder->proceedToNext();
    29.  
    30. $this->assertEquals('done', $contextOrder->toString());
    31. }
    32.  
    33. public function testStateDoneIsTheLastPossibleState()
    34. {
    35. $contextOrder = OrderContext::create();
    36. $contextOrder->proceedToNext();
    37. $contextOrder->proceedToNext();
    38. $contextOrder->proceedToNext();
    39.  
    40. $this->assertEquals('done', $contextOrder->toString());
    41. }