Skip to content

Commit

Permalink
Prevent nested arrays from causing array to string conversion when ca…
Browse files Browse the repository at this point in the history
…sting Subset as a string
  • Loading branch information
Danny-Smart committed May 2, 2023
1 parent 9ad050f commit 4769815
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 7 deletions.
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# Change Log

## 1.5.2 (2022-xx-xx)
## 1.5.2 (2023-xx-xx)

* Prevent array to string conversion when serialising a Subset matcher #1252
* Updated changelog for version 1.5.1 to include changes from #1180

## 1.3.6 (2022-09-07)
Expand Down
21 changes: 15 additions & 6 deletions library/Mockery/Matcher/Subset.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,12 +81,21 @@ public function match(&$actual)
*/
public function __toString()
{
$return = '<Subset[';
$elements = array();
foreach ($this->expected as $k=>$v) {
$elements[] = $k . '=' . (string) $v;
return '<Subset' . $this->formatArray($this->expected) . ">";
}

/**
* Recursively format an array into the string representation for this matcher
*
* @param array $array
* @return string
*/
protected function formatArray(array $array)
{
$elements = [];
foreach ($array as $k => $v) {
$elements[] = $k . '=' . (is_array($v) ? $this->formatArray($v) : (string) $v);
}
$return .= implode(', ', $elements) . ']>';
return $return;
return "[" . implode(", ", $elements) . "]";
}
}
24 changes: 24 additions & 0 deletions tests/Mockery/Matcher/SubsetTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,4 +94,28 @@ public function it_returns_false_if_actual_is_not_an_array()

$this->assertFalse($matcher->match($actual));
}

/** @test */
public function it_correctly_formats_nested_arrays_into_a_string()
{
$expected = [
"foo" => 123,
"bar" => [
"baz" => 456
]
];

$matcher = new Subset($expected);
$actual = $matcher->__toString();

$tests = [
"/foo=123/",
"/bar=\\[[^[\\]]+\\]/", // e.g. bar=[<anything other than square brackets>]
"/baz=456/"
];

foreach ($tests as $pattern) {
$this->assertMatchesRegularExpression($pattern, $actual);
}
}
}

0 comments on commit 4769815

Please sign in to comment.