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

CreateResourceController   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 5
dl 0
loc 31
ccs 15
cts 15
cp 1
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B __invoke() 0 27 6
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