Passed
Push — master ( c71cfc...3755d0 )
by Michael
01:44
created

DefaultController::usersAction()   C

Complexity

Conditions 8
Paths 6

Size

Total Lines 40
Code Lines 27

Duplication

Lines 11
Ratio 27.5 %

Code Coverage

Tests 22
CRAP Score 8.4065

Importance

Changes 0
Metric Value
dl 11
loc 40
ccs 22
cts 27
cp 0.8148
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 27
nc 6
nop 1
crap 8.4065
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\Document\User;
29
use DembeloMain\Model\Repository\Doctrine\ODM\AbstractRepository;
30
use DembeloMain\Document\Importfile;
31
use DembeloMain\Model\Repository\ImportfileRepositoryInterface;
32
use DembeloMain\Model\Repository\LicenseeRepositoryInterface;
33
use DembeloMain\Model\Repository\TopicRepositoryInterface;
34
use DembeloMain\Model\Repository\UserRepositoryInterface;
35
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
36
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
37
use Symfony\Component\Filesystem\Filesystem;
38
use Symfony\Component\HttpFoundation\Request;
39
use Symfony\Component\HttpFoundation\Response;
40
use DembeloMain\Document\Topic;
41
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoder;
42
use Symfony\Component\Serializer\Encoder\JsonEncoder;
43
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface as Templating;
44
45
/**
46
 * Class DefaultController
47
 * @Route(service="app.admin_controller_default")
48
 */
49
class DefaultController extends Controller
50
{
51
    /**
52
     * @var string
53
     */
54
    private $configTwineDirectory;
55
56
    /**
57
     * @var Templating
58
     */
59
    private $templating;
60
61
    /**
62
     * @var UserRepositoryInterface
63
     */
64
    private $userRepository;
65
66
    /**
67
     * @var LicenseeRepositoryInterface
68
     */
69
    private $licenseeRepository;
70
71
    /**
72
     * @var TopicRepositoryInterface
73
     */
74
    private $topicRepository;
75
76
    /**
77
     * @var ImportfileRepositoryInterface
78
     */
79
    private $importfileRepository;
80
81
    /**
82
     * @var UserPasswordEncoder
83
     */
84
    private $userPasswordEncoder;
85
86
    /**
87
     * @var string
88
     */
89
    private $topicImageDirectory;
90
91
    /**
92
     * @var Filesystem
93
     */
94
    private $filesystem;
95
96
    /**
97
     * DefaultController constructor.
98
     * @param Templating                    $templating
99
     * @param UserRepositoryInterface       $userRepository
100
     * @param LicenseeRepositoryInterface   $licenseeRepository
101
     * @param TopicRepositoryInterface      $topicRepository
102
     * @param ImportfileRepositoryInterface $importfileRepository
103
     * @param UserPasswordEncoder           $userPasswordEncoder
104
     * @param string                        $configTwineDirectory
105
     * @param string                        $topicImageDirectory
106
     * @param Filesystem                    $filesystem
107
     */
108 7
    public function __construct(
109
        Templating $templating,
110
        UserRepositoryInterface $userRepository,
111
        LicenseeRepositoryInterface $licenseeRepository,
112
        TopicRepositoryInterface $topicRepository,
113
        ImportfileRepositoryInterface $importfileRepository,
114
        UserPasswordEncoder $userPasswordEncoder,
115
        string $configTwineDirectory,
116
        string $topicImageDirectory,
117
        Filesystem $filesystem
118
    ) {
119 7
        $this->configTwineDirectory = $configTwineDirectory;
120 7
        $this->userRepository = $userRepository;
121 7
        $this->templating = $templating;
122 7
        $this->licenseeRepository = $licenseeRepository;
123 7
        $this->topicRepository = $topicRepository;
124 7
        $this->importfileRepository = $importfileRepository;
125 7
        $this->userPasswordEncoder = $userPasswordEncoder;
126 7
        $this->topicImageDirectory = $topicImageDirectory;
127 7
        $this->filesystem = $filesystem;
128 7
    }
129
130
    /**
131
     * @Route("/", name="admin_mainpage")
132
     *
133
     * @return Response
134
     * @throws \RuntimeException
135
     */
136 1
    public function indexAction(): Response
137
    {
138
        $mainMenuData = [
139 1
            ['id' => '1', 'type' => 'folder', 'value' => 'Benutzer', 'css' => 'folder_music'],
140
            ['id' => '2', 'type' => 'folder', 'value' => 'Lizenznehmer', 'css' => 'folder_music'],
141
            ['id' => '3', 'type' => 'folder', 'value' => 'Themenfelder', 'css' => 'folder_music'],
142
            ['id' => '4', 'type' => 'folder', 'value' => 'Importe', 'css' => 'folder_music'],
143
            ['id' => '5', 'type' => 'folder', 'value' => 'Textknoten', 'css' => 'folder_music'],
144
        ];
145
146 1
        $jsonEncoder = new JsonEncoder();
147
148 1
        return $this->templating->renderResponse(
149 1
            'AdminBundle::index.html.twig',
150
            [
151 1
                'mainMenuData' => $jsonEncoder->encode($mainMenuData, 'json'),
152
            ]
153
        );
154
    }
155
156
    /**
157
     * @Route("/save", name="admin_formsave")
158
     *
159
     * @param Request $request
160
     * @return Response
161
     * @throws \Symfony\Component\Filesystem\Exception\IOException
162
     * @throws \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
163
     * @throws \Exception
164
     * @throws \RuntimeException
165
     * @throws \InvalidArgumentException
166
     */
167 6
    public function formsaveAction(Request $request): Response
168
    {
169 6
        $params = $request->request->all();
170
171 6
        if (!isset($params['id'])) {
172 1
            return new Response(\json_encode(array('error' => true)));
173
        }
174 5
        $formtype = $params['formtype'] ?? '';
175
176
        /* @var $repository AbstractRepository */
177
        switch ($formtype) {
178 5
            case 'user':
179 1
                $repository = $this->userRepository;
180 1
                break;
181 4
            case 'topic':
182 1
                $repository = $this->topicRepository;
183 1
                break;
184 3
            case 'licensee':
185 1
                $repository = $this->licenseeRepository;
186 1
                break;
187 2
            case 'importfile':
188 1
                $repository = $this->importfileRepository;
189 1
                break;
190
            default:
191 1
                return new Response(\json_encode(array('error' => true)));
192
        }
193
194 4
        if (isset($params['id']) && $params['id'] === 'new') {
195 1
            $className = $repository->getClassName();
196 1
            $item = new $className();
197
        } else {
198 3
            $item = $repository->find($params['id']);
199 3
            if (null === $item || $item->getId() !== $params['id']) {
200
                return new Response(\json_encode(array('error' => true)));
201
            }
202
        }
203
204 4
        foreach ($params as $param => $value) {
205 4
            if (in_array($param, array('id', 'formtype', 'filename', 'orgname'), true)) {
206 4
                continue;
207
            }
208 2
            if ($param === 'password' && empty($value)) {
209
                continue;
210
            }
211
212 2
            if ($item instanceof User && $param === 'password') {
213 1
                $value = $this->userPasswordEncoder->encodePassword($item, $value);
214 2
            } elseif ($value === '' && in_array($param, ['licenseeId', 'imported'], true)) {
215
                $value = null;
216
            }
217 2
            $method = 'set'.ucfirst($param);
218 2
            if (method_exists($item, $method)) {
219 2
                $item->$method($value);
220
            }
221
        }
222
223 4
        if (method_exists($item, 'setMetadata')) {
224 1
            $item->setMetadata('updated', time());
225
        }
226 4
        $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 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

226
        $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; 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

226
        $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

226
        $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

226
        $repository->save(/** @scrutinizer ignore-type */ $item);
Loading history...
227
228 4
        if ($item instanceof Topic
229 1
            && array_key_exists('imageFileName', $params)
230 1
            && array_key_exists('originalImageName', $params)
231 1
            && !empty($params['imageFileName'])
232 1
            && !empty($params['originalImageName'])
233
        ) {
234 1
            $this->saveTopicImage($item, $params['imageFileName'], $params['originalImageName']);
235 1
            $repository->save($item);
0 ignored issues
show
Bug introduced by
$item of type DembeloMain\Document\Lic...beloMain\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

235
            $repository->save(/** @scrutinizer ignore-type */ $item);
Loading history...
Bug introduced by
It seems like $item can also be of type DembeloMain\Document\Use...beloMain\Document\Topic and DembeloMain\Document\Topic; 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

235
            $repository->save(/** @scrutinizer ignore-type */ $item);
Loading history...
Bug introduced by
It seems like $item can also be of type DembeloMain\Document\Lic...beloMain\Document\Topic 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

235
            $repository->save(/** @scrutinizer ignore-type */ $item);
Loading history...
236
        }
237
238 4
        if ($item instanceof Importfile
239 1
            && array_key_exists('filename', $params)
240 1
            && array_key_exists('orgname', $params)
241 1
            && !empty($params['filename'])
242 1
            && !empty($params['orgname'])
243
        ) {
244 1
            $this->saveFile($item, $params['filename'], $params['orgname']);
245 1
            $repository->save($item);
0 ignored issues
show
Bug introduced by
It seems like $item can also be of type DembeloMain\Document\Top...ain\Document\Importfile and DembeloMain\Document\Importfile and DembeloMain\Document\Lic...ain\Document\Importfile; 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

245
            $repository->save(/** @scrutinizer ignore-type */ $item);
Loading history...
Bug introduced by
It seems like $item can also be of type DembeloMain\Document\Top...ain\Document\Importfile and DembeloMain\Document\Importfile and DembeloMain\Document\Use...ain\Document\Importfile; 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

245
            $repository->save(/** @scrutinizer ignore-type */ $item);
Loading history...
Bug introduced by
It seems like $item can also be of type DembeloMain\Document\Importfile and DembeloMain\Document\Lic...ain\Document\Importfile and DembeloMain\Document\Use...ain\Document\Importfile; 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

245
            $repository->save(/** @scrutinizer ignore-type */ $item);
Loading history...
246
        }
247
248
        $output = array(
249 4
            'error' => false,
250 4
            'newId' => $item->getId(),
251
        );
252
253 4
        return new Response(\json_encode($output));
254
    }
255
256
    /**
257
     * saves temporary file to final place
258
     *
259
     * @param Importfile $item importfile instance
260
     * @param string $filename filename hash
261
     * @param string $orgname original name
262
     * @throws \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
263
     * @throws \RuntimeException
264
     * @throws \Symfony\Component\Filesystem\Exception\IOException
265
     */
266 1
    private function saveFile(Importfile $item, $filename, $orgname)
267
    {
268 1
        $directory = $this->configTwineDirectory;
269 1
        $file = $directory.$filename;
270 1
        if (!$this->filesystem->exists($file)) {
271
            return;
272
        }
273 1
        $finalDirectory = $directory.$item->getLicenseeId().'/';
274 1
        $this->filesystem->mkdir($finalDirectory);
275 1
        $finalName = $finalDirectory.$item->getId();
276
277 1
        $this->filesystem->rename($file, $finalName);
278
279 1
        $item->setOriginalname($orgname);
280 1
        $item->setFilename($finalName);
281 1
    }
282
283
    /**
284
     * saves temporary file to final place
285
     *
286
     * @param Topic $item topic instance
287
     * @param string $filename filename hash
288
     * @param string $orgname original name
289
     * @throws \RuntimeException
290
     */
291 1
    private function saveTopicImage(Topic $item, string $filename, string $orgname)
292
    {
293 1
        $directory = $this->topicImageDirectory;
294 1
        $finalDirectory = $directory.$item->getId().'/';
295 1
        $this->filesystem->mkdir($finalDirectory);
296
297 1
        $finalName = $finalDirectory.$orgname;
298 1
        $file = $directory.$filename;
299 1
        $this->filesystem->rename($file, $finalName);
300 1
        $item->setOriginalImageName($orgname);
301 1
        $item->setImageFilename($finalName);
302 1
    }
303
}
304