Completed
Push — master ( 68e36d...6b5a0d )
by Ryan
21:49 queued 16:05
created

SetJsonResponse::handle()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 14
c 1
b 0
f 0
nc 6
nop 2
dl 0
loc 27
rs 8.439
1
<?php namespace Anomaly\Streams\Platform\Ui\Form\Command;
2
3
use Anomaly\Streams\Platform\Support\Collection;
4
use Anomaly\Streams\Platform\Ui\Form\Component\Action\ActionResponder;
5
use Anomaly\Streams\Platform\Ui\Form\FormBuilder;
6
use Illuminate\Http\RedirectResponse;
7
use Illuminate\Routing\ResponseFactory;
8
9
/**
10
 * Class SetJsonResponse
11
 *
12
 * @link   http://pyrocms.com/
13
 * @author PyroCMS, Inc. <[email protected]>
14
 * @author Ryan Thompson <[email protected]>
15
 */
16
class SetJsonResponse
17
{
18
19
    /**
20
     * The form builder.
21
     *
22
     * @var FormBuilder
23
     */
24
    protected $builder;
25
26
    /**
27
     * Create a new SetJsonResponse instance.
28
     *
29
     * @param FormBuilder $builder
30
     */
31
    public function __construct(FormBuilder $builder)
32
    {
33
        $this->builder = $builder;
34
    }
35
36
    /**
37
     * Handle the command.
38
     *
39
     * @param ResponseFactory $response
40
     * @param ActionResponder $responder
41
     */
42
    public function handle(ResponseFactory $response, ActionResponder $responder)
43
    {
44
        $data = new Collection();
45
        $original = $this->builder->getFormResponse();
46
47
        if ($action = $this->builder->getActiveFormAction()) {
48
49
            $responder->setFormResponse($this->builder, $action);
50
51
            if ($original instanceof RedirectResponse) {
52
                $data->put('redirect', $original->getTargetUrl());
53
            }
54
        }
55
56
        $data->put('success', !$this->builder->hasFormErrors());
57
        $data->put('errors', $this->builder->getFormErrors()->toArray());
58
        
59
        if ($original && !$original instanceof RedirectResponse) {
60
            foreach ($original->getData() as $key => $val) {
61
                $data->put($key, $val);
62
            }
63
        }
64
65
        $this->builder->setFormResponse(
66
            $response = $response->json($data)
67
        );
68
    }
69
}
70