Skip to content
This repository has been archived by the owner on Apr 1, 2024. It is now read-only.

Added MaxWords validation rule #18

Merged
merged 1 commit into from
Apr 26, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ The following validation rules are currently available:
| Domain | validation.domain | Requires that the given value be a domain e.g. google.com, www.google.com |
| CitizenIdentification | validation.citizen_identification | Requires that the given value be a citizen identification number of USA, UK, France or Brazil (see class for details) |
| WithoutWhitespace | validation.without_whitespace | Requires that the given value not include any whitespace characters |
| MaxWords | validation.max_words | Requires that the given value cannot contains more words than the specified - see class for details |

## Contributing

Expand Down
32 changes: 32 additions & 0 deletions src/Rules/MaxWords.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php declare(strict_types = 1);

namespace Axiom\Rules;

use Axiom\Types\Rule;

class MaxWords extends Rule
{
/**
* Determine if the validation rule passes.
*
**/
public function passes($attribute, $value) : bool
{
return count(preg_split('~[^\p{L}\p{N}\']+~u',$value)) <= $this->parameters[0];
}



/**
* Get the validation error message.
*
**/
public function message() : string
{
return $this->getLocalizedErrorMessage(
'max_words',
'The :attribute cannot be longer than ' . $this->parameters[0] . ' words.'
);
}

}
42 changes: 42 additions & 0 deletions tests/MaxWordsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php declare(strict_types=1);

namespace Axiom\Rules\Tests;

use Axiom\Rules\MaxWords;
use Orchestra\Testbench\TestCase;

class MaxWordsTest extends TestCase
{

/**
* @test
* @dataProvider provideSentences
*/
public function the_max_words_rule_can_be_validated($data)
{
$rule = ['text' => [new MaxWords($data['max_words'])]];
$this->assertEquals($data['passes'], validator(['text' => $data['text']], $rule)->passes());
}

function provideSentences()
{
return [
[
['text' => 'hello world', 'max_words' => 2, 'passes' => true]
],
[
['text' => 'مرحبا بالعالم', 'max_words' => 2, 'passes' => true]
],
[
['text' => 'This sentence contains more than 2 words', 'max_words' => 2, 'passes' => false]
],
[
['text' => 'Three words sentence', 'max_words' => 3, 'passes' => true]
],
[
['text' => 'مرحبا بالعالم من التحقق', 'max_words' => 3, 'passes' => false]
],
];
}

}