RotativeProcessor::rotate()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 4
eloc 9
c 2
b 0
f 0
nc 3
nop 1
dl 0
loc 19
rs 9.9666
1
<?php
2
3
namespace Cesargb\Log\Processors;
4
5
class RotativeProcessor extends AbstractProcessor
6
{
7
    private int $maxFiles = 366;
8
9
    /**
10
     * Log files are rotated count times before being removed.
11
     */
12
    public function files(int $count): self
13
    {
14
        $this->maxFiles = $count;
15
16
        return $this;
17
    }
18
19
    public function handler(string $filename): ?string
20
    {
21
        $filenameTarget = "{$this->filenameSource}.1";
22
23
        $this->rotate();
24
25
        rename($filename, $filenameTarget);
26
27
        return $this->processed($filenameTarget);
28
    }
29
30
    private function rotate(int $number = 1): string
31
    {
32
        $filenameTarget = "{$this->filenameSource}.{$number}{$this->extension}";
33
34
        if (!file_exists($filenameTarget)) {
35
            return $filenameTarget;
36
        }
37
38
        if ($this->maxFiles > 0 && $number >= $this->maxFiles) {
39
            unlink($filenameTarget);
40
41
            return $filenameTarget;
42
        }
43
44
        $nextFilename = $this->rotate($number + 1);
45
46
        rename($filenameTarget, $nextFilename);
47
48
        return $filenameTarget;
49
    }
50
}
51