Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[9.x] Adds isEqual to compare file hashes in filesystem #41586

Merged
merged 4 commits into from
Mar 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/Illuminate/Filesystem/Filesystem.php
Original file line number Diff line number Diff line change
Expand Up @@ -499,6 +499,20 @@ public function isWritable($path)
return is_writable($path);
}

/**
* Determine if two files are the same by comparing their hashes.
*
* @param string $firstFile
* @param string $secondFile
* @return bool
*/
public function hasSameHash($firstFile, $secondFile)
{
$hash = @md5_file($firstFile);

return $hash && $hash === @md5_file($secondFile);
}

/**
* Determine if the given path is a file.
*
Expand Down
1 change: 1 addition & 0 deletions src/Illuminate/Support/Facades/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
* @method static bool deleteDirectory(string $directory, bool $preserve = false)
* @method static bool exists(string $path)
* @method static bool isDirectory(string $directory)
* @method static bool isEqual(string $file, string $compared)
* @method static bool isFile(string $file)
* @method static bool isReadable(string $path)
* @method static bool isWritable(string $path)
Expand Down
15 changes: 15 additions & 0 deletions tests/Filesystem/FilesystemTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,21 @@ public function testCopyCopiesFileProperly()
$this->assertEquals($data, file_get_contents(self::$tempDir.'/text/foo2.txt'));
}

public function testHasSameHashChecksFileHashes()
{
$filesystem = new Filesystem;

mkdir(self::$tempDir.'/text');
file_put_contents(self::$tempDir.'/text/foo.txt', 'contents');
file_put_contents(self::$tempDir.'/text/foo2.txt', 'contents');
file_put_contents(self::$tempDir.'/text/foo3.txt', 'invalid');

$this->assertTrue($filesystem->hasSameHash(self::$tempDir.'/text/foo.txt', self::$tempDir.'/text/foo2.txt'));
$this->assertFalse($filesystem->hasSameHash(self::$tempDir.'/text/foo.txt', self::$tempDir.'/text/foo3.txt'));
$this->assertFalse($filesystem->hasSameHash(self::$tempDir.'/text/foo4.txt', self::$tempDir.'/text/foo.txt'));
$this->assertFalse($filesystem->hasSameHash(self::$tempDir.'/text/foo.txt', self::$tempDir.'/text/foo4.txt'));
}

public function testIsFileChecksFilesProperly()
{
$filesystem = new Filesystem;
Expand Down