diff --git a/src/View.php b/src/View.php index 511f406a..564f7af8 100644 --- a/src/View.php +++ b/src/View.php @@ -184,6 +184,10 @@ public function render(Model $model) $event->setRenderer($renderer); $results = $events->trigger(ViewEvent::EVENT_RENDERER_POST, $event); + // If EVENT_RENDERER or EVENT_RENDERER_POST changed the model, make sure + // we use this new model instead of the current $model + $model = $event->getModel(); + // If we have children, render them first, but only if: // a) the renderer does not implement TreeRendererInterface, or // b) it does, but canRenderTrees() returns false diff --git a/test/ViewTest.php b/test/ViewTest.php index a2c9299a..5ddf398f 100644 --- a/test/ViewTest.php +++ b/test/ViewTest.php @@ -22,6 +22,7 @@ use Zend\View\Resolver; use Zend\View\Variables as ViewVariables; use Zend\View\View; +use Zend\View\ViewEvent; class ViewTest extends TestCase { @@ -306,4 +307,31 @@ public function testCanTriggerPostRendererEvent() $this->view->render($this->model); $this->assertTrue($test->flag); } + + /** + * Test the view model can be swapped out + * + * @see https://github.com/zendframework/zf2/pull/4164 + */ + public function testModelFromEventIsUsedByRenderer() + { + $renderer = $this->getMock('Zend\View\Renderer\PhpRenderer', array('render')); + + $model1 = new ViewModel; + $model2 = new ViewModel; + + $this->view->addRenderingStrategy(function ($e) use ($renderer) { + return $renderer; + }); + + $this->view->getEventManager(ViewEvent::EVENT_RENDERER_POST, function($e) use ($model2) { + $e->setModel($model2); + }); + + $renderer->expects($this->once()) + ->method('render') + ->with($model2); + + $this->view->render($model1); + } }