Browse Source

Handle immutable responses better.

Wait until the afterDispatch event to grab the controller response
property. Event listeners in the shutdown or afterDispatch events may
have replaced the controller's response.
mark_story 8 years ago
parent
commit
2cb101226f

+ 2 - 2
src/Controller/Controller.php

@@ -622,9 +622,9 @@ class Controller implements EventListenerInterface, EventDispatcherInterface
 
         $this->View = $this->createView();
         $contents = $this->View->render($view, $layout);
-        $this->response = $this->View->response;
+        $this->response = $this->View->response->withStringBody($contents);
 
-        return $this->response->withStringBody($contents);
+        return $this->response;
     }
 
     /**

+ 4 - 3
src/Http/ActionDispatcher.php

@@ -122,15 +122,16 @@ class ActionDispatcher
         }
 
         if (!$response && $controller->autoRender) {
-            $response = $controller->render();
-        } elseif (!$response) {
-            $response = $controller->response;
+            $controller->render();
         }
 
         $result = $controller->shutdownProcess();
         if ($result instanceof Response) {
             return $result;
         }
+        if (!$response) {
+            $response = $controller->response;
+        }
 
         return $response;
     }

+ 6 - 2
tests/TestCase/Routing/DispatcherFactoryTest.php

@@ -121,12 +121,16 @@ class DispatcherFactoryTest extends TestCase
         $response = $this->getMockBuilder('Cake\Http\Response')
             ->setMethods(['send'])
             ->getMock();
+
+        $response->expects($this->once())
+            ->method('send')
+            ->will($this->returnSelf());
+
         DispatcherFactory::add('ControllerFactory');
         DispatcherFactory::add('Append');
 
         $dispatcher = DispatcherFactory::create();
         $result = $dispatcher->dispatch($url, $response);
-        $this->assertNull($result);
-        $this->assertEquals('posts index appended content', $response->body());
+        $this->assertEquals('posts index appended content', $result->body());
     }
 }

+ 3 - 1
tests/TestCase/Routing/DispatcherTest.php

@@ -160,7 +160,9 @@ class DispatcherTest extends TestCase
                 'pass' => ['extract'],
             ]
         ]);
-        $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
+        $response = $this->getMockBuilder('Cake\Http\Response')
+            ->setMethods(['send'])
+            ->getMock();
         $response->expects($this->once())
             ->method('send');
 

+ 4 - 0
tests/test_app/TestApp/Template/Posts/header.ctp

@@ -0,0 +1,4 @@
+<?php
+$this->response = $this->response->withHeader('X-view-template', 'yes');
+?>
+header template