Passed
Push — main ( 50e9df...8b2649 )
by Sammy
01:43
created

TextFile::compare_content()   A

Complexity

Conditions 6
Paths 4

Size

Total Lines 28
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 6
eloc 16
nc 4
nop 3
dl 0
loc 28
rs 9.1111
c 1
b 0
f 1
1
<?php
2
3
namespace HexMakina\LocalFS\Text;
4
5
class TextFile extends \HexMakina\LocalFS\File
6
{
7
8
    public static function identical($filepath_1, $filepath_2, $read_length = 8192)
9
    {
10
      //** TEST FOR EXISTENCE
11
        if (!file_exists($filepath_1) || !file_exists($filepath_2)) {
12
            throw new \Exception('file_exists false');
13
        }
14
15
      //** TEST FOR SYMLINK
16
        $filepath_1 = self::resolve_symlink($filepath_1);
17
        $filepath_2 = self::resolve_symlink($filepath_2);
18
19
      //** TEST FOR IDENTICAL TYPE AND SIZE
20
        if (filetype($filepath_1) !== filetype($filepath_2) || filesize($filepath_1) !== filesize($filepath_2)) {
21
            return false;
22
        }
23
24
      //** TEST FOR IDENTICAL CONTENT
25
        return self::compare_content($filepath_1, $filepath_2, $read_length);
26
    }
27
28
    public static function compare_content($filepath_1, $filepath_2, $read_length = 8192) : bool
29
    {
30
31
        $file_1 = new TextFile($filepath_1, 'r');
32
        $file_2 = new TextFile($filepath_2, 'r');
33
34
        if ($file_1->size() !== $file_2->size()) {
35
            return false;
36
        }
37
38
        $identical = true;
39
        while (!feof($file_1->pointer()) && $identical === true) {
40
            $chunk_1 = fread($file_1->pointer(), $read_length);
41
            $chunk_2 = fread($file_2->pointer(), $read_length);
42
43
            if ($chunk_1 === false || $chunk_2 === false) {
44
                $file_1->close();
45
                $file_2->close();
46
                throw new \RuntimeException('fread failure');
47
            }
48
49
            $identical = $chunk_1 === $chunk_2; // must be last loop line
50
        }
51
52
        $file_1->close();
53
        $file_2->close();
54
55
        return $identical;
56
    }
57
58
59
    public function __toString()
60
    {
61
        return file_get_contents($this->filepath());
62
    }
63
}
64