Passed
Push — master ( 1c18d9...949a29 )
by
unknown
13:44 queued 13s
created

RemoveOldCSPViolationsTask::getDescription()   B

Complexity

Conditions 6
Paths 12

Size

Total Lines 37
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 21
c 1
b 0
f 0
nc 12
nop 0
dl 0
loc 37
rs 8.9617
1
<?php
2
namespace Signify\Tasks;
3
4
use DateInterval;
5
use Signify\Jobs\RemoveOldCSPViolationsJob;
6
use SilverStripe\Core\Config\Config;
7
use SilverStripe\Dev\BuildTask;
8
use Symbiote\QueuedJobs\Services\QueuedJobService;
9
10
class RemoveOldCSPViolationsTask extends BuildTask
11
{
12
    protected $title = 'Remove old CSP violation reports';
13
14
    /**
15
     * {@inheritDoc}
16
     * @see \SilverStripe\Dev\BuildTask::run()
17
     */
18
    public function run($request)
19
    {
20
        $deletionJob = new RemoveOldCSPViolationsJob();
21
22
        $jobId = singleton(QueuedJobService::class)->queueJob($deletionJob);
23
24
        print "Job queued with ID $jobId\n";
25
    }
26
27
    /**
28
     * {@inheritDoc}
29
     * @see \SilverStripe\Dev\BuildTask::getDescription()
30
     */
31
    public function getDescription()
32
    {
33
        // Map DateInterval fields to text names. Order is significant.
34
        static $parts = [
35
            'y' => 'year',
36
            'm' => 'month',
37
            'd' => 'day',
38
            'h' => 'hour',
39
            'i' => 'minute',
40
            's' => 'second',
41
            'f' => 'microsecond',
42
        ];
43
44
        $retention = Config::inst()->get(RemoveOldCSPViolationsJob::class, 'retention_period');
45
        $retention = new DateInterval($retention);
46
47
        $duration_parts = [];
48
        foreach ($parts as $field => $label) {
49
            if ($retention->$field != 0) {
50
                // Microseconds are a fraction of a second. Everything else is defined in terms of itself.
51
                $value = $field === 'f' ? round($retention->$field * 1000000.0, 0, PHP_ROUND_HALF_UP) : $retention->$field;
52
53
                // Cheap and nasty pluralisation.
54
                $duration_parts[] = $value . ' ' . $label . ($value === 1 ? '' : 's');
55
            }
56
        }
57
58
        // Convert to string e.g. "12 hours, 30 minutes and 10 seconds"
59
        if (count($duration_parts) > 1) {
60
            $last = array_pop($duration_parts);
61
            $duration_string = implode(', ', $duration_parts) . ' and ' . $last;
62
        }
63
        else {
64
            $duration_string = reset($duration_parts);
65
        }
66
67
        return 'CSP reports that have not been created or modified within the last ' . $duration_string . ' will be removed.';
68
    }
69
70
    public function isEnabled()
71
    {
72
        return parent::isEnabled() && class_exists(QueuedJobService::class);
73
    }
74
75
}