1717use App \Model \Entity \SupplementaryExerciseFile ;
1818use App \Model \Entity \UploadedFile ;
1919use App \Model \Entity \AttachmentFile ;
20+ use App \Model \Repository \Assignments ;
2021use App \Model \Repository \AttachmentFiles ;
2122use App \Model \Repository \Exercises ;
2223use App \Model \Entity \Exercise ;
@@ -37,6 +38,12 @@ class ExerciseFilesPresenter extends BasePresenter
3738 */
3839 public $ exercises ;
3940
41+ /**
42+ * @var Assignments
43+ * @inject
44+ */
45+ public $ assignments ;
46+
4047 /**
4148 * @var UploadedFiles
4249 * @inject
@@ -345,7 +352,37 @@ public function actionDeleteAttachmentFile(string $id, string $fileId)
345352 $ exercise ->removeAttachmentFile ($ file );
346353 $ this ->exercises ->flush ();
347354
348- $ this ->fileStorage ->deleteAttachmentFile ($ file );
355+ $ this ->attachmentFiles ->refresh ($ file );
356+ if ($ file ->getExercises ()->isEmpty ()) {
357+ // file has no attachments to exercises, let's check the assignments
358+ $ isUsed = false ;
359+ foreach ($ file ->getAssignments () as $ assignment ) {
360+ $ group = $ assignment ->getGroup ();
361+ if ($ group && !$ group ->isArchived ()) {
362+ $ isUsed = true ; // only non-archived assignments are considered relevant
363+ break ;
364+ }
365+ }
366+
367+ if (!$ isUsed ) {
368+ if ($ file ->getAssignments ()->isEmpty ()) {
369+ // only if no attachments exists (except for deleted ones)
370+ // remove all links to deleted entities and remove the file record
371+ foreach ($ file ->getExercisesAndIReallyMeanAllOkay () as $ exercise ) {
372+ $ exercise ->removeAttachmentFile ($ file );
373+ $ this ->exercises ->persist ($ exercise , false );
374+ }
375+ foreach ($ file ->getAssignmentsAndIReallyMeanAllOkay () as $ assignment ) {
376+ $ assignment ->removeAttachmentFile ($ file );
377+ $ this ->assignments ->persist ($ assignment , false );
378+ }
379+
380+ $ this ->attachmentFiles ->remove ($ file );
381+ }
382+
383+ $ this ->fileStorage ->deleteAttachmentFile ($ file );
384+ }
385+ }
349386
350387 $ this ->sendSuccessResponse ("OK " );
351388 }
0 commit comments