1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ProjetNormandie\UserBundle\Controller\Avatar; |
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\Request; |
13
|
|
|
use Symfony\Component\HttpFoundation\Response; |
14
|
|
|
use Symfony\Contracts\Translation\TranslatorInterface; |
15
|
|
|
|
16
|
|
|
class Upload extends AbstractController |
17
|
|
|
{ |
18
|
|
|
public function __construct( |
19
|
|
|
private readonly TranslatorInterface $translator, |
20
|
|
|
private readonly EntityManagerInterface $em, |
21
|
|
|
private readonly AvatarManager $avatarManager |
22
|
|
|
) { |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @param Request $request |
27
|
|
|
* @return Response |
28
|
|
|
* @throws Exception |
29
|
|
|
* @throws FilesystemException |
30
|
|
|
*/ |
31
|
|
|
public function __invoke(Request $request): Response |
32
|
|
|
{ |
33
|
|
|
/** @var User $user */ |
34
|
|
|
$user = $this->getUser(); |
35
|
|
|
$data = json_decode($request->getContent(), true); |
36
|
|
|
$file = $data['imageData']; |
37
|
|
|
$fp1 = fopen($file, 'r'); |
38
|
|
|
$meta = stream_get_meta_data($fp1); |
39
|
|
|
$mimeType = $meta['mediatype']; |
40
|
|
|
|
41
|
|
|
$data = explode(',', $file); |
42
|
|
|
|
43
|
|
|
if (!in_array($mimeType, $this->avatarManager->getAllowedMimeType())) { |
44
|
|
|
return new JsonResponse( |
45
|
|
|
[ |
46
|
|
|
'message' => $this->translator->trans( |
47
|
|
|
'avatar_upload.extension_not_allowed', |
48
|
|
|
[], |
49
|
|
|
'PnUser', |
50
|
|
|
$user->getLanguage() |
51
|
|
|
), |
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(['success' => true]); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|