Completed
Push — master ( bbc0d1...8af693 )
by Enrico
02:09
created

CreateResourceController   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 95.45%

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 6
dl 0
loc 43
ccs 21
cts 22
cp 0.9545
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
B __invoke() 0 22 5
A validate() 0 8 2
1
<?php
2
3
namespace Resourceful\Controller;
4
5
use Doctrine\Common\Cache\Cache;
6
use Silex\Application;
7
use Symfony\Component\HttpFoundation\JsonResponse;
8
use Symfony\Component\HttpFoundation\Request;
9
use Symfony\Component\HttpFoundation\Response;
10
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
11
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
12
use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;
13
14
class CreateResourceController
15
{
16
    protected $service;
17
    protected $schema;
18
19 8
    public function __construct(Cache $service, $schema)
20
    {
21 8
        $this->service = $service;
22 8
        $this->schema = $schema;
23 8
    }
24
25 4
    public function __invoke(Application $app, Request $request)
26
    {
27 4
        $requestJson = $request->getContent() ?: "{}";
28 4
        $data = json_decode($requestJson);
29 4
		if(!isset($data->id)) {
30 4
			$data->id = $app["uniqid"];
31
		}
32
		
33 4
        $this->validate($app, $data);
34
35 3
        $location = $app["url_generator"]->generate($this->schema, array("id" => $data->id));
36
		
37 3
		if ($this->service->contains($location)){
38
			throw new ConflictHttpException("Sorry $location already exists.");
39
		}
40
		
41 3
        if ($this->service->save($location, $data) === false) {
42 1
            throw new ServiceUnavailableHttpException(null, "Failed to save resource");
43
        }
44
45 2
        return JsonResponse::create($data, Response::HTTP_CREATED, array("Location" => $location));
46
    }
47
48 4
    private function validate(Application $app, $data)
49
    {
50 4
        $schema = $app["json-schema.schema-store"]->get($this->schema);
51 4
        $validation = $app["json-schema.validator"]->validate($data, $schema);
52 4
        if (!$validation->valid) {
53 1
            throw new BadRequestHttpException(json_encode($validation->errors));
54
        }
55 3
    }
56
}
57