Skip to content

Commit

Permalink
Validator: add support for value objects (#202)
Browse files Browse the repository at this point in the history
  • Loading branch information
xificurk authored and dg committed Feb 28, 2019
1 parent 7d2226b commit 0a10145
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/Forms/Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ public static function validateSubmitted(Controls\SubmitButton $control): bool
*/
public static function validateEmail(IControl $control): bool
{
return Validators::isEmail($control->getValue());
return Validators::isEmail((string) $control->getValue());
}


Expand All @@ -234,10 +234,12 @@ public static function validateEmail(IControl $control): bool
*/
public static function validateUrl(IControl $control): bool
{
if (Validators::isUrl($value = $control->getValue())) {
$value = (string) $control->getValue();
if (Validators::isUrl($value)) {
return true;

} elseif (Validators::isUrl($value = "http://$value")) {
}
$value = "http://$value";
if (Validators::isUrl($value)) {
$control->setValue($value);
return true;
}
Expand Down
60 changes: 60 additions & 0 deletions tests/Forms/Controls.TextInput.valueObjectValidation.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

/**
* Test: Nette\Forms\Controls\TextInput.
*/

declare(strict_types=1);

use Nette\Forms\Form;
use Tester\Assert;


require __DIR__ . '/../bootstrap.php';


class ValueObject
{
/** @var string */
private $value;


public function __construct(string $value)
{
$this->value = $value;
}


public function __toString(): string
{
return $this->value;
}
}


test(function (): void { // e-mail
$form = new Form;
$input = $form->addEmail('email');

$input->setValue(new ValueObject('[email protected]'));
Assert::type(ValueObject::class, $input->getValue());
$form->validate();
Assert::same([], $form->getErrors());
});


test(function (): void { // URL
$form = new Form;
$input = $form->addText('url')
->addRule(Form::URL);

$input->setValue(new ValueObject('https://example.com'));
Assert::type(ValueObject::class, $input->getValue());
$form->validate();
Assert::same([], $form->getErrors());

$input->setValue(new ValueObject('example.com'));
Assert::type(ValueObject::class, $input->getValue());
$form->validate();
Assert::same([], $form->getErrors());
});

0 comments on commit 0a10145

Please sign in to comment.