Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent array to string conversion in Subset matcher #1253

Merged
merged 2 commits into from
May 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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);
}
}
}