1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace HexMakina\LocalFS\Text; |
4
|
|
|
|
5
|
|
|
use HexMakina\LocalFS\FileSystem; |
6
|
|
|
|
7
|
|
|
class TextFile extends \HexMakina\LocalFS\File |
8
|
|
|
{ |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* @param int<0, max> $read_length |
12
|
|
|
*/ |
13
|
|
|
public static function identical(string $filepath_1, string $filepath_2, int $read_length = 8192) : bool |
14
|
|
|
{ |
15
|
|
|
//** TEST FOR EXISTENCE |
16
|
|
|
if (!file_exists($filepath_1) || !file_exists($filepath_2)) { |
17
|
|
|
throw new \Exception('file_exists false'); |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
//** TEST FOR SYMLINK |
21
|
|
|
$filepath_1 = FileSystem::resolve_symlink($filepath_1); |
22
|
|
|
$filepath_2 = FileSystem::resolve_symlink($filepath_2); |
23
|
|
|
|
24
|
|
|
//** TEST FOR IDENTICAL TYPE AND SIZE |
25
|
|
|
if (filetype($filepath_1) !== filetype($filepath_2) || filesize($filepath_1) !== filesize($filepath_2)) { |
26
|
|
|
return false; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
//** TEST FOR IDENTICAL CONTENT |
30
|
|
|
return self::compare_content($filepath_1, $filepath_2, $read_length); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @param int<0, max> $read_length |
35
|
|
|
*/ |
36
|
|
|
public static function compare_content(string $filepath_1, string $filepath_2, int $read_length = 8192): bool |
37
|
|
|
{ |
38
|
|
|
|
39
|
|
|
$file_1 = new TextFile($filepath_1, 'r'); |
40
|
|
|
$file_2 = new TextFile($filepath_2, 'r'); |
41
|
|
|
|
42
|
|
|
if ($file_1->size() !== $file_2->size()) { |
43
|
|
|
return false; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
$identical = true; |
47
|
|
|
while (!feof($file_1->pointer()) && $identical === true) { |
48
|
|
|
$chunk_1 = fread($file_1->pointer(), $read_length); |
49
|
|
|
$chunk_2 = fread($file_2->pointer(), $read_length); |
50
|
|
|
|
51
|
|
|
if ($chunk_1 === false || $chunk_2 === false) { |
52
|
|
|
$file_1->close(); |
53
|
|
|
$file_2->close(); |
54
|
|
|
throw new \RuntimeException('fread failure'); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
$identical = $chunk_1 === $chunk_2; // must be last loop line |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
$file_1->close(); |
61
|
|
|
$file_2->close(); |
62
|
|
|
|
63
|
|
|
return $identical; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
|
67
|
|
|
public function __toString() |
68
|
|
|
{ |
69
|
|
|
$ret = file_get_contents($this->path()); |
70
|
|
|
if($ret === false) |
71
|
|
|
$ret = $this->path(); |
72
|
|
|
|
73
|
|
|
return $ret; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|