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

CreateResourceController::__invoke()   B

Complexity

Conditions 5
Paths 12

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 5.0144

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 11
cts 12
cp 0.9167
rs 8.6737
c 0
b 0
f 0
cc 5
eloc 12
nc 12
nop 2
crap 5.0144
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