Passed
Push — develop ( aa7b98...444ddf )
by BENARD
02:50
created

AvatarController::getResponse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 9
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
namespace ProjetNormandie\UserBundle\Controller;
4
5
use Doctrine\ORM\EntityManagerInterface;
6
use Exception;
7
use League\Flysystem\FilesystemException;
8
use ProjetNormandie\UserBundle\Entity\User;
9
use ProjetNormandie\UserBundle\Service\AvatarManager;
10
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
11
use Symfony\Component\HttpFoundation\JsonResponse;
12
use Symfony\Component\HttpFoundation\StreamedResponse;
13
use Symfony\Component\HttpFoundation\Request;
14
use Symfony\Component\HttpFoundation\Response;
15
use Symfony\Contracts\Translation\TranslatorInterface;
16
17
class AvatarController extends AbstractController
18
{
19
    private TranslatorInterface $translator;
20
    private EntityManagerInterface $em;
21
    private AvatarManager $avatarManager;
22
23
24
    public function __construct(TranslatorInterface $translator, EntityManagerInterface $em, AvatarManager $avatarManager)
25
    {
26
        $this->translator = $translator;
27
        $this->em = $em;
28
        $this->avatarManager = $avatarManager;
29
    }
30
31
    /**
32
     * @param Request $request
33
     * @return Response
34
     * @throws Exception
35
     * @throws FilesystemException
36
     */
37
    public function upload(Request $request): Response
38
    {
39
        /** @var User $user */
40
        $user = $this->getUser();
41
        $data = json_decode($request->getContent(), true);
42
        $file = $data['file'];
43
        $fp1 = fopen($file, 'r');
44
        $meta = stream_get_meta_data($fp1);
45
        $mimeType = $meta['mediatype'];
46
47
        $data = explode(',', $file);
48
49
        if (!in_array($mimeType, $this->avatarManager->getAllowedMimeType())) {
50
            return new JsonResponse([
51
                'message' => $this->translator->trans('avatar.extension_not_allowed'),
52
            ],
53
            400
54
            );
55
        }
56
57
        // Set filename
58
        $filename = $user->getId() . '_' . uniqid() . '.' . $this->avatarManager->getExtension($mimeType);
59
60
        $this->avatarManager->write($filename, base64_decode($data[1]));
61
62
        // Save avatar
63
        $user->setAvatar($filename);
64
        $this->em->flush();
65
66
        return new JsonResponse([
67
            'message' => $this->translator->trans('avatar.success'),
68
        ], 200);
69
    }
70
71
    /**
72
     * @param User $user
73
     * @return StreamedResponse
74
     * @throws FilesystemException
75
     */
76
    public function download(User $user): StreamedResponse
77
    {
78
        return $this->avatarManager->read($user->getAvatar());
79
    }
80
}
81