Skip to content

Commit

Permalink
Reject invalid separator
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastianbergmann committed Mar 27, 2023
1 parent d35f462 commit a17b0d1
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/Parser.php
Expand Up @@ -10,6 +10,7 @@
namespace SebastianBergmann\CsvParser;

use function is_array;
use function strlen;
use Generator;
use RuntimeException;
use SplFileObject;
Expand Down Expand Up @@ -42,8 +43,15 @@ public function parse(string $filename, Schema $schema): Generator
return $this->generator($file, $schema);
}

/**
* @throws InvalidSeparatorException
*/
public function setSeparator(string $separator): void
{
if (strlen($separator) !== 1) {
throw new InvalidSeparatorException;
}

$this->separator = $separator;
}

Expand Down
20 changes: 20 additions & 0 deletions src/exception/InvalidSeparatorException.php
@@ -0,0 +1,20 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/csv-parser.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\CsvParser;

use InvalidArgumentException;

final class InvalidSeparatorException extends InvalidArgumentException implements Exception
{
public function __construct()
{
parent::__construct('Separator must be a one single-byte character');
}
}
11 changes: 11 additions & 0 deletions tests/unit/ParserTest.php
Expand Up @@ -17,6 +17,7 @@
use PHPUnit\Framework\TestCase;

#[CoversClass(Parser::class)]
#[CoversClass(InvalidSeparatorException::class)]
#[UsesClass(Schema::class)]
#[UsesClass(ColumnDefinition::class)]
#[UsesClass(Type::class)]
Expand Down Expand Up @@ -156,4 +157,14 @@ public function test_Cannot_read_from_CSV_file_that_does_not_exist(): void

(new Parser)->parse('does_not_exist.csv', Schema::from());
}

public function testRejectsInvalidSeparator(): void
{
$parser = new Parser;

$this->expectException(InvalidSeparatorException::class);
$this->expectExceptionMessage('Separator must be a one single-byte character');

$parser->setSeparator('..');
}
}

0 comments on commit a17b0d1

Please sign in to comment.