Completed
Push — master ( 506ee6...2ad65e )
by Oscar
02:37
created

Entity::actionItem()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 23
rs 8.7972
cc 4
eloc 13
nc 3
nop 3
1
<?php
2
3
namespace Folk\Controllers;
4
5
use Psr7Middlewares\Middleware\FormatNegotiator;
6
use Zend\Diactoros\Response\RedirectResponse;
7
use FormManager\Builder as F;
8
use Folk\SearchQuery;
9
10
class Entity
11
{
12
    protected $entity;
13
14
    /**
15
     * GET: List/search items.
16
     */
17
    public function listItems($request, $response, $app)
0 ignored issues
show
Unused Code introduced by
The parameter $response 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...
18
    {
19
        $entity = $app->getEntity($request->getAttribute('entity'));
20
        $search = new SearchQuery($request->getQueryParams());
21
22
        //Check whether the query is an id
23
        if (($id = $search->getId())) {
24
            if ($items = $entity->read($id)) {
25
                $items = [$id => $items];
26
            } else {
27
                $items = [];
28
            }
29
        } else {
30
            $items = $entity->search($search);
31
        }
32
33
        //Return as json (for ajax calls)
0 ignored issues
show
Unused Code Comprehensibility introduced by
39% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
34
        if (FormatNegotiator::getFormat($request) === 'json') {
35
            $json = [];
36
37
            foreach ($items as $id => $item) {
38
                $json[$id] = $entity->getLabel($id, $item);
39
            }
40
41
            return json_encode($json);
42
        }
43
44
        //Redirect to edit element if it's only one result
45
        if (!empty($search->getQuery()) && count($items) === 1) {
46
            return new RedirectResponse($app->getRouteUrl('edit', [
47
                'entity' => $entity->getName(),
48
                'id' => key($items),
49
            ]));
50
        }
51
52
        //Load the values
53
        $row = $entity->getScheme($app['builder']);
54
55
        //Remove non-listable elements
56
        $removedKeys = [];
57
58
        foreach ($row as $key => $value) {
59
            if ($value->get('list') === false) {
60
                $removedKeys[] = $key;
61
            }
62
        }
63
64
        foreach ($removedKeys as $key) {
65
            unset($row[$key]);
66
        }
67
68
        //populate the data
69
        $rows = [];
70
71
        foreach ($items as $id => &$item) {
72
            $rows[$id] = clone $row;
73
            $rows[$id]->val($item);
74
        }
75
76
        if ($search->getPage() && count($items) === 50) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $search->getPage() of type null|integer is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
77
            $search->setPage($search->getPage() + 1);
78
        }
79
80
        //List all results
81
        return $app['templates']->render('pages/list', [
82
            'rows' => $rows,
83
            'entity' => $entity,
84
            'search' => $search,
85
        ]);
86
    }
87
88
    /**
89
     * POST: Create a new element
90
     * GET:  Display the form.
91
     */
92
    public function createItem($request, $response, $app)
0 ignored issues
show
Unused Code introduced by
The parameter $response 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...
93
    {
94
        $entity = $app->getEntity($request->getAttribute('entity'));
95
96
        //Create form
97
        $form = F::form()
98
            ->method('post')
99
            ->enctype('multipart/form-data');
100
101
        $form->add([
102
            'entity' => F::hidden()->val($entity->getName())->class('field-data-entity'),
103
            'data' => $entity->getScheme($app['builder']),
104
        ]);
105
106
        //Save
107 View Code Duplication
        if ($request->getMethod() === 'POST') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
108
            //Load data
109
            $form->loadFromPsr7($request);
110
111
            if ($form->isValid()) {
112
                return new RedirectResponse($app->getRouteUrl('edit', [
113
                    'entity' => $entity->getName(),
114
                    'id' => $entity->create($form['data']->val()),
115
                ]));
116
            }
117
        }
118
119
        return $app['templates']->render('pages/create', [
120
            'entity' => $entity,
121
            'form' => $form,
122
        ]);
123
    }
124
125
    /**
126
     * POST: Edit an element
127
     * GET:  Display the form.
128
     */
129
    public function editItem($request, $response, $app)
0 ignored issues
show
Unused Code introduced by
The parameter $response 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...
130
    {
131
        $entity = $app->getEntity($request->getAttribute('entity'));
132
        $id = $request->getAttribute('id');
133
134
        //Create form
135
        $form = F::form()
136
            ->method('post')
137
            ->enctype('multipart/form-data');
138
139
        $form->add([
140
            'id' => F::hidden()->val($id)->class('field-data-id'),
141
            'entity' => F::hidden()->val($entity->getName())->class('field-data-entity'),
142
            'data' => $entity->getScheme($app['builder']),
143
        ]);
144
145
        //Save
146
        if ($request->getMethod() === 'POST') {
147
            //Load data
148
            $form->loadFromPsr7($request);
149
150 View Code Duplication
            if ($form->isValid()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
151
                $entity->update($id, $form['data']->val());
152
153
                return new RedirectResponse($app->getRouteUrl('edit', [
154
                    'entity' => $entity->getName(),
155
                    'id' => $id,
156
                ]));
157
            }
158
        } else {
159
            //View
160
            $data = $entity->read($id);
161
162
            $form['data']->val($data);
163
        }
164
165
        //Render template
166
        return $app['templates']->render('pages/edit', [
167
            'entity' => $entity,
168
            'form' => $form,
169
            'id' => $id,
170
        ]);
171
    }
172
173
    /**
174
     * POST: Delete the element.
175
     */
176
    public function deleteItem($request, $response, $app)
0 ignored issues
show
Unused Code introduced by
The parameter $response 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...
177
    {
178
        $entity = $app->getEntity($request->getAttribute('entity'));
179
180
        $entity->delete($request->getAttribute('id'));
181
182
        return new RedirectResponse($app->getRouteUrl('list', [
183
            'entity' => $entity->getName(),
184
        ]));
185
    }
186
}
187