Skip to content

Commit

Permalink
Merge pull request #15 from spira/feature/composite-key-validation
Browse files Browse the repository at this point in the history
Adding composite key validation method (unique_with).
  • Loading branch information
zakhenry committed Dec 21, 2015
2 parents dbb8211 + 89138b8 commit c1a2f7d
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
21 changes: 21 additions & 0 deletions Validation/SpiraValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Illuminate\Support\Arr;
use Rhumsaa\Uuid\Uuid;
use Spira\Core\Model\Datasets\Countries;
use Illuminate\Support\Facades\DB;

class SpiraValidator extends Validator
{
Expand Down Expand Up @@ -78,6 +79,26 @@ public function validateNotRequiredIf($attribute, $value, $parameters)
return true;
}

/**
* Rule used to validate if two columns are unique within a table.
*
* Usage:
* 'field1' => 'unique_with:table_name,field2'
*/
public function validateUniqueWith($attribute, $value, $parameters)
{
$count = DB::table($parameters[0])
->where($attribute, '=', $value)
->where($parameters[1], '=', $this->getData()[$parameters[1]])
->count();

if ($count > 0) {
return false;
}

return true;
}

/**
* Register custom validation rule for countries.
*
Expand Down
24 changes: 24 additions & 0 deletions tests/ValidatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -142,4 +142,28 @@ public function testFailingValidateAlphaDashSpace()

$this->assertContains('spaces', $validation->messages()->get('username')[0]);
}

public function testValidateUniqueWith()
{
$testEntity = $this->getFactory(TestEntity::class)->customize([
'integer' => 123,
'text' => 'foobar',
])->create();

$testEntity->entity_id = (string) Uuid::uuid4();

$validationFail = $this->validator->make($testEntity->toArray(), [
'integer' => 'unique_with:'.TestEntity::getTableName().',text',
]);

$this->assertFalse($validationFail->passes());

$testEntity->text = 'barfoo';

$validationPass = $this->validator->make($testEntity->toArray(), [
'integer' => 'unique_with:'.TestEntity::getTableName().',text',
]);

$this->assertTrue($validationPass->passes());
}
}

0 comments on commit c1a2f7d

Please sign in to comment.