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

Add validData method #320

Closed
wants to merge 1 commit into from
Closed
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
25 changes: 25 additions & 0 deletions gump.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,31 @@ public function errors()
return $this->errors;
}

/**
* Perform data validation against the provided ruleset and return the valid data.
*
* @param array $data
* @param $check_fields
*
* @return array valid data.
*/
public function validData(array $data, $check_fields = false)
{
$data = $this->run($data, $check_fields);

if ($data === false) {
return [];
}

$allowed = array_keys($this->validation_rules());

$validData = array_filter($data, function ($key) use ($allowed) {
return in_array($key, $allowed);
}, ARRAY_FILTER_USE_KEY);

return $validData;
}

/**
* Perform data validation against the provided ruleset.
*
Expand Down
47 changes: 47 additions & 0 deletions tests/ValidDataTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

namespace Tests;

/**
* Class ValidateTest
*
* @package Tests
*/
class ValidDataTest extends BaseTestCase
{
public function testOnFailureReturnsEmptyArray()
{
$this->gump->validation_rules(array(
'field0' => 'required',
));

$result = $this->gump->validData([
'field1' => 'somedata'
]);

$this->assertEquals([], $result);
}

public function testOnSuccessReturnsOnlyValidDataWithFiltersApplied()
{
$this->gump->validation_rules(array(
'field0' => 'required|numeric',
'field1' => 'required',
));

$this->gump->filter_rules(array(
'field0' => 'trim'
));

$result = $this->gump->validData([
'field0' => ' 123 ',
'field1' => 'somedata',
'field2' => 'test'
]);

$this->assertEquals([
'field0' => '123',
'field1' => 'somedata'
], $result);
}
}