Passed
Push — develop ( cfccb6...0b3512 )
by BENARD
04:54
created

Upload   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 3
eloc 30
dl 0
loc 62
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
A __invoke() 0 32 2
1
<?php
2
3
namespace VideoGamesRecords\CoreBundle\Controller\Team\Avatar;
4
5
use Doctrine\ORM\EntityManagerInterface;
6
use Doctrine\ORM\Exception\ORMException;
7
use League\Flysystem\FilesystemException;
8
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
9
use Symfony\Component\HttpFoundation\JsonResponse;
10
use Symfony\Component\HttpFoundation\Request;
11
use Symfony\Component\HttpFoundation\Response;
12
use Symfony\Contracts\Translation\TranslatorInterface;
13
use VideoGamesRecords\CoreBundle\Manager\AvatarManager;
14
use VideoGamesRecords\CoreBundle\Security\UserProvider;
15
16
class Upload extends AbstractController
17
{
18
    private AvatarManager $avatarManager;
19
    private UserProvider $userProvider;
20
    private EntityManagerInterface $em;
21
    private TranslatorInterface $translator;
22
23
24
    private array $extensions = array(
25
        'image/png' => '.png',
26
        'image/jpeg' => '.jpg',
27
    );
28
29
    public function __construct(
30
        AvatarManager $avatarManager,
31
        UserProvider $userProvider,
32
        EntityManagerInterface $em,
33
        TranslatorInterface $translator
34
    ) {
35
        $this->avatarManager = $avatarManager;
36
        $this->userProvider = $userProvider;
37
        $this->em = $em;
38
        $this->translator = $translator;
39
    }
40
41
    /**
42
     * @param Request $request
43
     * @return Response
44
     * @throws FilesystemException|ORMException
45
     */
46
    public function __invoke(Request $request): Response
47
    {
48
        $team = $this->userProvider->getTeam();
49
50
        $data = json_decode($request->getContent(), true);
51
        $file = $data['file'];
52
        $fp1 = fopen($file, 'r');
53
        $meta = stream_get_meta_data($fp1);
54
        $mimeType = $meta['mediatype'];
55
56
        $data = explode(',', $file);
57
58
        if (!array_key_exists($meta['mediatype'], $this->extensions)) {
59
            return new JsonResponse([
60
                'message' => $this->translator->trans('avatar.extension_not_allowed'),
61
            ],
62
            400
63
            );
64
        }
65
66
        // Set filename
67
        $filename = $team->getId() . '_' . uniqid() . '.' . $this->avatarManager->getExtension($mimeType);
68
69
        $this->avatarManager->write($filename, base64_decode($data[1]));
70
71
        // Save avatar
72
        $team->setLogo($filename);
73
        $this->em->flush();
74
75
        return new JsonResponse([
76
            'message' => $this->translator->trans('avatar.success'),
77
        ], 200);
78
    }
79
}
80