Skip to content

Commit 89e43ae

Browse files
[9.x] Adds isEqual to compare file hashes in filesystem (#41586)
* [9.x] Adds `isEqual` to compare file hashes in filesystem. * Changed argument name to the compared target. * Adds method to facade. * formatting Co-authored-by: Taylor Otwell <[email protected]>
1 parent 628d39f commit 89e43ae

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

src/Illuminate/Filesystem/Filesystem.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -499,6 +499,20 @@ public function isWritable($path)
499499
return is_writable($path);
500500
}
501501

502+
/**
503+
* Determine if two files are the same by comparing their hashes.
504+
*
505+
* @param string $firstFile
506+
* @param string $secondFile
507+
* @return bool
508+
*/
509+
public function hasSameHash($firstFile, $secondFile)
510+
{
511+
$hash = @md5_file($firstFile);
512+
513+
return $hash && $hash === @md5_file($secondFile);
514+
}
515+
502516
/**
503517
* Determine if the given path is a file.
504518
*

src/Illuminate/Support/Facades/File.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
* @method static bool deleteDirectory(string $directory, bool $preserve = false)
1616
* @method static bool exists(string $path)
1717
* @method static bool isDirectory(string $directory)
18+
* @method static bool isEqual(string $file, string $compared)
1819
* @method static bool isFile(string $file)
1920
* @method static bool isReadable(string $path)
2021
* @method static bool isWritable(string $path)

tests/Filesystem/FilesystemTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -544,6 +544,21 @@ public function testCopyCopiesFileProperly()
544544
$this->assertEquals($data, file_get_contents(self::$tempDir.'/text/foo2.txt'));
545545
}
546546

547+
public function testHasSameHashChecksFileHashes()
548+
{
549+
$filesystem = new Filesystem;
550+
551+
mkdir(self::$tempDir.'/text');
552+
file_put_contents(self::$tempDir.'/text/foo.txt', 'contents');
553+
file_put_contents(self::$tempDir.'/text/foo2.txt', 'contents');
554+
file_put_contents(self::$tempDir.'/text/foo3.txt', 'invalid');
555+
556+
$this->assertTrue($filesystem->hasSameHash(self::$tempDir.'/text/foo.txt', self::$tempDir.'/text/foo2.txt'));
557+
$this->assertFalse($filesystem->hasSameHash(self::$tempDir.'/text/foo.txt', self::$tempDir.'/text/foo3.txt'));
558+
$this->assertFalse($filesystem->hasSameHash(self::$tempDir.'/text/foo4.txt', self::$tempDir.'/text/foo.txt'));
559+
$this->assertFalse($filesystem->hasSameHash(self::$tempDir.'/text/foo.txt', self::$tempDir.'/text/foo4.txt'));
560+
}
561+
547562
public function testIsFileChecksFilesProperly()
548563
{
549564
$filesystem = new Filesystem;

0 commit comments

Comments
 (0)