Completed
Push — bugfix/364-refactor-adminBundl... ( e3c582 )
by Michael
04:28
created

DefaultController::saveFile()   C

Complexity

Conditions 7
Paths 4

Size

Total Lines 23
Code Lines 14

Duplication

Lines 23
Ratio 100 %

Importance

Changes 0
Metric Value
dl 23
loc 23
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 14
nc 4
nop 3
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 DembeloMain\Model\Repository\ImportfileRepositoryInterface;
31
use DembeloMain\Model\Repository\LicenseeRepositoryInterface;
32
use DembeloMain\Model\Repository\TopicRepositoryInterface;
33
use DembeloMain\Model\Repository\UserRepositoryInterface;
34
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
35
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
36
use Symfony\Component\HttpFoundation\Request;
37
use Symfony\Component\HttpFoundation\Response;
38
use DembeloMain\Document\Topic;
39
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoder;
40
use Symfony\Component\Serializer\Encoder\JsonEncoder;
41
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface as Templating;
42
43
/**
44
 * Class DefaultController
45
 * @Route(service="app.admin_controller_default")
46
 */
47
class DefaultController extends Controller
48
{
49
    /**
50
     * @var string
51
     */
52
    private $configTwineDirectory;
53
54
    /**
55
     * @var Templating
56
     */
57
    private $templating;
58
59
    /**
60
     * @var UserRepositoryInterface
61
     */
62
    private $userRepository;
63
64
    /**
65
     * @var LicenseeRepositoryInterface
66
     */
67
    private $licenseeRepository;
68
69
    /**
70
     * @var TopicRepositoryInterface
71
     */
72
    private $topicRepository;
73
74
    /**
75
     * @var ImportfileRepositoryInterface
76
     */
77
    private $importfileRepository;
78
79
    /**
80
     * @var UserPasswordEncoder
81
     */
82
    private $userPasswordEncoder;
83
84
    /**
85
     * @var string
86
     */
87
    private $topicImageDirectory;
88
89
    /**
90
     * DefaultController constructor.
91
     * @param Templating                    $templating
92
     * @param UserRepositoryInterface       $userRepository
93
     * @param LicenseeRepositoryInterface   $licenseeRepository
94
     * @param TopicRepositoryInterface      $topicRepository
95
     * @param ImportfileRepositoryInterface $importfileRepository
96
     * @param UserPasswordEncoder           $userPasswordEncoder
97
     * @param string                        $configTwineDirectory
98
     * @param string                        $topicImageDirectory
99
     */
100
    public function __construct(
101
        Templating $templating,
102
        UserRepositoryInterface $userRepository,
103
        LicenseeRepositoryInterface $licenseeRepository,
104
        TopicRepositoryInterface $topicRepository,
105
        ImportfileRepositoryInterface $importfileRepository,
106
        UserPasswordEncoder $userPasswordEncoder,
107
        string $configTwineDirectory,
108
        string $topicImageDirectory
109
    ) {
110
        $this->configTwineDirectory = $configTwineDirectory;
111
        $this->userRepository = $userRepository;
112
        $this->templating = $templating;
113
        $this->licenseeRepository = $licenseeRepository;
114
        $this->topicRepository = $topicRepository;
115
        $this->importfileRepository = $importfileRepository;
116
        $this->userPasswordEncoder = $userPasswordEncoder;
117
        $this->topicImageDirectory = $topicImageDirectory;
118
    }
119
120
    /**
121
     * @Route("/", name="admin_mainpage")
122
     *
123
     * @return Response
124
     * @throws \RuntimeException
125
     */
126
    public function indexAction(): Response
127
    {
128
        $mainMenuData = [
129
            ['id' => '1', 'type' => 'folder', 'value' => 'Benutzer', 'css' => 'folder_music'],
130
            ['id' => '2', 'type' => 'folder', 'value' => 'Lizenznehmer', 'css' => 'folder_music'],
131
            ['id' => '3', 'type' => 'folder', 'value' => 'Themenfelder', 'css' => 'folder_music'],
132
            ['id' => '4', 'type' => 'folder', 'value' => 'Importe', 'css' => 'folder_music'],
133
            ['id' => '5', 'type' => 'folder', 'value' => 'Textknoten', 'css' => 'folder_music'],
134
        ];
135
136
        $jsonEncoder = new JsonEncoder();
137
138
        return $this->templating->renderResponse(
139
            'AdminBundle::index.html.twig',
140
            [
141
                'mainMenuData' => $jsonEncoder->encode($mainMenuData, 'json'),
142
            ]
143
        );
144
    }
145
146
    /**
147
     * @Route("/save", name="admin_formsave")
148
     *
149
     * @param Request $request
150
     * @return Response
151
     * @throws \Exception
152
     * @throws \RuntimeException
153
     * @throws \InvalidArgumentException
154
     */
155
    public function formsaveAction(Request $request): Response
156
    {
157
        $params = $request->request->all();
158
159
        if (!isset($params['formtype']) || !in_array($params['formtype'], array('user', 'licensee', 'topic', 'importfile', 'textnode'), true)) {
160
            return new Response(\json_encode(array('error' => true)));
161
        }
162
        if (!isset($params['id'])) {
163
            return new Response(\json_encode(array('error' => true)));
164
        }
165
        $formtype = $params['formtype'];
166
167
        /* @var $repository AbstractRepository */
168
        switch ($formtype) {
169
            case 'user':
170
                $repository = $this->userRepository;
171
                break;
172
            case 'topic':
173
                $repository = $this->topicRepository;
174
                break;
175
            case 'licensee':
176
                $repository = $this->licenseeRepository;
177
                break;
178
            case 'importfile':
179
                $repository = $this->importfileRepository;
180
                break;
181
            default:
182
                throw new \RuntimeException('unknown formtype ['.$formtype.']');
183
        }
184
185
        if (isset($params['id']) && $params['id'] === 'new') {
186
            $className = $repository->getClassName();
187
            $item = new $className();
188
        } else {
189
            $item = $repository->find($params['id']);
190
            if (null === $item || $item->getId() !== $params['id']) {
191
                return new Response(\json_encode(array('error' => true)));
192
            }
193
        }
194
195
        foreach ($params as $param => $value) {
196
            if (in_array($param, array('id', 'formtype', 'filename', 'orgname'), true)) {
197
                continue;
198
            }
199
            if ($param === 'password' && empty($value)) {
200
                continue;
201
            }
202
203
            if ($param === 'password') {
204
                $value = $this->userPasswordEncoder->encodePassword($item, $value);
0 ignored issues
show
Bug introduced by
It seems like $item can also be of type DembeloMain\Document\Licensee and DembeloMain\Document\Topic; however, parameter $user of Symfony\Component\Securi...coder::encodePassword() does only seem to accept Symfony\Component\Security\Core\User\UserInterface, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

204
                $value = $this->userPasswordEncoder->encodePassword(/** @scrutinizer ignore-type */ $item, $value);
Loading history...
205
            } elseif ($param === 'licenseeId' && $value === '') {
206
                $value = null;
207
            } elseif ($param === 'imported' && $value === '') {
208
                $value = null;
209
            }
210
            $method = 'set'.ucfirst($param);
211
            if (method_exists($item, $method)) {
212
                $item->$method($value);
213
            }
214
        }
215
        //var_dump($item);die();
216
        if (method_exists($item, 'setMetadata')) {
217
            $item->setMetadata('updated', time());
218
        }
219
        $repository->save($item);
0 ignored issues
show
Bug introduced by
It seems like $item can also be of type DembeloMain\Document\Licensee and DembeloMain\Document\Topic; however, parameter $user of DembeloMain\Model\Reposi...sitoryInterface::save() does only seem to accept DembeloMain\Document\User, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

219
        $repository->save(/** @scrutinizer ignore-type */ $item);
Loading history...
Bug introduced by
It seems like $item can also be of type DembeloMain\Document\Licensee and DembeloMain\Document\Topic and DembeloMain\Document\User; however, parameter $importfile of DembeloMain\Model\Reposi...sitoryInterface::save() does only seem to accept DembeloMain\Document\Importfile, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

219
        $repository->save(/** @scrutinizer ignore-type */ $item);
Loading history...
Bug introduced by
It seems like $item can also be of type DembeloMain\Document\Licensee and DembeloMain\Document\User; however, parameter $topic of DembeloMain\Model\Reposi...sitoryInterface::save() does only seem to accept DembeloMain\Document\Topic, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

219
        $repository->save(/** @scrutinizer ignore-type */ $item);
Loading history...
Bug introduced by
It seems like $item can also be of type DembeloMain\Document\Topic and DembeloMain\Document\User; however, parameter $licensee of DembeloMain\Model\Reposi...sitoryInterface::save() does only seem to accept DembeloMain\Document\Licensee, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

219
        $repository->save(/** @scrutinizer ignore-type */ $item);
Loading history...
220
221
        if ($formtype === 'topic' && array_key_exists('imageFileName', $params) && !is_null($params['imageFileName'])) {
222
            $this->saveTopicImage($item, $params['imageFileName'], $params['originalImageName']);
0 ignored issues
show
Bug introduced by
It seems like $item can also be of type DembeloMain\Document\Licensee and DembeloMain\Document\User; however, parameter $item of AdminBundle\Controller\D...oller::saveTopicImage() does only seem to accept DembeloMain\Document\Topic, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

222
            $this->saveTopicImage(/** @scrutinizer ignore-type */ $item, $params['imageFileName'], $params['originalImageName']);
Loading history...
223
            $repository->save($item);
0 ignored issues
show
Bug introduced by
$item of type DembeloMain\Document\Topic is incompatible with the type DembeloMain\Document\User expected by parameter $user of DembeloMain\Model\Reposi...sitoryInterface::save(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

223
            $repository->save(/** @scrutinizer ignore-type */ $item);
Loading history...
Bug introduced by
$item of type DembeloMain\Document\Topic is incompatible with the type DembeloMain\Document\Importfile expected by parameter $importfile of DembeloMain\Model\Reposi...sitoryInterface::save(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

223
            $repository->save(/** @scrutinizer ignore-type */ $item);
Loading history...
Bug introduced by
$item of type DembeloMain\Document\Topic is incompatible with the type DembeloMain\Document\Licensee expected by parameter $licensee of DembeloMain\Model\Reposi...sitoryInterface::save(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

223
            $repository->save(/** @scrutinizer ignore-type */ $item);
Loading history...
224
        }
225
226
        if ($formtype === 'importfile' && array_key_exists('filename', $params)) {
227
            $this->saveFile($item, $params['filename'], $params['orgname']);
0 ignored issues
show
Bug introduced by
It seems like $item can also be of type DembeloMain\Document\Licensee and DembeloMain\Document\Topic and DembeloMain\Document\User; however, parameter $item of AdminBundle\Controller\D...tController::saveFile() does only seem to accept DembeloMain\Document\Importfile, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

227
            $this->saveFile(/** @scrutinizer ignore-type */ $item, $params['filename'], $params['orgname']);
Loading history...
228
            $repository->save($item);
0 ignored issues
show
Bug introduced by
$item of type DembeloMain\Document\Importfile is incompatible with the type DembeloMain\Document\Licensee expected by parameter $licensee of DembeloMain\Model\Reposi...sitoryInterface::save(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

228
            $repository->save(/** @scrutinizer ignore-type */ $item);
Loading history...
Bug introduced by
$item of type DembeloMain\Document\Importfile is incompatible with the type DembeloMain\Document\User expected by parameter $user of DembeloMain\Model\Reposi...sitoryInterface::save(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

228
            $repository->save(/** @scrutinizer ignore-type */ $item);
Loading history...
Bug introduced by
$item of type DembeloMain\Document\Importfile is incompatible with the type DembeloMain\Document\Topic expected by parameter $topic of DembeloMain\Model\Reposi...sitoryInterface::save(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

228
            $repository->save(/** @scrutinizer ignore-type */ $item);
Loading history...
229
        }
230
231
        $output = array(
232
            'error' => false,
233
            'newId' => $item->getId(),
234
        );
235
236
        return new Response(\json_encode($output));
237
    }
238
239
    /**
240
     * saves temporary file to final place
241
     *
242
     * @param Importfile $item importfile instance
243
     * @param string $filename filename hash
244
     * @param string $orgname original name
245
     * @throws \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
246
     * @throws \RuntimeException
247
     */
248 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...
249
    {
250
        if (empty($filename) || empty($orgname)) {
251
            return;
252
        }
253
254
        $directory = $this->configTwineDirectory;
255
        $file = $directory.$filename;
256
        if (!file_exists($file)) {
257
            return;
258
        }
259
        $finalDirectory = $directory.$item->getLicenseeId().'/';
260
        if (!is_dir($finalDirectory)) {
261
            if (!mkdir($finalDirectory) && !is_dir($finalDirectory)) {
262
                throw new \RuntimeException(sprintf('Directory "%s" was not created', $finalDirectory));
263
            }
264
        }
265
        $finalName = $finalDirectory.$item->getId();
266
267
        rename($file, $finalName);
268
269
        $item->setOriginalname($orgname);
270
        $item->setFilename($finalName);
271
    }
272
273
    /**
274
     * saves temporary file to final place
275
     *
276
     * @param Topic $item topic instance
277
     * @param string $filename filename hash
278
     * @param string $orgname original name
279
     * @throws \RuntimeException
280
     */
281 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...
282
    {
283
        if (empty($filename) || empty($orgname)) {
284
            return;
285
        }
286
        $directory = $this->topicImageDirectory;
287
        $finalDirectory = $directory.$item->getId().'/';
288
        if (!is_dir($finalDirectory)) {
289
            if (!mkdir($finalDirectory) && !is_dir($finalDirectory)) {
290
                throw new \RuntimeException(sprintf('Directory "%s" was not created', $finalDirectory));
291
            }
292
        }
293
        $finalName = $finalDirectory.$orgname;
294
        $file = $directory.$filename;
295
        rename($file, $finalName);
296
        $item->setOriginalImageName($orgname);
297
        $item->setImageFilename($finalName);
298
    }
299
}
300