Skip to content

Commit

Permalink
Add test for MimeTypeFilter.
Browse files Browse the repository at this point in the history
  • Loading branch information
mermshaus committed Mar 26, 2016
1 parent 00b539e commit dda2874
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 9 deletions.
20 changes: 11 additions & 9 deletions src/MimeTypeFilter.php
Expand Up @@ -13,14 +13,17 @@
use Iterator;
use SplFileInfo;

/**
*
*/
final class MimeTypeFilter extends FilterIterator
{
/**
* List of allowed file extensions
* List of allowed MIME types
*
* @var array
*/
protected $whitelist;
private $whitelist;

/**
*
Expand All @@ -30,7 +33,10 @@ final class MimeTypeFilter extends FilterIterator
public function __construct(Iterator $iterator, array $whitelist)
{
parent::__construct($iterator);
$this->whitelist = $whitelist;

// Reformat array to simplify lookup

$this->whitelist = array_flip($whitelist);
}

/**
Expand All @@ -47,15 +53,11 @@ public function accept()
return false;
}

$finfo = finfo_open(\FILEINFO_MIME_TYPE);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$type = finfo_file($finfo, $fileInfo->getPathname());
finfo_close($finfo);

// Only allow MIME types from $whitelist
if (!in_array($type, $this->whitelist)) {
return false;
}

return true;
return (isset($this->whitelist[$type]));
}
}
59 changes: 59 additions & 0 deletions tests/Kaloa/Tests/Filesystem/MimeTypeFilterTest.php
@@ -0,0 +1,59 @@
<?php

/*
* This file is part of the kaloa/filesystem package.
*
* For full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/

namespace Kaloa\Tests\Filesystem;

use Kaloa\Filesystem\MimeTypeFilter;
use PHPUnit_Framework_TestCase;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;

/**
*
*/
class MimeTypeFilterTest extends PHPUnit_Framework_TestCase
{
public function testFilter()
{
$path = __DIR__ . '/test-files';

$whitelist = array(
'text/php',
'text/x-php', // Ubuntu 14.04 (?)
'application/php',
'application/x-php'
);

$iterator = new MimeTypeFilter(
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path)
),
$whitelist
);

$files = iterator_to_array($iterator);

$this->assertEquals(1, count($files));

$whitelist = array(
'image/png'
);

$iterator = new MimeTypeFilter(
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path)
),
$whitelist
);

$files = iterator_to_array($iterator);

$this->assertEquals(0, count($files));
}
}
8 changes: 8 additions & 0 deletions tests/Kaloa/Tests/Filesystem/test-files/hello.php
@@ -0,0 +1,8 @@
<?php

function sayHello()
{
echo "Hello World!\n";
}

sayHello();

0 comments on commit dda2874

Please sign in to comment.