Skip to content

Commit

Permalink
Fix Subset string casting issue with nested arrays (#1253)
Browse files Browse the repository at this point in the history
Signed-off-by: Nathanael Esayeas <nathanael.esayeas@protonmail.com>
  • Loading branch information
ghostwriter committed May 3, 2023
2 parents aed9f5e + 05b11ed commit bac1765
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 6 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
* [#1245 Deprecate hamcrest/hamcrest-php package](https://github.com/mockery/mockery/pull/1245)
* [#1246 Add BUG_REPORT.yml Issue template](https://github.com/mockery/mockery/pull/1246)
* [#1250 Deprecate PHP <=8.0](https://github.com/mockery/mockery/issues/1250)
* [#1253 Prevent array to string conversion when serialising a Subset matcher](https://github.com/mockery/mockery/issues/1253)

## 1.3.6 (2022-09-07)
* PHP 8.2 | Fix "Use of "parent" in callables is deprecated" notice #1169
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 bac1765

Please sign in to comment.