diff --git a/CHANGELOG.md b/CHANGELOG.md index 6dc867a2..47734383 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/src/PhpSpreadsheet/Reader/Csv.php b/src/PhpSpreadsheet/Reader/Csv.php index c31a37f5..76bac01a 100644 --- a/src/PhpSpreadsheet/Reader/Csv.php +++ b/src/PhpSpreadsheet/Reader/Csv.php @@ -195,11 +195,11 @@ class Csv extends BaseReader } $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) @@ -476,6 +476,13 @@ class Csv extends BaseReader fclose($this->fileHandle); - return true; + $type = mime_content_type($pFilename); + $supportedTypes = [ + 'text/csv', + 'text/plain', + 'inode/x-empty', + ]; + + return in_array($type, $supportedTypes, true); } } diff --git a/tests/PhpSpreadsheetTests/Reader/CsvTest.php b/tests/PhpSpreadsheetTests/Reader/CsvTest.php index 003478fa..85f60721 100644 --- a/tests/PhpSpreadsheetTests/Reader/CsvTest.php +++ b/tests/PhpSpreadsheetTests/Reader/CsvTest.php @@ -63,4 +63,30 @@ class CsvTest extends TestCase ], ]; } + + /** + * @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'], + ]; + } } diff --git a/tests/data/Reader/CSV/empty.csv b/tests/data/Reader/CSV/empty.csv new file mode 100644 index 00000000..e69de29b