Skip to content

Commit

Permalink
Merge pull request #62 from ragulka/use-str-getcsv
Browse files Browse the repository at this point in the history
use str_getcsv instead of explode in Delimited rule
  • Loading branch information
freekmurze authored May 9, 2023
2 parents 43a768d + 4178cb7 commit 5819eb5
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/Rules/Delimited.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ class Delimited implements Rule
/** @var bool */
protected $trimItems = true;

protected bool $asCsv = false;

/** @var string */
protected $validationMessageWord = 'item';

Expand Down Expand Up @@ -79,13 +81,20 @@ public function validationMessageWord(string $word)
return $this;
}

public function asCsv(): static
{
$this->asCsv = true;

return $this;
}

public function passes($attribute, $value)
{
if ($this->trimItems) {
$value = trim($value);
}

$items = collect(explode($this->separatedBy, $value))
$items = collect($this->asCsv ? str_getcsv($value, $this->separatedBy) : explode($this->separatedBy, $value))
->filter(function ($item) {
return strlen((string) $item) > 0;
});
Expand Down
9 changes: 9 additions & 0 deletions tests/Rules/DelimitedTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,15 @@ public function it_can_skip_trimming_items()
$this->assertRuleFails('[email protected] , [email protected]');
}

/** @test */
public function it_can_treat_input_as_csv()
{
$rule = (new Delimited('string|min:5'))->asCsv();

$this->assertTrue($rule->passes('attribute', '"Doe, John", "Doe, Jane"'));
$this->assertFalse($rule->passes('attribute', '"Doe", "Jane"'));
}

/** @test */
public function it_can_accept_a_rule_as_an_array()
{
Expand Down

0 comments on commit 5819eb5

Please sign in to comment.