Skip to content

Instantly share code, notes, and snippets.

@suin
Created November 29, 2012 04:29
Show Gist options
  • Save suin/4166802 to your computer and use it in GitHub Desktop.
Save suin/4166802 to your computer and use it in GitHub Desktop.
Assertionフレームワークのプロトタイプ(案)
<?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