Completed
Pull Request — master (#331)
by Elan
02:10 queued 57s
created

ImportController   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 2
dl 0
loc 49
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A import() 0 19 3
A runImport() 0 11 3
1
<?php
2
3
namespace XHGui\Controller;
4
5
use Exception;
6
use InvalidArgumentException;
7
use Slim\Http\Request;
8
use Slim\Slim;
9
use XHGui\Saver\SaverInterface;
10
use XHGui\AbstractController;
11
12
class ImportController extends AbstractController
13
{
14
    /**
15
     * @var SaverInterface
16
     */
17
    private $saver;
18
19
    /** @var string */
20
    private $token;
21
22
    public function __construct(Slim $app, SaverInterface $saver, $token)
23
    {
24
        parent::__construct($app);
25
        $this->saver = $saver;
26
        $this->token = $token;
27
    }
28
29
    public function import()
30
    {
31
        $request = $this->app->request();
32
        $response = $this->app->response();
33
34
        try {
35
            $this->runImport($request);
36
            $result = ['ok' => true, 'size' => $request->getContentLength()];
37
        } catch (InvalidArgumentException $e) {
38
            $result = ['error' => true, 'message' => $e->getMessage()];
39
            $response->setStatus(401);
40
        } catch (Exception $e) {
41
            $result = ['error' => true, 'message' => $e->getMessage()];
42
            $response->setStatus(500);
43
        }
44
45
        $response['Content-Type'] = 'application/json';
46
        $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...
47
    }
48
49
    private function runImport(Request $request)
50
    {
51
        if ($this->token) {
52
            if ($this->token !== $request->get('token')) {
53
                throw new InvalidArgumentException('Token validation failed');
54
            }
55
        }
56
57
        $data = json_decode($request->getBody(), true);
58
        $this->saver->save($data);
59
    }
60
}
61