From 9ea9352bab12f5aa3a13d831c843a09684c70aa0 Mon Sep 17 00:00:00 2001 From: Samuel Nogueira Date: Fri, 20 Jul 2018 19:10:58 +0100 Subject: [PATCH] Cloning ViewModel now also clones it's variables if they are an object Fixes #157 --- src/Model/ViewModel.php | 13 +++++++++++++ test/Model/ViewModelTest.php | 21 +++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/src/Model/ViewModel.php b/src/Model/ViewModel.php index 204ea2a9..7896dd2d 100644 --- a/src/Model/ViewModel.php +++ b/src/Model/ViewModel.php @@ -140,6 +140,19 @@ public function __unset($name) unset($this->variables[$name]); } + /** + * Called after this view model is cloned. + * Clones variables property so variables changes done in the new instance don't change the old one. + * + * @return void + */ + public function __clone() + { + if (is_object($this->variables)) { + $this->variables = clone $this->variables; + } + } + /** * Set a single option * diff --git a/test/Model/ViewModelTest.php b/test/Model/ViewModelTest.php index a5ce3fce..318825f8 100644 --- a/test/Model/ViewModelTest.php +++ b/test/Model/ViewModelTest.php @@ -340,4 +340,25 @@ public function testGetChildrenByCaptureToNonRecursive() $this->assertEmpty($model->getChildrenByCaptureTo('bar', false)); } + + public function testCloneCopiesVariables() + { + $model1 = new ViewModel(); + $model1->setVariables(['a' => 'foo']); + $model2 = clone $model1; + $model2->setVariables(['a' => 'bar']); + + $this->assertEquals('foo', $model1->getVariable('a')); + $this->assertEquals('bar', $model2->getVariable('a')); + } + + public function testCloneWithArray() + { + $model1 = new ViewModel(['a' => 'foo']); + $model2 = clone $model1; + $model2->setVariables(['a' => 'bar']); + + $this->assertEquals('foo', $model1->getVariable('a')); + $this->assertEquals('bar', $model2->getVariable('a')); + } }