Skip to content

Commit 135ec37

Browse files
committed
Allow returned response objects to work from controllers.
1 parent 220cc1a commit 135ec37

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

system/CodeIgniter.php

+15
Original file line numberDiff line numberDiff line change
@@ -810,12 +810,27 @@ protected function display404errors(PageNotFoundException $e)
810810
/**
811811
* Gathers the script output from the buffer, replaces some execution
812812
* time tag in the output and displays the debug toolbar, if required.
813+
*
814+
* @param null $cacheConfig
815+
* @param null $returned
813816
*/
814817
protected function gatherOutput($cacheConfig = null, $returned = null)
815818
{
816819
$this->output = ob_get_contents();
817820
ob_end_clean();
818821

822+
// If the controller returned a response object,
823+
// we need to grab the body from it so it can
824+
// be added to anything else that might have been
825+
// echoed already.
826+
// We also need to save the instance locally
827+
// so that any status code changes, etc, take place.
828+
if ($returned instanceof Response)
829+
{
830+
$this->response = $returned;
831+
$returned = $returned->getBody();
832+
}
833+
819834
if (is_string($returned))
820835
{
821836
$this->output .= $returned;

tests/system/CodeIgniterTest.php

+49
Original file line numberDiff line numberDiff line change
@@ -162,4 +162,53 @@ public function testRun404OverrideByClosure()
162162

163163
//--------------------------------------------------------------------
164164

165+
public function testControllersCanReturnString()
166+
{
167+
$_SERVER['argv'] = [
168+
'index.php',
169+
'pages/about',
170+
];
171+
$_SERVER['argc'] = 2;
172+
173+
// Inject mock router.
174+
$routes = Services::routes();
175+
$routes->add('pages/(:segment)', function($segment)
176+
{
177+
return 'You want to see "'.esc($segment).'" page.';
178+
});
179+
$router = Services::router($routes);
180+
Services::injectMock('router', $router);
181+
182+
ob_start();
183+
$this->codeigniter->run();
184+
$output = ob_get_clean();
185+
186+
$this->assertContains('You want to see "about" page.', $output);
187+
}
188+
189+
public function testControllersCanReturnResponseObject()
190+
{
191+
$_SERVER['argv'] = [
192+
'index.php',
193+
'pages/about',
194+
];
195+
$_SERVER['argc'] = 2;
196+
197+
// Inject mock router.
198+
$routes = Services::routes();
199+
$routes->add('pages/(:segment)', function($segment)
200+
{
201+
$response = Services::response();
202+
$string = "You want to see 'about' page.";
203+
return $response->setBody($string);
204+
});
205+
$router = Services::router($routes);
206+
Services::injectMock('router', $router);
207+
208+
ob_start();
209+
$this->codeigniter->run();
210+
$output = ob_get_clean();
211+
212+
$this->assertContains("You want to see 'about' page.", $output);
213+
}
165214
}

0 commit comments

Comments
 (0)