Save::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 0
cts 3
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
namespace Magium\Configuration\View\Controllers;
4
5
use Magium\Configuration\Config\BuilderInterface;
6
use Magium\Configuration\Config\Repository\ConfigInterface;
7
use Psr\Http\Message\ServerRequestInterface;
8
use Zend\View\Model\JsonModel;
9
10
class Save implements ControllerInterface
11
{
12
13
    const STATUS_SUCCESS = 'success';
14
    const STATUS_ERROR = 'error';
15
16
    protected $builder;
17
18
    public function __construct(
19
        BuilderInterface $builder
20
    )
21
    {
22
        $this->builder = $builder;
23
    }
24
25
    public function execute(ServerRequestInterface $request)
26
    {
27
        try {
28
            $json = $this->read($request);
29
            $this->process($json);
30
            return new JsonModel([[
31
                'status'    => self::STATUS_SUCCESS,
32
                'message'   => sprintf(
33
                    '%d setting%s saved in the context: %s',
34
                        count($json['values']),
35
                        count($json['values'])>1?'s':'',
36
                        $json['context'])
37
            ]]);
38
        } catch (\Exception $e) {
39
            return new JsonModel([[
40
                'status'    => self::STATUS_ERROR,
41
                'message'   => $e->getMessage()
42
            ]]);
43
        }
44
    }
45
46
    public function process(array $json)
47
    {
48
        $context = $json['context'];
49
50
        foreach ($json['values'] as $path => $value) {
51
            $this->builder->setValue($path, $value, $context);
52
        }
53
    }
54
55
    public function read(ServerRequestInterface $request)
56
    {
57
        $header = $request->getHeader('content-type');
58
        if (is_array($header)) {
59
            $header = array_shift($header);
60
        }
61
        if (strpos($header,  'application/json') === false) {
62
            throw new InvalidRequestException('MCM save operation requires an application/json content type');
63
        }
64
        $body = $request->getBody();
65
        $body->rewind();
66
        $json  = json_decode($body->getContents(), true);
67
        if ($json === false) {
68
            throw new InvalidRequestException('Unable to read JSON string');
69
        }
70
71
        if (!isset($json['values'])) {
72
            throw new InvalidRequestException('Missing required values key');
73
        }
74
75
        if (!isset($json['context'])) {
76
            $json['context'] = ConfigInterface::CONTEXT_DEFAULT;
77
        }
78
79
        return $json;
80
    }
81
82
}
83