Passed
Push — main ( 574ec4...ea1a90 )
by Sammy
01:36
created

TextFile::identical()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 18
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 7
nc 3
nop 3
dl 0
loc 18
rs 9.6111
c 0
b 0
f 0
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
        $filepointer_1 = $file_1->open();
39
        $filepointer_2 = $file_2->open();
40
41
        $identical = true;
42
        while (!feof($filepointer_1) && $identical === true) {
43
            $chunk_1 = fread($filepointer_1, $read_length);
44
            $chunk_2 = fread($filepointer_2, $read_length);
45
46
            if ($chunk_1 === false || $chunk_2 === false) {
47
                $file_1->close();
48
                $file_2->close();
49
                throw \RuntimeException('fread returned false');
0 ignored issues
show
Bug introduced by
The function RuntimeException was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

49
                throw /** @scrutinizer ignore-call */ \RuntimeException('fread returned false');
Loading history...
50
            }
51
52
            if ($chunk_1 !== $chunk_2) {
53
                $identical = false;
54
            }
55
        }
56
57
        $file_1->close();
58
        $file_2->close();
59
60
        return $identical;
61
    }
62
63
64
    public function __toString()
65
    {
66
        return file_get_contents($this->filepath());
67
    }
68
}
69