Completed
Push — wip-platform ( 03cba6...2999ab )
by
unknown
05:53 queued 02:49
created

CRUDController::createAction()   D

Complexity

Conditions 15
Paths 109

Size

Total Lines 106
Code Lines 63

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 106
rs 4.7613
c 0
b 0
f 0
cc 15
eloc 63
nc 109
nop 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 *
5
 * Copyright (C) 2015-2017 Libre Informatique
6
 *
7
 * This file is licenced under the GNU LGPL v3.
8
 * For the full copyright and license information, please view the LICENSE.md
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Blast\Bundle\CoreBundle\Controller;
13
14
use Sonata\AdminBundle\Controller\CRUDController as SonataController;
15
use Symfony\Component\HttpFoundation\JsonResponse;
16
use Symfony\Component\HttpFoundation\Request;
17
18
/**
19
 * Class CRUDController.
20
 *
21
 * @author  Thomas Rabaix <[email protected]>
22
 */
23
class CRUDController extends SonataController
24
{
25
    /**
26
     * The related Admin class.
27
     *
28
     * @var AdminInterface
29
     */
30
    protected $admin;
31
32
    /**
33
     * Duplicate action.
34
     *
35
     * @return response
36
     */
37
    public function duplicateAction()
38
    {
39
        $id = $this->getRequest()->get($this->admin->getIdParameter());
40
        $object = clone $this->admin->getObject($id);
41
42
        $preResponse = $this->preDuplicate($object);
43
        if ($preResponse !== null) {
44
            return $preResponse;
45
        }
46
47
        return $this->createAction($object);
48
    }
49
50
    /**
51
     * Create action.
52
     *
53
     * @param object $object
54
     *
55
     * @return Response
56
     *
57
     * @throws AccessDeniedException If access is not granted
58
     */
59
    public function createAction($object = null)
60
    {
61
        $request = $this->getRequest();
62
        // the key used to lookup the template
63
        $templateKey = 'edit';
64
65
        $this->admin->checkAccess('create');
66
67
        $class = new \ReflectionClass($this->admin->hasActiveSubClass() ? $this->admin->getActiveSubClass() : $this->admin->getClass());
68
69
        if ($class->isAbstract()) {
70
            return $this->render(
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->render('So...ate'), null, $request); (Symfony\Component\HttpFoundation\Response) is incompatible with the return type documented by Blast\Bundle\CoreBundle\...ontroller::createAction of type Blast\Bundle\CoreBundle\Controller\Response.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
71
                'SonataAdminBundle:CRUD:select_subclass.html.twig',
72
                array(
73
                    'base_template' => $this->getBaseTemplate(),
74
                    'admin'         => $this->admin,
75
                    'action'        => 'create',
76
                ),
77
                null,
78
                $request
0 ignored issues
show
Unused Code introduced by
The call to CRUDController::render() has too many arguments starting with $request.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
79
            );
80
        }
81
82
        $object = $object ? $object : $this->admin->getNewInstance();
83
84
        $preResponse = $this->preCreate($request, $object);
85
        if ($preResponse !== null) {
86
            return $preResponse;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $preResponse; (Blast\Bundle\CoreBundle\Controller\Response) is incompatible with the return type of the parent method Sonata\AdminBundle\Contr...ontroller::createAction of type Symfony\Component\HttpFoundation\Response.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
87
        }
88
89
        $this->admin->setSubject($object);
90
91
        /** @var $form \Symfony\Component\Form\Form */
92
        $form = $this->admin->getForm();
93
        $form->setData($object);
94
        $form->handleRequest($request);
95
96
        if ($form->isSubmitted()) {
97
            //TODO: remove this check for 4.0
98
            if (method_exists($this->admin, 'preValidate')) {
99
                $this->admin->preValidate($object);
100
            }
101
            $isFormValid = $form->isValid();
102
103
            // persist if the form was valid and if in preview mode the preview was approved
104
            if ($isFormValid && (!$this->isInPreviewMode($request) || $this->isPreviewApproved($request))) {
0 ignored issues
show
Unused Code introduced by
The call to CRUDController::isInPreviewMode() has too many arguments starting with $request.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
Unused Code introduced by
The call to CRUDController::isPreviewApproved() has too many arguments starting with $request.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
105
                $this->admin->checkAccess('create', $object);
106
107
                try {
108
                    $object = $this->admin->create($object);
109
110
                    if ($this->isXmlHttpRequest()) {
111
                        return $this->renderJson(array(
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->renderJson...bject)), 200, array()); (Symfony\Component\HttpFoundation\JsonResponse) is incompatible with the return type documented by Blast\Bundle\CoreBundle\...ontroller::createAction of type Blast\Bundle\CoreBundle\Controller\Response.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
112
                            'result'   => 'ok',
113
                            'objectId' => $this->admin->getNormalizedIdentifier($object),
114
                        ), 200, array());
115
                    }
116
117
                    $this->addFlash(
118
                        'sonata_flash_success',
119
                        $this->admin->trans(
120
                            'flash_create_success',
121
                            array('%name%' => $this->escapeHtml($this->admin->toString($object))),
122
                            'SonataAdminBundle'
123
                        )
124
                    );
125
126
                    // redirect to edit mode
127
                    return $this->redirectTo($object);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->redirectTo($object); (Symfony\Component\HttpFoundation\RedirectResponse) is incompatible with the return type documented by Blast\Bundle\CoreBundle\...ontroller::createAction of type Blast\Bundle\CoreBundle\Controller\Response.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
128
                } catch (ModelManagerException $e) {
0 ignored issues
show
Bug introduced by
The class Blast\Bundle\CoreBundle\...r\ModelManagerException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
129
                    $this->handleModelManagerException($e);
130
131
                    $isFormValid = false;
132
                }
133
            }
134
135
            // show an error message if the form failed validation
136
            if (!$isFormValid) {
137
                if (!$this->isXmlHttpRequest()) {
138
                    $this->addFlash(
139
                        'sonata_flash_error',
140
                        $this->admin->trans(
141
                            'flash_create_error',
142
                            array('%name%' => $this->escapeHtml($this->admin->toString($object))),
143
                            'SonataAdminBundle'
144
                        )
145
                    );
146
                }
147
            } elseif ($this->isPreviewRequested()) {
148
                // pick the preview template if the form was valid and preview was requested
149
                $templateKey = 'preview';
150
                $this->admin->getShow();
151
            }
152
        }
153
154
        $view = $form->createView();
155
156
        // set the theme for the current Admin Form
157
        $this->defineFormTheme($view, $this->admin->getFormTheme());
158
159
        return $this->render($this->admin->getTemplate($templateKey), array(
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->render($th...ct' => $object), null); (Symfony\Component\HttpFoundation\Response) is incompatible with the return type documented by Blast\Bundle\CoreBundle\...ontroller::createAction of type Blast\Bundle\CoreBundle\Controller\Response.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
160
            'action' => 'create',
161
            'form'   => $view,
162
            'object' => $object,
163
        ), null);
164
    }
165
166
    /**
167
     * Generate Entity Code action.
168
     *
169
     * @param int|string|null $id
170
     *
171
     * @return JsonResponse
172
     */
173
    public function generateEntityCodeAction($id = null)
0 ignored issues
show
Unused Code introduced by
The parameter $id 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...
174
    {
175
        $request = $this->getRequest();
176
177
        $id = $request->get($this->admin->getIdParameter());
178
        if ($id) {
179
            $subject = $this->admin->getObject($id);
180
            if (!$subject) {
181
                $error = sprintf('unable to find the object with id : %s', $id);
182
183
                return new JsonResponse(['error' => $error]);
184
            }
185
            try {
186
                $this->admin->checkAccess('edit', $subject); // TODO: is it necessary ? (we are not editing the entity)
187
            } catch (Exception $exc) {
0 ignored issues
show
Bug introduced by
The class Blast\Bundle\CoreBundle\Controller\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
188
                $error = $exc->getMessage();
189
190
                return new JsonResponse(['error' => $error]);
191
            }
192
        } else {
193
            $subject = $this->admin->getNewInstance();
194
        }
195
196
        $this->admin->setSubject($subject);
197
198
        $form = $this->admin->getForm();
199
        $form->setData($subject);
200
        $form->submit($request->request->get($form->getName()));
201
        $entity = $form->getData();
202
203
        $field = $request->query->get('field', 'code');
204
        $registry = $this->get('blast_core.code_generators');
205
        $generator = $registry::getCodeGenerator(get_class($entity), $field);
206
        try {
207
            $code = $generator::generate($entity);
208
209
            return new JsonResponse(['code' => $code]);
210
        } catch (\Exception $exc) {
211
            $error = $this->get('translator')->trans($exc->getMessage());
212
213
            return new JsonResponse(['error' => $error, 'generator' => get_class($generator)]);
214
        }
215
    }
216
217
    /**
218
     * This method can be overloaded in your custom CRUD controller.
219
     * It's called from createAction.
220
     *
221
     * @param Request $request
222
     * @param mixed   $object
223
     *
224
     * @return Response|null
225
     */
226
    protected function preCreate(Request $request, $object)
227
    {
228
    }
229
230
    /**
231
     * This method can be overloaded in your custom CRUD controller.
232
     * It's called from editAction.
233
     *
234
     * @param Request $request
235
     * @param mixed   $object
236
     *
237
     * @return Response|null
238
     */
239
    protected function preEdit(Request $request, $object)
240
    {
241
    }
242
243
    /**
244
     * This method can be overloaded in your custom CRUD controller.
245
     * It's called from deleteAction.
246
     *
247
     * @param Request $request
248
     * @param mixed   $object
249
     *
250
     * @return Response|null
251
     */
252
    protected function preDelete(Request $request, $object)
253
    {
254
    }
255
256
    /**
257
     * This method can be overloaded in your custom CRUD controller.
258
     * It's called from showAction.
259
     *
260
     * @param Request $request
261
     * @param mixed   $object
262
     *
263
     * @return Response|null
264
     */
265
    protected function preShow(Request $request, $object)
266
    {
267
    }
268
269
    /**
270
     * This method can be overloaded in your custom CRUD controller.
271
     * It's called from listAction.
272
     *
273
     * @param Request $request
274
     *
275
     * @return Response|null
276
     */
277
    protected function preList(Request $request)
278
    {
279
    }
280
281
    /**
282
     * This method can be overloaded in your custom CRUD controller.
283
     * It's called from duplicateAction.
284
     *
285
     * @param mixed $object
286
     *
287
     * @return Response|null
288
     */
289
    protected function preDuplicate($object)
0 ignored issues
show
Unused Code introduced by
The parameter $object 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...
290
    {
291
    }
292
293
    protected function defineFormTheme($formView, $formTheme)
294
    {
295
        $twig = $this->get('twig');
296
297
        $renderer = ($twig->hasExtension('Symfony\Bridge\Twig\Form\TwigRenderer')) ?
298
                  $twig->getRuntime('Symfony\Bridge\Twig\Form\TwigRenderer') :
299
                  $twig->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer;
300
        $renderer->setTheme($formView, $formTheme);
301
    }
302
}
303