Skip to content

Commit d8f4aa0

Browse files
committed
[FEATURE] Add original file name to SanitizeFileNameEvent
Resolves: TYPO3-Documentation/Changelog-To-Doc#1524 Releases: main
1 parent 3101c97 commit d8f4aa0

File tree

2 files changed

+47
-8
lines changed

2 files changed

+47
-8
lines changed

Documentation/ApiOverview/Events/Events/Core/Resource/SanitizeFileNameEvent.rst

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,28 @@ SanitizeFileNameEvent
77
=====================
88

99
The PSR-14 event :php:`\TYPO3\CMS\Core\Resource\Event\SanitizeFileNameEvent` is
10-
fired once an index was just added to the database (= indexed), so it is possible
11-
to modify the file name, and name the files according to naming conventions of a
12-
specific project.
10+
fired when a file name is sanitized. Event listeners can modify the sanitized
11+
file name in order to apply custom naming conventions (for example, replacing
12+
whitespace with hyphens for SEO-friendly file names).
1313

14-
Example
15-
=======
14+
.. _SanitizeFileNameEvent-example:
1615

17-
.. include:: /_includes/EventsContributeNote.rst.txt
16+
Example: Sanitize a file name with hyphens instead of underscores
17+
=================================================================
1818

19-
API
20-
===
19+
The following listener uses the original (unsanitized) file name to replace
20+
whitespace with hyphens and assigns the result as sanitized file name.
21+
22+
.. literalinclude:: _SanitizeFileNameEvent/_SeoFriendlyFileNameListener.php
23+
:caption: EXT:my_extension/Classes/EventListener/SeoFriendlyFileNameListener.php
24+
25+
.. _SanitizeFileNameEvent-api:
26+
27+
SanitizeFileNameEvent API
28+
=========================
29+
30+
.. versionchanged:: 14.0
31+
The original (unsanitized) file name can now be retrieved using
32+
:php:`SanitizeFileNameEvent::getOriginalFileName()`.
2133

2234
.. include:: /CodeSnippets/Events/Core/Resource/SanitizeFileNameEvent.rst.txt
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace MyVendor\MyExtension\EventListener;
6+
7+
use TYPO3\CMS\Core\Attribute\AsEventListener;
8+
use TYPO3\CMS\Core\Resource\Event\SanitizeFileNameEvent;
9+
10+
#[AsEventListener(
11+
identifier: 'my-extension/seo-friendly-filename',
12+
)]
13+
final readonly class SeoFriendlyFileNameListener
14+
{
15+
public function __invoke(SanitizeFileNameEvent $event): void
16+
{
17+
$originalFileName = $event->getOriginalFileName();
18+
19+
if (!str_contains($originalFileName, ' ')) {
20+
return;
21+
}
22+
// Apply custom logic based on the original file name
23+
$customFileName = str_replace(' ', '-', $originalFileName);
24+
25+
$event->setFileName($customFileName);
26+
}
27+
}

0 commit comments

Comments
 (0)