1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* For licensing terms, see /license.txt */ |
6
|
|
|
|
7
|
|
|
namespace Chamilo\CoreBundle\Component\VichUploader; |
8
|
|
|
|
9
|
|
|
use Chamilo\CoreBundle\Entity\Asset; |
10
|
|
|
use InvalidArgumentException; |
11
|
|
|
use Symfony\Component\HttpFoundation\RequestStack; |
12
|
|
|
use Symfony\Contracts\Translation\TranslatorInterface; |
13
|
|
|
use Vich\UploaderBundle\Mapping\PropertyMapping; |
14
|
|
|
use Vich\UploaderBundle\Naming\NamerInterface; |
15
|
|
|
|
16
|
|
|
use const PATHINFO_EXTENSION; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @implements NamerInterface<Asset> |
20
|
|
|
*/ |
21
|
|
|
class AssetFileNameNamer implements NamerInterface |
22
|
|
|
{ |
23
|
|
|
private RequestStack $requestStack; |
24
|
|
|
private TranslatorInterface $translator; |
25
|
|
|
|
26
|
|
|
public function __construct(RequestStack $requestStack, TranslatorInterface $translator) |
27
|
|
|
{ |
28
|
|
|
$this->requestStack = $requestStack; |
29
|
|
|
$this->translator = $translator; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public function name($object, PropertyMapping $mapping): string |
33
|
|
|
{ |
34
|
|
|
if (!$object instanceof Asset) { |
35
|
|
|
throw new InvalidArgumentException('Expected object of type Asset.'); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
$category = $object->getCategory(); |
39
|
|
|
|
40
|
|
|
if (\in_array($category, [Asset::TEMPLATE, Asset::SYSTEM_TEMPLATE])) { |
41
|
|
|
$request = $this->requestStack->getCurrentRequest(); |
42
|
|
|
if ($request) { |
43
|
|
|
$templateId = $object->getId(); |
44
|
|
|
$templateTitle = $request->get('title', 'default-title'); |
45
|
|
|
$titleSlug = $this->slugify($templateTitle); |
46
|
|
|
$extension = pathinfo($mapping->getFileName($object), PATHINFO_EXTENSION); |
47
|
|
|
|
48
|
|
|
return \sprintf('%s-%s.%s', $templateId, $titleSlug, $extension); |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
return $mapping->getFileName($object); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
private function slugify(string $text): string |
56
|
|
|
{ |
57
|
|
|
return strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $text), '-')); |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|