Skip to content

Commit 817f734

Browse files
committed
Adding __toString object support
1 parent 44e806e commit 817f734

File tree

2 files changed

+52
-1
lines changed

2 files changed

+52
-1
lines changed

src/FnDispatcher.php

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,17 @@ private function fn_type(array $args)
213213
private function fn_to_string(array $args)
214214
{
215215
$this->validateArity('to_string', count($args), 1);
216-
return is_string($args[0]) ? $args[0] : json_encode($args[0]);
216+
$v = $args[0];
217+
if (is_string($v)) {
218+
return $v;
219+
} elseif (is_object($v)
220+
&& !($v instanceof \JsonSerializable)
221+
&& method_exists($v, '__toString')
222+
) {
223+
return (string) $v;
224+
}
225+
226+
return json_encode($v);
217227
}
218228

219229
private function fn_to_number(array $args)

tests/FnDispatcherTest.php

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
<?php
2+
namespace JmesPath\Tests;
3+
4+
use JmesPath\FnDispatcher;
5+
6+
class FnDispatcherTest extends \PHPUnit_Framework_TestCase
7+
{
8+
public function testConvertsToString()
9+
{
10+
$fn = new FnDispatcher();
11+
$this->assertEquals('foo', $fn('to_string', ['foo']));
12+
$this->assertEquals('1', $fn('to_string', [1]));
13+
$this->assertEquals('["foo"]', $fn('to_string', [['foo']]));
14+
$std = new \stdClass();
15+
$std->foo = 'bar';
16+
$this->assertEquals('{"foo":"bar"}', $fn('to_string', [$std]));
17+
$this->assertEquals('foo', $fn('to_string', [new _TestStringClass()]));
18+
$this->assertEquals('"foo"', $fn('to_string', [new _TestJsonStringClass()]));
19+
}
20+
}
21+
22+
class _TestStringClass
23+
{
24+
public function __toString()
25+
{
26+
return 'foo';
27+
}
28+
}
29+
30+
class _TestJsonStringClass implements \JsonSerializable
31+
{
32+
public function __toString()
33+
{
34+
return 'no!';
35+
}
36+
37+
public function jsonSerialize()
38+
{
39+
return 'foo';
40+
}
41+
}

0 commit comments

Comments
 (0)