Last active
November 16, 2016 07:31
-
-
Save RickySu/b3d64dec9959c51d0e9f5a330fd7c9c0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
```PHP | |
<?php | |
class Controller | |
{ | |
/** | |
* @DI\Inject() | |
*/ | |
protected $validator; | |
/** | |
* @Route("/") | |
* @Method({"POST"}) | |
*/ | |
public function createAction(Request $request) | |
{ | |
$userToken = $request->attributes->get('_authorizedToken'); | |
if ($userToken == null || $userToken['type'] != 'user' ) { | |
return $this->createJsonResponse('Unauthorized Token', Response::HTTP_UNAUTHORIZED); | |
} | |
$userId = $userToken['aud']; | |
$parameters = json_decode($request->getContent(), true); | |
if(count($err = $this->validator->validate($parameters)) > 0){ | |
return $this->createJsonResponse('Bad Parameters', Response::HTTP_BAD_REQUEST); | |
} | |
$obj = new SomeModel(); | |
$obj->fromArray($parameters); | |
$obj->save(); | |
return $this->createJsonResponse(); | |
} | |
} | |
//tests | |
class ControllerTests extends WebTestCase | |
{ | |
public function test_createAction_ok() | |
{ | |
// arrange | |
$parameters = array(); | |
$validator = $this-getMockBuilder(Validator::class) | |
->setMethods('validate') | |
->disableOriginalConstructor() | |
->getMock(); | |
$validator | |
->expects($this->once) | |
->method('validate') | |
->willReturn(null); | |
$this->client->getContainer()->set('validator', $validator); | |
// act | |
$this->client->request( | |
'POST', | |
'/' | |
array(), | |
array(), | |
array(), | |
json_encode($parameters) | |
); | |
$response = $this->client->getResponse(); | |
//assert | |
$this->assertTrue($response->isOk()); | |
} | |
} | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment