From 969fb6c8062859a7947271859af682d62cb776c8 Mon Sep 17 00:00:00 2001 From: ADmad Date: Wed, 31 Jan 2018 18:19:58 +0530 Subject: [PATCH] Ensure response's status code doesn't get set to null. Closes #572. --- src/Listener/ApiListener.php | 9 ++-- tests/TestCase/Listener/ApiListenerTest.php | 53 +++++++++++++++++++++ 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/src/Listener/ApiListener.php b/src/Listener/ApiListener.php index 510c1e1be..0fd1692ee 100644 --- a/src/Listener/ApiListener.php +++ b/src/Listener/ApiListener.php @@ -124,10 +124,13 @@ public function respond(Event $event) return null; } - $response = $this->render($event->subject()) - ->withStatus($apiConfig['code']); + $response = $this->render($event->subject()); - return $response; + if (empty($apiConfig['code'])) { + return $response; + } + + return $response->withStatus($apiConfig['code']); } /** diff --git a/tests/TestCase/Listener/ApiListenerTest.php b/tests/TestCase/Listener/ApiListenerTest.php index cbcf51cdd..c3e7f93d7 100644 --- a/tests/TestCase/Listener/ApiListenerTest.php +++ b/tests/TestCase/Listener/ApiListenerTest.php @@ -167,6 +167,59 @@ public function testResponse() $listener->respond($event); } + /** + * testResponseWithStatusCodeNotSpecified + * + * @return void + * @see https://github.com/FriendsOfCake/crud/issues/572 + */ + public function testResponseWithStatusCodeNotSpecified() + { + $action = $this + ->getMockBuilder('\Crud\Action\ViewAction') + ->disableOriginalConstructor() + ->setMethods(['getConfig']) + ->getMock(); + + $response = $this + ->getMockBuilder(Response::class) + ->setMethods(['withStatus']) + ->getMock(); + + $subject = $this + ->getMockBuilder('\Crud\Event\Subject') + ->getMock(); + $subject->success = true; + + $event = new \Cake\Event\Event('Crud.afterSave', $subject); + + $listener = $this + ->getMockBuilder('\Crud\Listener\ApiListener') + ->disableOriginalConstructor() + ->setMethods(['_action', 'render']) + ->getMock(); + $listener + ->expects($this->next($listener)) + ->method('_action') + ->with() + ->will($this->returnValue($action)); + $action + ->expects($this->next($action)) + ->method('getConfig') + ->with('api.success') + ->will($this->returnValue(null)); + $listener + ->expects($this->next($listener)) + ->method('render') + ->with($subject) + ->will($this->returnValue($response)); + $response + ->expects($this->never()) + ->method('withStatus'); + + $response = $listener->respond($event); + } + /** * Test response method with exception config *