diff --git a/spec/Suite/Arg.spec.php b/spec/Suite/Arg.spec.php index 87254adf..8e4973b8 100644 --- a/spec/Suite/Arg.spec.php +++ b/spec/Suite/Arg.spec.php @@ -86,4 +86,43 @@ }); + describe("->__toString()", function () { + + it("describes the argument matcher", function () { + + $arg = Arg::toBe(true); + expect(strval($arg))->toBe('toBe(true)'); + + }); + + it("describes argument matchers with multiple arguments", function () { + + $arg = Arg::toBeCloseTo(1, 2); + expect(strval($arg))->toBe('toBeCloseTo(1, 2)'); + + }); + + it("describes argument matchers with no arguments", function () { + + $arg = Arg::toBeTruthy(); + expect(strval($arg))->toBe('toBeTruthy()'); + + }); + + it("describes argument matchers with array arguments", function () { + + $arg = Arg::toBe([1, 2]); + expect(strval($arg))->toBe('toBe(array[2])'); + + }); + + it("describes argument matchers with object arguments", function () { + + $arg = Arg::toBe((object) [1, 2]); + expect(strval($arg))->toBe('toBe(object[stdClass])'); + + }); + + }); + }); diff --git a/src/Arg.php b/src/Arg.php index c2159038..06b59073 100644 --- a/src/Arg.php +++ b/src/Arg.php @@ -2,6 +2,7 @@ namespace Kahlan; use Exception; +use Kahlan\Util\Text; /** * Class Arg @@ -137,4 +138,39 @@ public function match($actual) $boolean = call_user_func_array($matcher . '::match', $args); return $this->_not ? !$boolean : $boolean; } + + /** + * Returns the description of this argument matcher. + * + * @return string The description of this argument matcher. + */ + public function __toString() + { + return sprintf( + '%s(%s)', + $this->_name, + implode( + ', ', + array_map([Arg::class, '_describeArg'], $this->_args) + ) + ); + } + + /** + * Generate an inline string representation of an argument. + * + * @param mixed $arg The argument. + * @return string The dumped string. + */ + public static function _describeArg($arg) + { + if (is_array($arg)) { + return sprintf('array[%d]', count($arg)); + } + if (is_object($arg)) { + return sprintf('object[%s]', get_class($arg)); + } + + return Text::toString($arg); + } }