File size: 1,550 Bytes
d2897cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php

namespace Mautic\ReportBundle\Model;

use Mautic\ReportBundle\Scheduler\Model\FileHandler;

class ReportCleanup
{
    public const KEEP_FILE_DAYS = 7;

    public function __construct(private FileHandler $fileHandler)
    {
    }

    public function cleanup(int $reportId): void
    {
        if ($this->shouldBeDeleted($this->fileHandler->getPathToCompressedCsvFileForReportId($reportId))) {
            $this->fileHandler->deleteCompressedCsvFileForReportId($reportId);
        }
    }

    /**
     * Deletes files older than KEEP_FILE_DAYS.
     */
    public function cleanupAll(): void
    {
        $reportDirectory = $this->fileHandler->getCompressedCsvFileForReportDir();

        if (!file_exists($reportDirectory)) {
            return;
        }

        $files = array_diff(scandir($reportDirectory), ['.', '..']);

        foreach ($files as $file) {
            $filePath = $reportDirectory.'/'.$file;
            if (is_dir($filePath)) {
                continue;
            }

            if ($this->shouldBeDeleted($filePath)) {
                $this->fileHandler->delete($filePath);
            }
        }
    }

    private function shouldBeDeleted(string $filePath): bool
    {
        if (!file_exists($filePath)) {
            return false;
        }

        $created = new \DateTime(date('Y-m-d', filemtime($filePath)));
        $now     = new \DateTime();
        $days    = $created->diff($now)->days;

        if ($days > self::KEEP_FILE_DAYS) {
            return true;
        }

        return false;
    }
}