Skip to content

Commit

Permalink
put post patch
Browse files Browse the repository at this point in the history
  • Loading branch information
liuggio committed Nov 26, 2013
1 parent 1320dc1 commit 38363aa
Show file tree
Hide file tree
Showing 5 changed files with 160 additions and 61 deletions.
31 changes: 9 additions & 22 deletions app/config/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -73,40 +73,27 @@ sensio_framework_extra:
request: { converters: true }

fos_rest:
serializer:
serialize_null: true
param_fetcher_listener: true
view:
# default_engine: php
view_response_listener: force
force_redirects:
html: true
# xml: true
view_response_listener: 'force'
formats:
xml: true
json: true
xml: true
rss: false
templating_formats:
html: true
mime_types:
json: ['application/json', 'application/x-json', 'application/vnd.example-com.foo+json']
rss: 'application/rss+xml'
jpg: 'image/jpeg'
png: 'image/png'
body_listener: true
param_fetcher_listener: force
allowed_methods_listener: true
access_denied_listener:
json: true
format_listener:
rules:
- { path: '^/', priorities: ['html','json', 'xml'], fallback_format: html, prefer_extension: true }
routing_loader:
default_format: ~
- { path: ^/, priorities: [ html, json, xml ], fallback_format: ~, prefer_extension: true }
exception:
codes:
'Symfony\Component\Routing\Exception\ResourceNotFoundException': 404
'Doctrine\ORM\OptimisticLockException': HTTP_CONFLICT
messages:
'Symfony\Component\Routing\Exception\ResourceNotFoundException': true
allowed_methods_listener: true
access_denied_listener:
json: true
body_listener: true

nelmio_api_doc:
name: Page API
64 changes: 54 additions & 10 deletions src/Acme/BlogBundle/Controller/PageController.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@
use FOS\RestBundle\Util\Codes;
use FOS\RestBundle\Controller\Annotations;
use FOS\RestBundle\View\View;
use Symfony\Component\Form\FormTypeInterface;
use FOS\RestBundle\Request\ParamFetcherInterface;

use Symfony\Component\Form\FormTypeInterface;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;

use Acme\BlogBundle\Exception\InvalidFormException;
Expand All @@ -21,7 +22,41 @@
class PageController extends FOSRestController
{
/**
* Get single Page,
* List all pages.
*
* @ApiDoc(
* resource = true,
* statusCodes = {
* 200 = "Returned when successful"
* }
* )
*
* @Annotations\QueryParam(name="offset", requirements="\d+", nullable=true, description="Offset from which to start listing pages.")
* @Annotations\QueryParam(name="limit", requirements="\d+", default="5", description="How many pages to return.")
*
* @Annotations\View()
*
* @param Request $request the request object
* @param ParamFetcherInterface $paramFetcher param fetcher service
*
* @return array
*/
public function getPagesAction(Request $request, ParamFetcherInterface $paramFetcher)
{
$session = $request->getSession();

$offset = $paramFetcher->get('offset');
$start = null == $offset ? 0 : $offset + 1;
$limit = $paramFetcher->get('limit');

$pages = $session->get(self::SESSION_CONTEXT_PAGE, array());
$pages = array_slice($notes, $start, $limit, true);

return new NoteCollection($notes, $offset, $limit);
}

/**
* Get single Page.
*
* @ApiDoc(
* resource = true,
Expand Down Expand Up @@ -58,7 +93,9 @@ public function getPageAction($id)
* }
* )
*
* @Annotations\View()
* @Annotations\View(
* templateVar = "form"
* )
*
* @return FormTypeInterface
*/
Expand All @@ -67,7 +104,6 @@ public function newPageAction()
return $this->createForm(new PageType());
}


/**
* Create a Page from the submitted data.
*
Expand Down Expand Up @@ -118,6 +154,7 @@ public function postPageAction(Request $request)
* resource = true,
* input = "Acme\DemoBundle\Form\PageType",
* statusCodes = {
* 201 = "Returned when the Page is created",
* 204 = "Returned when successful",
* 400 = "Returned when the form has errors"
* }
Expand All @@ -138,18 +175,25 @@ public function postPageAction(Request $request)
public function putPageAction(Request $request, $id)
{
try {

$page = $this->container->get('acme_blog.page.handler')->put(
$this->getOr404($id),
$request->request->all()
);
if (!($page = $this->container->get('acme_blog.page.handler')->get($id))) {
$statusCode = Codes::HTTP_CREATED;
$page = $this->container->get('acme_blog.page.handler')->post(
$request->request->all()
);
} else {
$statusCode = Codes::HTTP_NO_CONTENT;
$page = $this->container->get('acme_blog.page.handler')->put(
$page,
$request->request->all()
);
}

$routeOptions = array(
'id' => $page->getId(),
'_format' => $request->get('_format')
);

return $this->routeRedirectView('api_1_get_page', $routeOptions, Codes::HTTP_NO_CONTENT);
return $this->routeRedirectView('api_1_get_page', $routeOptions, $statusCode);

} catch (InvalidFormException $exception) {

Expand Down
12 changes: 12 additions & 0 deletions src/Acme/BlogBundle/Handler/PageHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,18 @@ public function get($id)
return $this->repository->find($id);
}

/**
* Get a Page.
*
* @param mixed $id
*
* @return PageInterface
*/
public function all(int $offset = 0, int $limit = 5)
{
return $this->repository->find($id);
}

/**
* Create a new Page.
*
Expand Down
4 changes: 3 additions & 1 deletion src/Acme/BlogBundle/Resources/views/Page/newPage.html.twig
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@

{% block content %}
<h1>Page Form</h1>
<h1>Create Page Form</h1>
{% if (form is defined) %}
<form action="{{ url('api_1_post_page') }}" method="POST" {{ form_enctype(form) }}>
{{ form_widget(form) }}
<input type="submit" value="submit">
</form>
{% endif %}
{% endblock %}
110 changes: 82 additions & 28 deletions src/Acme/BlogBundle/Tests/Controller/PageControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,36 +29,68 @@ public function testJsonGetPageAction()

$decoded = json_decode($content, true);
$this->assertTrue(isset($decoded['id']));

}

public function testJsonPutPageAction()
public function testHeadRoute()
{
$fixtures = array('Acme\BlogBundle\Tests\Fixtures\Entity\LoadPageData');
$this->customSetUp($fixtures);
$pages = LoadPageData::$pages;
$page = array_pop($pages);

$this->client->request('HEAD', sprintf('/api/v1/pages/%d.json', $page->getId()), array('ACCEPT' => 'application/json'));
$response = $this->client->getResponse();
$this->assertJsonResponse($response, 200, false);
}

public function testJsonNewPageAction()
{
$this->client = static::createClient();
$this->client->request(
'PUT',
sprintf('/api/v1/pages/%d.json', $page->getId()),
'GET',
'/api/v1/pages/new.json',
array(),
array()
);

$this->assertJsonResponse($this->client->getResponse(), 200, true);
$this->assertEquals(
'{"children":{"title":[],"body":[]}}',
$this->client->getResponse()->getContent(),
$this->client->getResponse()->getContent());
}

public function testJsonPostPageAction()
{
$this->client = static::createClient();
$this->client->request(
'POST',
'/api/v1/pages.json',
array(),
array(),
array('CONTENT_TYPE' => 'application/json'),
'{"title":"abc","body":"def"}'
'{"title":"title1","body":"body1"}'
);

$page->setTitle('abc');
$page->setBody('def');
$this->assertJsonResponse($this->client->getResponse(), 201, false);
}

$this->assertJsonResponse($this->client->getResponse(), 204, false);
public function testJsonPostPageActionShouldReturn400WithBadParameters()
{
$this->client = static::createClient();
$this->client->request(
'POST',
'/api/v1/pages.json',
array(),
array(),
array('CONTENT_TYPE' => 'application/json'),
'{"titles":"title1","bodys":"body1"}'
);

$updatedPage = $this->getContainer()->get('acme_blog.page.handler')->get($page->getId());
$this->assertEquals($updatedPage, $page);
$this->assertJsonResponse($this->client->getResponse(), 400, false);
}

public function testJsonPatchPageAction()
public function testJsonPutPageActionShouldModify()
{
$fixtures = array('Acme\BlogBundle\Tests\Fixtures\Entity\LoadPageData');
$this->customSetUp($fixtures);
Expand All @@ -67,54 +99,76 @@ public function testJsonPatchPageAction()

$this->client = static::createClient();
$this->client->request(
'PATCH',
'PUT',
sprintf('/api/v1/pages/%d.json', $page->getId()),
array(),
array(),
array('CONTENT_TYPE' => 'application/json'),
'{"body":"def"}'
'{"title":"abc","body":"def"}'
);

$page->setBody('def');

$this->assertJsonResponse($this->client->getResponse(), 204, false);

$updatedPage = $this->getContainer()->get('acme_blog.page.handler')->get($page->getId());
$this->assertEquals($updatedPage, $page);
$this->assertTrue(
$this->client->getResponse()->headers->contains(
'Location',
sprintf('http://localhost/api/v1/pages/%d.json', $page->getId())
),
$this->client->getResponse()->headers
);
}


public function testJsonPostPageAction()
public function testJsonPutPageActionShouldCreate()
{
$this->client = static::createClient();
$id = 0;

$this->client->request('GET', sprintf('/api/v1/pages/%d.json', $id), array('ACCEPT' => 'application/json'));

$this->assertEquals(404, $this->client->getResponse()->getStatusCode(), $this->client->getResponse()->getContent());

$this->client->request(
'POST',
'/api/v1/pages.json',
'PUT',
sprintf('/api/v1/pages/%d.json', $id),
array(),
array(),
array('CONTENT_TYPE' => 'application/json'),
'{"title":"title1","body":"body1"}'
'{"title":"abc","body":"def"}'
);

$this->assertJsonResponse($this->client->getResponse(), 201, false);
}

public function testJsonPostPageActionShouldReturn400WithBadParameters()
public function testJsonPatchPageAction()
{
$fixtures = array('Acme\BlogBundle\Tests\Fixtures\Entity\LoadPageData');
$this->customSetUp($fixtures);
$pages = LoadPageData::$pages;
$page = array_pop($pages);

$this->client = static::createClient();
$this->client->request(
'POST',
'/api/v1/pages.json',
'PATCH',
sprintf('/api/v1/pages/%d.json', $page->getId()),
array(),
array(),
array('CONTENT_TYPE' => 'application/json'),
'{"titles":"title1","bodys":"body1"}'
'{"body":"def"}'
);

$this->assertJsonResponse($this->client->getResponse(), 400, false);
$this->assertJsonResponse($this->client->getResponse(), 204, false);
$this->assertTrue(
$this->client->getResponse()->headers->contains(
'Location',
sprintf('http://localhost/api/v1/pages/%d.json', $page->getId())
),
$this->client->getResponse()->headers
);
}





protected function assertJsonResponse($response, $statusCode = 200, $checkValidJson = true, $contentType = 'application/json')
{
$this->assertEquals(
Expand Down

0 comments on commit 38363aa

Please sign in to comment.