|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
/* For licensing terms, see /license.txt */ |
|
6
|
|
|
|
|
7
|
|
|
namespace Chamilo\CoreBundle\Controller\Api; |
|
8
|
|
|
|
|
9
|
|
|
use Chamilo\CoreBundle\Entity\Asset; |
|
10
|
|
|
use Chamilo\CourseBundle\Entity\CLink; |
|
11
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
|
12
|
|
|
use Exception; |
|
13
|
|
|
use Symfony\Component\HttpFoundation\Request; |
|
14
|
|
|
use Symfony\Component\HttpFoundation\Response; |
|
15
|
|
|
|
|
16
|
|
|
class CLinkImageController |
|
17
|
|
|
{ |
|
18
|
|
|
private EntityManagerInterface $entityManager; |
|
19
|
|
|
|
|
20
|
|
|
public function __construct(EntityManagerInterface $entityManager) |
|
21
|
|
|
{ |
|
22
|
|
|
$this->entityManager = $entityManager; |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
public function __invoke(CLink $link, Request $request): Response |
|
26
|
|
|
{ |
|
27
|
|
|
$removeImage = $request->request->getBoolean('removeImage', false); |
|
28
|
|
|
$file = $request->files->get('customImage'); |
|
29
|
|
|
|
|
30
|
|
|
if ($removeImage && $link->getCustomImage()) { |
|
31
|
|
|
$this->entityManager->remove($link->getCustomImage()); |
|
32
|
|
|
$link->setCustomImage(null); |
|
33
|
|
|
$this->entityManager->persist($link); |
|
34
|
|
|
$this->entityManager->flush(); |
|
35
|
|
|
|
|
36
|
|
|
if (!$file) { |
|
37
|
|
|
return new Response('Image removed successfully', Response::HTTP_OK); |
|
38
|
|
|
} |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
if (!$file || !$file->isValid()) { |
|
42
|
|
|
return new Response('Invalid or missing file', Response::HTTP_BAD_REQUEST); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
try { |
|
46
|
|
|
$finalFile = $file; |
|
47
|
|
|
$asset = new Asset(); |
|
48
|
|
|
$asset->setFile($finalFile) |
|
49
|
|
|
->setCategory(Asset::LINK) |
|
50
|
|
|
->setTitle($file->getClientOriginalName()); |
|
51
|
|
|
|
|
52
|
|
|
$this->entityManager->persist($asset); |
|
53
|
|
|
$this->entityManager->flush(); |
|
54
|
|
|
|
|
55
|
|
|
$link->setCustomImage($asset); |
|
56
|
|
|
$this->entityManager->persist($link); |
|
57
|
|
|
$this->entityManager->flush(); |
|
58
|
|
|
|
|
59
|
|
|
return new Response('Image uploaded and linked successfully', Response::HTTP_OK); |
|
60
|
|
|
} catch (Exception $e) { |
|
61
|
|
|
return new Response('Error processing image: '.$e->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR); |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|