Skip to content

Commit

Permalink
Implemented __toString() for argument matchers. (#260)
Browse files Browse the repository at this point in the history
  • Loading branch information
ezzatron authored and jails committed Jul 7, 2017
1 parent 40aefee commit 55d42cd
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
39 changes: 39 additions & 0 deletions spec/Suite/Arg.spec.php
Expand Up @@ -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])');

});

});

});
36 changes: 36 additions & 0 deletions src/Arg.php
Expand Up @@ -2,6 +2,7 @@
namespace Kahlan;

use Exception;
use Kahlan\Util\Text;

/**
* Class Arg
Expand Down Expand Up @@ -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);
}
}

0 comments on commit 55d42cd

Please sign in to comment.