Completed
Pull Request — master (#289)
by Elan
08:02 queued 06:48
created

Xhgui_Controller_Import::runImport()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
cc 3
nc 3
nop 1
1
<?php
2
3
use Slim\Http\Request;
4
use Slim\Slim;
5
6
class Xhgui_Controller_Import extends Xhgui_Controller
7
{
8
    /**
9
     * @var Xhgui_Saver_Interface
10
     */
11
    private $saver;
12
13
    /** @var string */
14
    private $token;
15
16
    public function __construct(Slim $app, Xhgui_Saver_Interface $saver, $token)
17
    {
18
        parent::__construct($app);
19
        $this->saver = $saver;
20
        $this->token = $token;
21
    }
22
23
    public function import()
24
    {
25
        $request = $this->app->request();
26
        $response = $this->app->response();
27
28
        try {
29
            $this->runImport($request);
30
            $result = ['ok' => true];
31
        } catch (Exception $e) {
32
            $result = ['error' => true, 'message' => $e->getMessage()];
33
        }
34
35
        $response['Content-Type'] = 'application/json';
36
        $response->body(json_encode($result));
0 ignored issues
show
Bug introduced by
The method body cannot be called on $response (of type array<string,string,{"Content-Type":"string"}>).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
37
    }
38
39
    private function runImport(Request $request)
40
    {
41
        if ($this->token) {
42
            if ($this->token !== $request->get('token')) {
43
                throw new RuntimeException('Token validation failed');
44
            }
45
        }
46
47
        $data = json_decode($request->getBody(), true);
48
        $this->saver->save($data);
49
    }
50
}
51