Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.6] Required If Rule based on a clousure or boolean value #25066

Merged
merged 8 commits into from
Aug 3, 2018
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
11 changes: 11 additions & 0 deletions src/Illuminate/Validation/Rule.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,15 @@ public static function unique($table, $column = 'NULL')
{
return new Rules\Unique($table, $column);
}

/**
* Get a required_if constraint builder instance.
*
* @param \Closure $callback
* @return \Illuminate\Validation\Rules\RequiredIf
*/
public static function requiredIf($callback)
{
return new Rules\RequiredIf($callback);
}
}
45 changes: 45 additions & 0 deletions src/Illuminate/Validation/Rules/RequiredIf.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

namespace Illuminate\Validation\Rules;

use Closure;

class RequiredIf
{
/**
* The name of the rule.
*/
protected $rule = 'required';

/**
* The condition that validates the attribute.
*
* @var bool|\Closure
*/
public $condition;

/**
* Create a new required validation rule based on a condition.
*
* @param bool|\Closure $condition
* @return void
*/
public function __construct($condition)
{
$this->condition = $condition;
}

/**
* Convert the rule to a validation string.
*
* @return string
*/
public function __toString()
{
if ($this->condition instanceof Closure) {
return $this->condition->__invoke() ? $this->rule : '';
}

return $this->condition ? $this->rule : '';
}
}
32 changes: 32 additions & 0 deletions tests/Validation/ValidationRequiredIfTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace Illuminate\Tests\Validation;

use PHPUnit\Framework\TestCase;
use Illuminate\Validation\Rules\RequiredIf;

class ValidationRequiredIfTest extends TestCase
{
public function testItClousureReturnsFormatsAStringVersionOfTheRule()
{
$rule = new RequiredIf(function () {
return true;
});

$this->assertEquals('required', (string) $rule);

$rule = new RequiredIf(function () {
return false;
});

$this->assertEquals('', (string) $rule);

$rule = new RequiredIf(true);

$this->assertEquals('required', (string) $rule);

$rule = new RequiredIf(false);

$this->assertEquals('', (string) $rule);
}
}