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'); |
|
|
|
|
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
|
|
|
|