ApiController   A
last analyzed

Complexity

Total Complexity 14

Size/Duplication

Total Lines 188
Duplicated Lines 11.17 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 14
c 1
b 0
f 0
lcom 1
cbo 7
dl 21
loc 188
rs 10

10 Methods

Rating   Name   Duplication   Size   Complexity  
A getAction() 10 10 1
A deleteAction() 11 11 1
A onError() 0 9 1
A createAction() 0 7 1
A updateAction() 0 11 1
A handleForm() 0 20 4
A onUpdateSuccess() 0 8 1
A onCreateSuccess() 0 11 1
A createRestForm() 0 9 2
A getViewHandler() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/*
4
 * This file is part of the distributed-configuration-bundle package
5
 *
6
 * Copyright (c) 2016 Guillaume Cavana
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 *
11
 * Feel free to edit as you please, and have fun.
12
 *
13
 * @author Guillaume Cavana <[email protected]>
14
 */
15
16
namespace Maikuro\DistributedConfigurationBundle\Controller;
17
18
use FOS\RestBundle\Util\Codes;
19
use FOS\RestBundle\View\View;
20
use FOS\RestBundle\View\ViewHandler;
21
use Maikuro\DistributedConfigurationBundle\Form\KeyValueType;
22
use Maikuro\DistributedConfigurationBundle\Model\KeyValue;
23
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
24
use Symfony\Component\Form\FormInterface;
25
use Symfony\Component\HttpFoundation\Request;
26
use Webmozart\KeyValueStore\Api\WriteException;
27
28
/**
29
 * Class ApiController.
30
 */
31
class ApiController extends Controller
32
{
33
    /**
34
     * Get a value from a key.
35
     *
36
     * @param Request $request
37
     * @param string  $key
38
     *
39
     * @throw Webmozart\KeyValueStore\Api\NoSuchKeyException
40
     *
41
     * @return KeyValue
42
     */
43 View Code Duplication
    public function getAction(Request $request, $key)
0 ignored issues
show
Duplication introduced by
This method 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...
44
    {
45
        $storeHandler = $this->get('maikuro_distributed_configuration.store_handler');
46
47
        $view = View::create()
48
            ->setStatusCode(Codes::HTTP_OK)
49
            ->setData($storeHandler->get($key));
50
51
        return $this->getViewHandler()->handle($view, $request);
52
    }
53
54
    /**
55
     * Create a key value.
56
     *
57
     * @param Request $request
58
     *
59
     * @return mixed|FormInterface
60
     */
61
    public function createAction(Request $request)
62
    {
63
        return $this->handleForm(
64
            $this->createRestForm(new KeyValueType(), new KeyValue()),
0 ignored issues
show
Documentation introduced by
new \Maikuro\Distributed...dle\Form\KeyValueType() is of type object<Maikuro\Distribut...ndle\Form\KeyValueType>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
65
            $request
66
        );
67
    }
68
69
    /**
70
     * Create a key.
71
     *
72
     * @param Request $request
73
     * @param string  $key
74
     *
75
     * @return Response
76
     */
77
    public function updateAction(Request $request, $key)
78
    {
79
        $storeHandler = $this->get('maikuro_distributed_configuration.store_handler');
80
        $keyValue = $storeHandler->get($key);
81
82
        return $this->handleForm($this->createRestForm(
83
            new KeyValueType(),
0 ignored issues
show
Documentation introduced by
new \Maikuro\Distributed...dle\Form\KeyValueType() is of type object<Maikuro\Distribut...ndle\Form\KeyValueType>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
84
            $keyValue,
85
            ['method' => $request->getMethod()]
86
        ), $request);
87
    }
88
89
    /**
90
     * Delete a key.
91
     *
92
     * @param Request $request
93
     * @param string  $key
94
     *
95
     * @throw Webmozart\KeyValueStore\Api\WriteException
96
     *
97
     * @return Response
98
     */
99 View Code Duplication
    public function deleteAction(Request $request, $key)
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...
Duplication introduced by
This method 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...
100
    {
101
        $view = View::create()
102
            ->setStatusCode(Codes::HTTP_NO_CONTENT)
103
        ;
104
105
        $storeHandler = $this->get('maikuro_distributed_configuration.store_handler');
106
        $storeHandler->remove($key);
107
108
        return $this->getViewHandler()->handle($view);
109
    }
110
111
    /**
112
     * handleForm.
113
     *
114
     * @param FormInterface $form
115
     * @param Request       $request
116
     *
117
     * @return Response
118
     */
119
    protected function handleForm(FormInterface $form, Request $request)
120
    {
121
        $method = $request->getMethod();
122
        $form->handleRequest($request);
123
124
        if ($form->isSubmitted() && $form->isValid()) {
125
            $entity = $form->getData();
126
127
            $storeHandler = $this->get('maikuro_distributed_configuration.store_handler');
128
            $storeHandler->flush($entity);
129
130
            if (in_array($method, ['PUT', 'PATCH'])) {
131
                return $this->getViewHandler()->handle($this->onUpdateSuccess($entity));
132
            }
133
134
            return $this->getViewHandler()->handle($this->onCreateSuccess($entity));
135
        }
136
137
        return $this->getViewHandler()->handle($this->onError($form));
138
    }
139
140
    /**
141
     * onUpdateSuccess.
142
     *
143
     * @param KeyValue $entity
144
     *
145
     * @return View
146
     */
147
    protected function onUpdateSuccess(KeyValue $entity)
0 ignored issues
show
Unused Code introduced by
The parameter $entity 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...
148
    {
149
        return  View::create()
150
                    ->setStatusCode(Codes::HTTP_NO_CONTENT)
151
                ;
152
153
        return $view;
0 ignored issues
show
Unused Code introduced by
return $view; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
154
    }
155
156
    /**
157
     * Returns a HTTP_BAD_REQUEST response when the form submission fails.
158
     *
159
     * @param KeyValue $entity
160
     *
161
     * @return View
162
     */
163
    protected function onCreateSuccess(KeyValue $entity)
164
    {
165
        $view = View::create()
166
            ->setStatusCode(Codes::HTTP_CREATED)
167
            ->setData(
168
                $entity
169
            )
170
        ;
171
172
        return $view;
173
    }
174
175
    /**
176
     * Returns a HTTP_BAD_REQUEST response when the form submission fails.
177
     *
178
     * @param FormInterface $form
179
     *
180
     * @return View
181
     */
182
    protected function onError(FormInterface $form)
183
    {
184
        $view = View::create()
185
            ->setStatusCode(Codes::HTTP_BAD_REQUEST)
186
            ->setData($form)
187
        ;
188
189
        return $view;
190
    }
191
192
    /**
193
     * createRestForm.
194
     *
195
     * @param string $type
196
     * @param mixed  $data
197
     * @param array  $options
198
     *
199
     * @return FormInterface
200
     */
201
    protected function createRestForm($type, $data = null, array $options = [])
202
    {
203
        // BC >= 2.8
204
        if ('Symfony\Component\Form\Extension\Core\Type\FormType' === $type->getParent()) {
0 ignored issues
show
Bug introduced by
The method getParent cannot be called on $type (of 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...
205
            $type = get_class($type);
206
        }
207
208
        return $this->container->get('form.factory')->createNamed(null, $type, $data, $options);
209
    }
210
211
    /**
212
     * ViewHandler.
213
     */
214
    protected function getViewHandler()
215
    {
216
        return $this->get('fos_rest.view_handler');
217
    }
218
}
219