LogHelper   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 1
dl 0
loc 41
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B ftruncatestart() 0 29 6
1
<?php
2
3
namespace Padosoft\Io;
4
5
/**
6
 * Class LogHelper
7
 * @package Padosoft\Io
8
 */
9
class LogHelper
10
{
11
    /**
12
     * Truncates a file to a given length but keep the end.
13
     * Takes the filepointer, handle, and truncates the file to length, size.
14
     * It will not just cut it but search for a newline so you avoid corrupting your csv or logfiles.
15
     * @param string $filename
16
     * @param $maxfilesize in byte
17
     * @return bool
18
     * @see http://php.net/manual/en/function.ftruncate.php#103591
19
     */
20
    public static function ftruncatestart(string $filename, $maxfilesize) : bool
21
    {
22
        if (!FileHelper::fileExistsSafe($filename)) {
23
            return false;
24
        }
25
        $size = filesize($filename);
26
        if ($size === false || ($size < $maxfilesize * 1.0)) {
27
            return false;
28
        }
29
        $maxfilesize = $maxfilesize * 0.5; //we don't want to do it too often...
30
        $fh = fopen($filename, "r+");
31
        if ($fh === false) {
32
            return false;
33
        }
34
        ftell($fh);
35
        fseek($fh, -$maxfilesize, SEEK_END);
36
        $drop = fgets($fh);
37
        $offset = ftell($fh);
38
        for ($x = 0; $x < $maxfilesize; $x++) {
39
            fseek($fh, $x + $offset);
40
            $c = fgetc($fh);
41
            fseek($fh, $x);
42
            fwrite($fh, $c);
43
        }
44
        ftruncate($fh, $maxfilesize - strlen($drop));
45
        fclose($fh);
46
47
        return true;
48
    }
49
}
50