RemoveOldCSPViolationsTask::isEnabled()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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