Completed
Push — feature/middleware ( e85030...d864e0 )
by Derek Stephen
05:41
created

UnicornController::createAction()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 26

Duplication

Lines 26
Ratio 100 %

Importance

Changes 0
Metric Value
dl 26
loc 26
rs 9.504
c 0
b 0
f 0
cc 3
nc 3
nop 2
1
<?php declare(strict_types=1);
2
3
namespace BoneMvc\Module\Unicorn\Controller;
4
5
use BoneMvc\Module\Unicorn\Collection\UnicornCollection;
6
use BoneMvc\Module\Unicorn\Entity\Unicorn;
7
use BoneMvc\Module\Unicorn\Form\UnicornForm;
8
use BoneMvc\Module\Unicorn\Service\UnicornService;
9
use Bone\Mvc\View\ViewEngine;
10
use Bone\View\Helper\AlertBox;
11
use Bone\View\Helper\Paginator;
12
use Del\Form\Field\Submit;
13
use Del\Form\Form;
14
use Del\Icon;
15
use Psr\Http\Message\ResponseInterface;
16
use Psr\Http\Message\ServerRequestInterface;
17
use Zend\Diactoros\Response\HtmlResponse;
18
19 View Code Duplication
class UnicornController
0 ignored issues
show
Duplication introduced by
This class seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
20
{
21
    /** @var int $numPerPage */
22
    private $numPerPage = 10;
23
24
    /** @var Paginator $paginator */
25
    private $paginator;
26
27
    /** @var UnicornService $service */
28
    private $service;
29
30
    /** @var ViewEngine $view */
31
    private $view;
32
33
    /**
34
     * @param UnicornService $service
35
     */
36
    public function __construct(ViewEngine $view, UnicornService $service)
37
    {
38
        $this->paginator = new Paginator();
39
        $this->service = $service;
40
        $this->view = $view;
41
    }
42
43
    /**
44
     * @param ServerRequestInterface $request
45
     * @param array $args
46
     * @return ResponseInterface $response
47
     * @throws \Exception
48
     */
49
    public function indexAction(ServerRequestInterface $request, array $args): ResponseInterface
0 ignored issues
show
Unused Code introduced by
The parameter $args is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
50
    {
51
        $db = $this->service->getRepository();
52
        $total = $db->getTotalUnicornCount();
53
54
        $this->paginator->setUrl('unicorn?page=:page');
55
        $page = (int) $request->getQueryParams()['page'] ?: 1;
56
        $this->paginator->setCurrentPage($page);
57
        $this->paginator->setPageCountByTotalRecords($total, $this->numPerPage);
58
59
        $unicorns = new UnicornCollection($db->findBy([], null, $this->numPerPage, ($page *  $this->numPerPage) - $this->numPerPage));
60
61
        $body = $this->view->render('unicorn::index', [
62
            'unicorns' => $unicorns,
63
            'paginator' => $this->paginator->render(),
64
        ]);
65
66
        return new HtmlResponse($body);
67
    }
68
69
    /**
70
     * @param ServerRequestInterface $request
71
     * @return ResponseInterface $response
72
     * @throws \Exception
73
     */
74
    public function viewAction(ServerRequestInterface $request, array $args): ResponseInterface
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
75
    {
76
        $db = $this->service->getRepository();
77
        $id = $args['id'];
78
        $unicorn = $db->find($id);
79
        $body = $this->view->render('unicorn::view', [
80
            'unicorn' => $unicorn,
81
        ]);
82
83
        return new HtmlResponse($body);
84
    }
85
86
    /**
87
     * @param ServerRequestInterface $request
88
     * @return ResponseInterface $response
89
     * @throws \Exception
90
     */
91
    public function createAction(ServerRequestInterface $request, array $args): ResponseInterface
0 ignored issues
show
Unused Code introduced by
The parameter $args is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
92
    {
93
        $msg = '';
94
        $form = new UnicornForm('createUnicorn');
95
        if ($request->getMethod() === 'POST') {
96
            $post = $request->getParsedBody();
97
            $form->populate($post);
98
            if ($form->isValid()) {
99
                $data = $form->getValues();
100
                $unicorn = $this->service->createFromArray($data);
101
                $this->service->saveUnicorn($unicorn);
102
                $msg = $this->alertBox(Icon::CHECK_CIRCLE . ' New unicorn added to database.', 'success');
103
                $form = new UnicornForm('createUnicorn');
104
            } else {
105
                $msg = $this->alertBox(Icon::REMOVE . ' There was a problem with the form.', 'danger');
106
            }
107
        }
108
109
        $form = $form->render();
110
        $body = $this->view->render('unicorn::create', [
111
            'form' => $form,
112
            'msg' => $msg,
113
        ]);
114
115
        return new HtmlResponse($body);
116
    }
117
118
    /**
119
     * @param ServerRequestInterface $request
120
     * @return ResponseInterface $response
121
     * @throws \Exception
122
     */
123
    public function editAction(ServerRequestInterface $request, array $args): ResponseInterface
124
    {
125
        $msg = '';
126
        $form = new UnicornForm('editUnicorn');
127
        $id = $args['id'];
128
        $db = $this->service->getRepository();
129
        /** @var Unicorn $unicorn */
130
        $unicorn = $db->find($id);
131
        $form->populate($unicorn->toArray());
132
133
        if ($request->getMethod() === 'POST') {
134
            $post = $request->getParsedBody();
135
            $form->populate($post);
136
            if ($form->isValid()) {
137
                $data = $form->getValues();
138
                $unicorn = $this->service->updateFromArray($unicorn, $data);
139
                $this->service->saveUnicorn($unicorn);
140
                $msg = $this->alertBox(Icon::CHECK_CIRCLE . ' Unicorn details updated.', 'success');
141
            } else {
142
                $msg = $this->alertBox(Icon::REMOVE . ' There was a problem with the form.', 'danger');
143
            }
144
        }
145
146
        $form = $form->render();
147
        $body = $this->view->render('unicorn::edit', [
148
            'form' => $form,
149
            'msg' => $msg,
150
        ]);
151
152
        return new HtmlResponse($body);
153
    }
154
155
    /**
156
     * @param ServerRequestInterface $request
157
     * @return ResponseInterface $response
158
     * @throws \Exception
159
     */
160
    public function deleteAction(ServerRequestInterface $request, array $args): ResponseInterface
161
    {
162
        $id = $args['id'];
163
        $db = $this->service->getRepository();
164
        $form = new Form('deleteUnicorn');
165
        $submit = new Submit('submit');
166
        $submit->setValue('Delete');
167
        $submit->setClass('btn btn-danger');
168
        $form->addField($submit);
169
        /** @var Unicorn $unicorn */
170
        $unicorn = $db->find($id);
171
172
        if ($request->getMethod() === 'POST') {
173
            $this->service->deleteUnicorn($unicorn);
174
            $msg = $this->alertBox(Icon::CHECK_CIRCLE . ' Unicorn deleted.', 'warning');
175
            $form = '<a href="/unicorn" class="btn btn-default">Back</a>';
176
        } else {
177
            $form = $form->render();
178
            $msg = $this->alertBox(Icon::WARNING . ' Warning, please confirm your intention to delete.', 'danger');
179
            $msg .= '<p class="lead">Are you sure you want to delete ' . $unicorn->getName() . '?</p>';
180
        }
181
182
        $body = $this->view->render('unicorn::delete', [
183
            'unicorn' => $unicorn,
184
            'form' => $form,
185
            'msg' => $msg,
186
        ]);
187
188
        return new HtmlResponse($body);
189
    }
190
191
    /**
192
     * @param string $message
193
     * @param string $class
194
     * @return string
195
     */
196
    private function alertBox(string $message, string $class): string
197
    {
198
        return AlertBox::alertBox([
199
            'message' => $message,
200
            'class' => $class,
201
        ]);
202
    }
203
}
204