Skip to content

Commit

Permalink
Add auto decode body option for JSON layer
Browse files Browse the repository at this point in the history
  • Loading branch information
Thibaud Fabre committed Feb 16, 2015
1 parent 4e21682 commit 1e6b403
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/Elements/ErrorHandlingLayer.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public function __invoke(Request $request)
} catch (\Exception $ex) {
$this->logger->error($ex);

return new Response($ex->getMessage(), 500);
throw new HttpException(500, 'Unhandled exception', $ex);
}
}
}
1 change: 1 addition & 0 deletions src/Elements/HttpLayerBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

class HttpLayerBuilder implements LayerBuilder
{

/**
*
* (non-PHPdoc) @see \Aztech\LayerBuilder::buildLayer()
Expand Down
25 changes: 24 additions & 1 deletion src/Elements/JsonRenderingLayer.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,12 @@ class JsonRenderingLayer implements Layer
{
private $callable;

public function __construct(Layer $callable)
private $mergeBody;

public function __construct(Layer $callable, $mergeBody)
{
$this->callable = $callable;
$this->mergeBody = (bool) $mergeBody;
}

public function __invoke(Request $request = null)
Expand All @@ -23,6 +26,26 @@ public function __invoke(Request $request = null)
$request = Request::createFromGlobals();
}

if ($this->mergeBody) {
$request = $this->mergeRequestBody($request);
}

return $this->runController($request);
}

private function mergeRequestBody(Request $request)
{
$body = json_decode($request->getContent(), true);

if (is_array($body)) {
$request->request->add($body);
}

return $request;
}

private function runController(Request $request)
{
$callable = $this->callable;

try {
Expand Down
4 changes: 3 additions & 1 deletion src/Elements/JsonRenderingLayerBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ public function buildLayer(Layer $nextLayer, array $arguments)
$nextLayer = $this->transformationLayerBuilder->buildLayer($nextLayer, $arguments);
}

return new JsonRenderingLayer($nextLayer);
$mergeBody = isset($arguments['mergeBody']) ? ((bool) $arguments['mergeBody']) : false;

return new JsonRenderingLayer($nextLayer, $mergeBody);
}
}

0 comments on commit 1e6b403

Please sign in to comment.