88
99namespace OCA \Text \Listeners ;
1010
11+ use Exception ;
1112use OCA \Text \Service \AttachmentService ;
13+ use OCA \Text \Service \DocumentService ;
1214use OCP \EventDispatcher \Event ;
1315use OCP \EventDispatcher \IEventListener ;
1416use OCP \Files \Events \Node \BeforeNodeRenamedEvent ;
1517use OCP \Files \File ;
18+ use Psr \Log \LoggerInterface ;
1619
1720/**
1821 * @template-implements IEventListener<Event|BeforeNodeRenamedEvent>
1922 */
2023class BeforeNodeRenamedListener implements IEventListener {
21- private AttachmentService $ attachmentService ;
22-
23- public function __construct ( AttachmentService $ attachmentService ) {
24- $ this -> attachmentService = $ attachmentService ;
24+ public function __construct (
25+ private readonly AttachmentService $ attachmentService ,
26+ private readonly DocumentService $ documentService ,
27+ private readonly LoggerInterface $ logger ) {
2528 }
2629
2730 public function handle (Event $ event ): void {
@@ -30,10 +33,24 @@ public function handle(Event $event): void {
3033 }
3134 $ source = $ event ->getSource ();
3235 $ target = $ event ->getTarget ();
33- if ($ source instanceof File
34- && $ source ->getMimeType () === 'text/markdown '
35- && $ target instanceof File
36- ) {
36+
37+ if (!($ source instanceof File && $ target instanceof File)) {
38+ return ;
39+ }
40+
41+ $ sourceIsMarkdown = $ source ->getMimeType () === 'text/markdown ' ;
42+ $ targetIsMarkdown = pathinfo ($ target ->getPath (), PATHINFO_EXTENSION ) === 'md ' ; // NonExistingFile has no `getMimetype()`
43+
44+ // Reset document state if mimetype changes from/to markdown as this means another editor is loaded
45+ if ($ sourceIsMarkdown xor $ targetIsMarkdown ) {
46+ try {
47+ $ this ->documentService ->resetDocument ($ source ->getId (), true );
48+ } catch (Exception $ e ) {
49+ $ this ->logger ->error ($ e ->getMessage (), ['exception ' => $ e ]);
50+ }
51+ }
52+
53+ if ($ sourceIsMarkdown ) {
3754 $ this ->attachmentService ->moveAttachments ($ source , $ target );
3855 }
3956 }
0 commit comments