Created
November 29, 2012 04:29
-
-
Save suin/4166802 to your computer and use it in GitHub Desktop.
Assertionフレームワークのプロトタイプ(案)
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 | |
class Assertion | |
{ | |
private $assertion; | |
private $valiator; | |
public function __construct($assertion, callable $validator) | |
{ | |
$this->assertion = $assertion; | |
$this->validator = $validator; | |
} | |
public function assertThat($object) | |
{ | |
$result = call_user_func($this->validator, $object); | |
if ( $result === false ) { | |
throw new Exception($this->assertion); | |
} | |
} | |
} | |
class AssertionCollection | |
{ | |
private $assertions = []; | |
public function add($assertion, callable $validator) | |
{ | |
$this->assertions[] = new Assertion($assertion, $validator); | |
} | |
public function assertThat($object) | |
{ | |
foreach ( $this->assertions as $assertion ) { | |
$assertion->assertThat($object); | |
} | |
} | |
} | |
// ✄ - - - - - - - - - - - - - - - - - - - - - - - - ここからクライアントコード | |
class ItemEntity | |
{ | |
public $price = 0; | |
} | |
class ItemAssertion | |
{ | |
public static function assertInvariantOf(ItemEntity $item) | |
{ | |
$assertions = new AssertionCollection(); | |
$assertions->add("Item price is always unsinged", function(ItemEntity $item){ | |
return ( $item->price > 0 ); | |
}); | |
$assertions->assertThat($item); | |
} | |
} | |
$item = new ItemEntity(); | |
$item->price = -1; | |
ItemAssertion::assertInvariantOf($item); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment