Completed
Pull Request — master (#373)
by Michael
05:15 queued 01:03
created

DefaultController   F

Complexity

Total Complexity 63

Size/Duplication

Total Lines 413
Duplicated Lines 30.75 %

Test Coverage

Coverage 39.38%

Importance

Changes 1
Bugs 1 Features 0
Metric Value
wmc 63
c 1
b 1
f 0
dl 127
loc 413
ccs 76
cts 193
cp 0.3938
rs 3.6585

14 Methods

Rating   Name   Duplication   Size   Complexity  
A buildLicenseeIndex() 0 10 2
A buildImportfileIndex() 0 10 2
A licenseeSuggestAction() 22 22 2
A saveTopicImage() 15 15 4
B useractivationmailAction() 0 36 2
A indexAction() 0 13 1
A saveFile() 17 17 4
C usersAction() 11 40 8
A formatMetadata() 0 8 2
A licenseesAction() 16 16 2
A topicsAction() 18 18 2
C formsaveAction() 0 66 24
B textnodesAction() 0 27 6
A topicSuggestAction() 22 22 2

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like DefaultController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use DefaultController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/* Copyright (C) 2015 Michael Giesler
4
 *
5
 * This file is part of Dembelo.
6
 *
7
 * Dembelo is free software: you can redistribute it and/or modify
8
 * it under the terms of the GNU Affero General Public License as published by
9
 * the Free Software Foundation, either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * Dembelo is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
 * GNU Affero General Public License 3 for more details.
16
 *
17
 * You should have received a copy of the GNU Affero General Public License 3
18
 * along with Dembelo. If not, see <http://www.gnu.org/licenses/>.
19
 */
20
21
22
/**
23
 * @package AdminBundle
24
 */
25
26
namespace AdminBundle\Controller;
27
28
use DembeloMain\Model\Repository\Doctrine\ODM\AbstractRepository;
29
use DembeloMain\Document\Importfile;
30
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
31
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
32
use Symfony\Component\HttpFoundation\Request;
33
use Symfony\Component\HttpFoundation\Response;
34
use StdClass;
35
use DembeloMain\Document\Topic;
36
use Symfony\Component\Serializer\Encoder\JsonEncoder;
37
38
/**
39
 * Class DefaultController
40
 */
41
class DefaultController extends Controller
42
{
43
44
    /**
45
     * @Route("/", name="admin_mainpage")
46
     *
47
     * @return Response
48
     */
49
    public function indexAction(): Response
50
    {
51
        $mainMenuData = [
52
            ['id' => '1', 'type' => 'folder', 'value' => 'Benutzer', 'css' => 'folder_music'],
53
            ['id' => '2', 'type' => 'folder', 'value' => 'Lizenznehmer', 'css' => 'folder_music'],
54
            ['id' => '3', 'type' => 'folder', 'value' => 'Themenfelder', 'css' => 'folder_music'],
55
            ['id' => '4', 'type' => 'folder', 'value' => 'Importe', 'css' => 'folder_music'],
56
            ['id' => '5', 'type' => 'folder', 'value' => 'Textknoten', 'css' => 'folder_music'],
57
        ];
58
59
        $jsonEncoder = new JsonEncoder();
60
61
        return $this->render('AdminBundle::index.html.twig', array('mainMenuData' => $jsonEncoder->encode($mainMenuData, 'json')));
62
    }
63
64
    /**
65
     * @Route("/users", name="admin_users")
66
     *
67
     * @param Request $request
68
     * @return Response
69
     */
70
    public function usersAction(Request $request): Response
71
    {
72
        $repository = $this->get('app.model_repository_user');
73 2
74
        $filters = $request->query->get('filter');
75 2
76
        $query = $repository->createQueryBuilder();
77 2
        if (null !== $filters) {
78 View Code Duplication
            foreach ($filters as $field => $value) {
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...
79 2
                if (empty($value) && $value !== '0') {
80 2
                    continue;
81 2
                }
82
                if ($field === 'status') {
83
                    //$value = $value === 'aktiv' ? 1 : 0;
84
                    $query->field($field)->equals((int) $value);
85
                } else {
86
                    $query->field($field)->equals(new \MongoRegex('/.*'.$value.'.*/i'));
87
                }
88
            }
89
        }
90
        $users = $query->getQuery()->execute();
91
92
        $output = array();
93 2
        /* @var $user \DembeloMain\Document\User */
94
        foreach ($users as $user) {
95 2
            $obj = new StdClass();
96
            $obj->id = $user->getId();
97 2
            $obj->email = $user->getEmail();
98 1
            $obj->roles = implode(', ', $user->getRoles());
99 1
            $obj->licenseeId = is_null($user->getLicenseeId()) ? '' : $user->getLicenseeId();
100 1
            $obj->gender = $user->getGender();
101 1
            $obj->status = $user->getStatus(); // === 0 ? 'inaktiv' : 'aktiv';
102 1
            $obj->source = $user->getSource();
103 1
            $obj->reason = $user->getReason();
104 1
            $obj->created = date('Y-m-d H:i:s', $user->getMetadata()['created']);
105 1
            $obj->updated = date('Y-m-d H:i:s', $user->getMetadata()['updated']);
106 1
            $output[] = $obj;
107 1
        }
108 1
109 1
        return new Response(\json_encode($output));
110
    }
111
112 2
    /**
113
     * @Route("/licensees", name="admin_licensees")
114
     *
115
     * @return Response
116
     */
117 View Code Duplication
    public function licenseesAction(): Response
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...
118
    {
119
        $repository = $this->get('app.model_repository_licensee');
120 2
121
        $licensees = $repository->findAll();
122 2
123
        $output = array();
124 2
        /* @var $licensee \DembeloMain\Document\Licensee */
125
        foreach ($licensees as $licensee) {
126 2
            $obj = new StdClass();
127
            $obj->id = $licensee->getId();
128 2
            $obj->name = $licensee->getName();
129 1
            $output[] = $obj;
130 1
        }
131 1
132 1
        return new Response(\json_encode($output));
133
    }
134
135 2
    /**
136
     * @Route("/licenseeSuggest", name="admin_licensee_suggest")
137
     *
138
     * @param Request $request
139
     * @return Response
140
     */
141 View Code Duplication
    public function licenseeSuggestAction(Request $request): Response
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...
142
    {
143
        $filter = $request->query->get('filter');
144
145
        $searchString = $filter['value'];
146
147
        $mongo = $this->get('doctrine_mongodb');
148
        /* @var $repository \Doctrine\ODM\MongoDB\DocumentRepository */
149
        $repository = $mongo->getRepository('DembeloMain:Licensee');
150
151
        $licensees = $repository->findBy(array('name' => new \MongoRegex('/'.$searchString.'/')), null, 10);
152
153
        $output = array();
154
        /* @var $licensee \DembeloMain\Document\Licensee */
155
        foreach ($licensees as $licensee) {
156
            $output[] = array(
157
                'id' => $licensee->getId(),
158
                'value' => $licensee->getName(),
159
            );
160
        }
161
162
        return new Response(\json_encode($output));
163
    }
164
165
    /**
166
     * @Route("/topicSuggest", name="admin_topic_suggest")
167
     *
168
     * @param Request $request
169
     * @return Response
170
     */
171 View Code Duplication
    public function topicSuggestAction(Request $request): Response
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...
172
    {
173
        $filter = $request->query->get('filter');
174
175
        $searchString = $filter['value'];
176
177
        $mongo = $this->get('doctrine_mongodb');
178
        /* @var $repository \Doctrine\ODM\MongoDB\DocumentRepository */
179
        $repository = $mongo->getRepository('DembeloMain:Topic');
180
181
        /* @var $topics \DembeloMain\Document\Topic[] */
182
        $topics = $repository->findBy(array('name' => new \MongoRegex('/'.$searchString.'/')), null, 10);
183
184
        $output = [];
185
        foreach ($topics as $topic) {
186
            $output[] = array(
187
                'id' => $topic->getId(),
188
                'value' => $topic->getName(),
189
            );
190
        }
191
192
        return new Response(\json_encode($output));
193
    }
194
195
    /**
196
     * @Route("/topics", name="admin_topics")
197
     *
198
     * @return Response
199 5
     */
200 View Code Duplication
    public function topicsAction(): Response
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...
201 5
    {
202
        $mongo = $this->get('doctrine_mongodb');
203 5
        /* @var $repository \Doctrine\ODM\MongoDB\DocumentRepository */
204 2
        $repository = $mongo->getRepository('DembeloMain:Topic');
205
206 3
        $users = $repository->findAll();
207 1
208
        $output = array();
209 2
        /* @var $user \DembeloMain\Document\Topic */
210
        foreach ($users as $user) {
211
            $obj = new StdClass();
212 2
            $obj->id = $user->getId();
213
            $obj->name = $user->getName();
214 2
            $output[] = $obj;
215
        }
216
217
        return new Response(\json_encode($output));
218 2
    }
219 2
220 1
    /**
221
     * @Route("/save", name="admin_formsave")
222
     *
223
     * @param Request $request
224 1
     * @return Response
225 1
     */
226 1
    public function formsaveAction(Request $request): Response
227
    {
228
        $params = $request->request->all();
229
230
        if (!isset($params['formtype']) || !in_array($params['formtype'], array('user', 'licensee', 'topic', 'importfile', 'textnode'))) {
231
            return new Response(\json_encode(array('error' => true)));
232
        }
233
        if (!isset($params['id'])) {
234
            return new Response(\json_encode(array('error' => true)));
235
        }
236
        $formtype = $params['formtype'];
237
238
        /* @var $repository AbstractRepository */
239
        $repository = $this->get('app.model_repository_'.$formtype);
240
241
        if (isset($params['id']) && $params['id'] == 'new') {
242
            $className = $repository->getClassName();
243
            $item = new $className();
244 1
        } else {
245 1
            $item = $repository->find($params['id']);
246
            if (is_null($item) || $item->getId() != $params['id']) {
247 1
                return new Response(\json_encode(array('error' => true)));
248
            }
249 1
        }
250
251
        foreach ($params as $param => $value) {
252
            if (in_array($param, array('id', 'formtype', 'filename', 'orgname'))) {
253
                continue;
254 1
            }
255
            if ($param == 'password' && empty($value)) {
256
                continue;
257
            } elseif ($param == 'password') {
258
                $encoder = $this->get('security.password_encoder');
259
                $value = $encoder->encodePassword($item, $value);
260 1
            } elseif ($param == 'licenseeId' && $value === '') {
261 1
                $value = null;
262
            } elseif ($param === 'imported' && $value === '') {
263
                $value = null;
264 1
            }
265
            $method = 'set'.ucfirst($param);
266
            if (method_exists($item, $method)) {
267
                $item->$method($value);
268
            }
269
        }
270
        //var_dump($item);die();
271
        if (method_exists($item, 'setMetadata')) {
272
            $item->setMetadata('updated', time());
273
        }
274
        $repository->save($item);
275
276
        if ($formtype === 'topic' && array_key_exists('imageFileName', $params) && !is_null($params['imageFileName'])) {
277
            $this->saveTopicImage($item, $params['imageFileName'], $params['originalImageName']);
278
            $repository->save($item);
279
        }
280
281
        if ($formtype == 'importfile' && array_key_exists('filename', $params)) {
282
            $this->saveFile($item, $params['filename'], $params['orgname']);
283
            $repository->save($item);
284
        }
285
286
        $output = array(
287
            'error' => false,
288
            'newId' => $item->getId(),
289
        );
290
291
        return new Response(\json_encode($output));
292
    }
293
294
    /**
295
     * @Route("/useractivationmail", name="admin_user_activation_mail")
296
     *
297
     * @param Request $request
298
     * @return Response
299
     */
300
    public function useractivationmailAction(Request $request): Response
301
    {
302
        $userId = $request->request->get('userId');
303
304
        /* @var $mongo \Doctrine\Bundle\MongoDBBundle\ManagerRegistry */
305
        $mongo = $this->get('doctrine_mongodb');
306
        /* @var $dm \Doctrine\ODM\MongoDB\DocumentManager*/
307
        $dm = $mongo->getManager();
308
309
        $repository = $mongo->getRepository('DembeloMain:User');
310
311
        /* @var $user \DembeloMain\Document\User */
312
        $user = $repository->find($userId);
313
        if (null === $user) {
314
            return new Response(\json_encode(['error' => false]));
315
        }
316
        $user->setActivationHash(sha1($user->getEmail().$user->getPassword().\time()));
317
318
        $dm->persist($user);
319
        $dm->flush();
320
321
        $message = (new \Swift_Message('waszulesen - Bestätigung der Email-Adresse'))
322
            ->setFrom('[email protected]')
323
            ->setTo($user->getEmail())
324
            ->setBody(
325
                $this->renderView(
326
                    // app/Resources/views/Emails/registration.html.twig
327
                    'AdminBundle::Emails/registration.txt.twig',
328
                    array('hash' => $user->getActivationHash())
329
                ),
330
                'text/html'
331
            );
332
333
        $this->get('mailer')->send($message);
334
335
        return new Response(\json_encode(['error' => false]));
336
    }
337
338
    /**
339
     * @Route("/textnodes", name="admin_textnodes")
340
     *
341
     * @return Response
342
     */
343
    public function textnodesAction(): Response
344
    {
345
        $repository = $this->get('app.model_repository_textNode');
346
        $textnodes = $repository->findAll();
347
348
        $licenseeIndex = $this->buildLicenseeIndex();
349
        $importfileIndex = $this->buildImportfileIndex();
350
351
        $output = array();
352
        /* @var $textnode \DembeloMain\Document\Textnode */
353
        foreach ($textnodes as $textnode) {
354
            $obj = new StdClass();
355
            $obj->id = $textnode->getId();
356
            $obj->arbitraryId = $textnode->getArbitraryId();
357
            $obj->created = $textnode->getCreated()->format('d.m.Y, H:i:s');
358
            $obj->status = $textnode->getStatus() ? 'aktiv' : 'inaktiv';
359
            $obj->access = $textnode->getAccess() ? 'ja' : 'nein';
360
            $obj->licensee = $licenseeIndex[$textnode->getLicenseeId()];
361
            $obj->importfile = isset($importfileIndex[$textnode->getImportfileId()]) ? $importfileIndex[$textnode->getImportfileId()] : 'unbekannt';
362
            $obj->beginning = substr(htmlentities(strip_tags($textnode->getText())), 0, 200)."...";
363
            $obj->financenode = $textnode->isFinanceNode() ? 'ja' : 'nein';
364
            $obj->twineId = $textnode->getTwineId();
365
            $obj->metadata = $this->formatMetadata($textnode->getMetadata());
366
            $output[] = $obj;
367
        }
368
369
        return new Response(\json_encode($output));
370
    }
371
372
    /**
373
     * saves temporary file to final place
374
     *
375 1
     * @param Importfile $item importfile instance
376
     * @param string $filename filename hash
377 1
     * @param string $orgname original name
378 1
     */
379 View Code Duplication
    private function saveFile(Importfile $item, $filename, $orgname)
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...
380 1
    {
381 1
        if (empty($filename) || empty($orgname)) {
382
            return;
383 1
        }
384
385 1
        $directory = $this->container->getParameter('twine_directory');
386 1
        $finalDirectory = $directory.$item->getLicenseeId().'/';
387 1
        if (!is_dir($finalDirectory)) {
388 1
            mkdir($finalDirectory);
389 1
        }
390 1
        $finalName = $finalDirectory.$item->getId();
391 1
        $file = $directory.$filename;
392 1
        rename($file, $finalName);
393 1
394 1
        $item->setOriginalname($orgname);
395 1
        $item->setFilename($finalName);
396 1
    }
397 1
398 1
    private function buildLicenseeIndex(): array
399
    {
400
        $repository = $this->get('app.model_repository_licensee');
401 1
        $licensees = $repository->findAll();
402
        $index = [];
403
        foreach ($licensees as $licensee) {
404
            $index[$licensee->getID()] = $licensee->getName();
405
        }
406
407
        return $index;
408
    }
409
410
    private function buildImportfileIndex(): array
411
    {
412
        $repository = $this->get('app.model_repository_importfile');
413
        $importfiles = $repository->findAll();
414
        $index = [];
415
        foreach ($importfiles as $importfile) {
416
            $index[$importfile->getID()] = $importfile->getName();
417
        }
418
419
        return $index;
420
    }
421
422
    /**
423
     * saves temporary file to final place
424
     *
425
     * @param Topic $item topic instance
426
     * @param string $filename filename hash
427
     * @param string $orgname original name
428
     */
429 View Code Duplication
    private function saveTopicImage(Topic $item, $filename, $orgname)
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...
430
    {
431
        if (empty($filename) || empty($orgname)) {
432
            return;
433
        }
434
        $directory = $this->container->getParameter('topic_image_directory');
435
        $finalDirectory = $directory.$item->getId().'/';
436
        if (!is_dir($finalDirectory)) {
437
            mkdir($finalDirectory);
438
        }
439
        $finalName = $finalDirectory.$orgname;
440
        $file = $directory.$filename;
441
        rename($file, $finalName);
442
        $item->setOriginalImageName($orgname);
443
        $item->setImageFilename($finalName);
444
    }
445
446
    private function formatMetadata(array $metadata): string
447
    {
448
        $string = '';
449
        foreach ($metadata as $key => $value) {
450
            $string .= $key.': '.$value."\n";
451
        }
452
453
        return $string;
454
    }
455
}
456