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