Completed
Push — master ( 8af693...a60473 )
by Enrico
03:36
created

CreateResourceController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
crap 1
1
<?php
2
3
namespace Resourceful\Controller;
4
5
use Silex\Application;
6
use Symfony\Component\HttpFoundation\Request;
7
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
8
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
9
use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;
10
11
class CreateResourceController extends AbstractSchemaValidatedResourceController
12
{
13
14 5
    public function __invoke(Application $app, Request $request)
15
    {
16 5
    	$store = $this->getStore($app);
17
    	
18 5
        $requestJson = $request->getContent() ?: "{}";
19 5
        $data = json_decode($requestJson);
20 5
		if(!isset($data->id)) {
21 1
			$data->id = $app["uniqid"];
22 1
			$requiredUniquenessTesting = false;
23
		} else {
24 4
			$requiredUniquenessTesting = true;
25
		}
26
		
27 5
        $this->validate($app, $data->id, $data);
28
		
29 5
        $location = $app["url_generator"]->generate($this->schema, array("id" => $data->id));
30
		
31 4
		if ($requiredUniquenessTesting && $store->contains($location)){
32 1
			throw new ConflictHttpException("Sorry $location already exists.");
33
		}
34
		
35 3
        if ($store->save($location, $data) === false) {
36 1
            throw new ServiceUnavailableHttpException(null, "Failed to save resource");
37
        }
38
39 2
        return $app->json($data, 201, array("Location" => $location));
40
    }
41
}
42