diff --git a/CHANGELOG.md b/CHANGELOG.md index 4fc3c02..8fbd587 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## Unreleased +- Copy `$response` in `ProfilerItem` not to store a reference to the original object ## 1.0.0 - 2021-05-12 - Initial implementation diff --git a/src/ValueObject/ProfilerItem.php b/src/ValueObject/ProfilerItem.php index 1eb94c5..e3714d4 100644 --- a/src/ValueObject/ProfilerItem.php +++ b/src/ValueObject/ProfilerItem.php @@ -49,8 +49,8 @@ public function __construct( $this->itemType = $this->matchItemType($itemType); $this->type = $type; - $this->response = $response; - $this->error = $error; + $this->setResponse($response); + $this->setError($error); $this->cacheKey = $cacheKey; $this->isLoadedFromCache = $isLoadedFromCache; $this->isStoredInCache = $isStoredInCache; @@ -112,7 +112,18 @@ public function getResponse() /** @param mixed|FormattedValue $response */ public function setResponse($response): void { - $this->response = $response; + $this->response = $this->copy($response); + } + + /** + * @param mixed $value + * @return mixed + */ + private function copy($value) + { + return is_object($value) + ? clone $value + : $value; } /** @return \Throwable|FormattedValue|null */ diff --git a/tests/ValueObject/ProfilerItemTest.php b/tests/ValueObject/ProfilerItemTest.php new file mode 100644 index 0000000..245659a --- /dev/null +++ b/tests/ValueObject/ProfilerItemTest.php @@ -0,0 +1,39 @@ +value = 'foo'; + + $profilerItem = new ProfilerItem('id', null, 'test', null, $response); + + $response->value = 'fooBar'; + + $this->assertSame('foo', $profilerItem->getResponse()->value); + } + + /** + * @test + */ + public function shouldProfileResponseAsItIsInThatMomentViaSetter(): void + { + $response = new \stdClass(); + $response->value = 'foo'; + + $profilerItem = new ProfilerItem('id', null, 'test'); + $profilerItem->setResponse($response); + + $response->value = 'fooBar'; + + $this->assertSame('foo', $profilerItem->getResponse()->value); + } +}