Skip to content

Commit

Permalink
Check for MIME type to know if CSV reader can read a file
Browse files Browse the repository at this point in the history
CSV reader used to accept any file without any kind of check. That made
users incorrectly believe that things were ok, even though there is no
way for CSV reader to read anything else that plain text files.

Fixes #167
  • Loading branch information
PowerKiKi committed Feb 5, 2018
1 parent 13a10e4 commit e31878c
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 6 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
### Fixed

- Avoid potentially unsupported PSR-16 cache keys - [#354](https://github.com/PHPOffice/PhpSpreadsheet/issues/354)
- Check for MIME type to know if CSV reader can read a file - [#167](https://github.com/PHPOffice/PhpSpreadsheet/issues/167)

## [1.1.0] - 2018-01-28

Expand Down
19 changes: 13 additions & 6 deletions src/PhpSpreadsheet/Reader/Csv.php
Original file line number Diff line number Diff line change
Expand Up @@ -195,11 +195,11 @@ protected function inferSeparator()
}

$meanSquareDeviations[$delimiter] = array_reduce(
$series,
function ($sum, $value) use ($median) {
return $sum + pow($value - $median, 2);
}
) / count($series);
$series,
function ($sum, $value) use ($median) {
return $sum + pow($value - $median, 2);
}
) / count($series);
}

// ... and pick the delimiter with the smallest mean square deviation (in case of ties, the order in potentialDelimiters is respected)
Expand Down Expand Up @@ -476,6 +476,13 @@ public function canRead($pFilename)

fclose($this->fileHandle);

return true;
$type = mime_content_type($pFilename);
$supportedTypes = [
'text/csv',
'text/plain',
'inode/x-empty',
];

return in_array($type, $supportedTypes, true);
}
}
26 changes: 26 additions & 0 deletions tests/PhpSpreadsheetTests/Reader/CsvTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,30 @@ public function providerDelimiterDetection()
],
];
}

/**
* @dataProvider providerCanLoad
*
* @param bool $expected
* @param string $filename
*/
public function testCanLoad($expected, $filename)
{
$reader = new Csv();
self::assertSame($expected, $reader->canRead($filename));
}

public function providerCanLoad()
{
return [
[false, 'data/Reader/Ods/data.ods'],
[false, 'data/Reader/Xml/WithoutStyle.xml'],
[true, 'data/Reader/CSV/enclosure.csv'],
[true, 'data/Reader/CSV/semicolon_separated.csv'],
[true, 'data/Reader/HTML/csv_with_angle_bracket.csv'],
[true, 'data/Reader/CSV/empty.csv'],
[true, '../samples/Reader/sampleData/example1.csv'],
[true, '../samples/Reader/sampleData/example2.csv'],
];
}
}
Empty file added tests/data/Reader/CSV/empty.csv
Empty file.

0 comments on commit e31878c

Please sign in to comment.