Skip to content

Commit ac5287b

Browse files
committed
Detect binary file by NULL byte
1 parent ba22bb2 commit ac5287b

File tree

2 files changed

+25
-5
lines changed

2 files changed

+25
-5
lines changed

src/Gitonomy/Git/Blob.php

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919
*/
2020
class Blob
2121
{
22+
private const FIRST_FEW_BYTES = 8000;
23+
2224
/**
2325
* @var Repository
2426
*/
@@ -39,6 +41,11 @@ class Blob
3941
*/
4042
protected $mimetype;
4143

44+
/**
45+
* @var bool
46+
*/
47+
protected $text;
48+
4249
/**
4350
* @param Repository $repository Repository where the blob is located
4451
* @param string $hash Hash of the blob
@@ -103,6 +110,10 @@ public function isBinary()
103110
*/
104111
public function isText()
105112
{
106-
return (bool) preg_match('#^text/|^application/xml#', $this->getMimetype());
113+
if (null === $this->text) {
114+
$this->text = !str_contains(substr($this->getContent(), 0, self::FIRST_FEW_BYTES), chr(0));
115+
}
116+
117+
return $this->text;
107118
}
108119
}

tests/Gitonomy/Git/Tests/BlobTest.php

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,11 @@ public function getReadmeBlob($repository)
2323
return $repository->getCommit(self::LONGFILE_COMMIT)->getTree()->resolvePath('README.md');
2424
}
2525

26+
public function getImageBlob($repository)
27+
{
28+
return $repository->getCommit(self::LONGFILE_COMMIT)->getTree()->resolvePath('image.jpg');
29+
}
30+
2631
/**
2732
* @dataProvider provideFoobar
2833
*/
@@ -67,16 +72,20 @@ public function testGetMimetype($repository)
6772
*/
6873
public function testIsText($repository)
6974
{
70-
$blob = $this->getReadmeBlob($repository);
71-
$this->assertTrue($blob->isText());
75+
$readmeBlob = $this->getReadmeBlob($repository);
76+
$this->assertTrue($readmeBlob->isText());
77+
$imageBlob = $this->getImageBlob($repository);
78+
$this->assertFalse($imageBlob->isText());
7279
}
7380

7481
/**
7582
* @dataProvider provideFoobar
7683
*/
7784
public function testIsBinary($repository)
7885
{
79-
$blob = $this->getReadmeBlob($repository);
80-
$this->assertFalse($blob->isBinary());
86+
$readmeBlob = $this->getReadmeBlob($repository);
87+
$this->assertFalse($readmeBlob->isBinary());
88+
$imageBlob = $this->getImageBlob($repository);
89+
$this->assertTrue($imageBlob->isBinary());
8190
}
8291
}

0 commit comments

Comments
 (0)