Skip to content

Commit

Permalink
feat: add Controller::validateData()
Browse files Browse the repository at this point in the history
  • Loading branch information
kenjis committed Feb 1, 2022
1 parent 156b24d commit 69afb8d
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 3 deletions.
29 changes: 26 additions & 3 deletions system/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -128,13 +128,36 @@ protected function loadHelpers()
}

/**
* A shortcut to performing validation on input data. If validation
* is not successful, a $errors property will be set on this class.
* A shortcut to performing validation on Request data.
*
* @param array|string $rules
* @param array $messages An array of custom error messages
*/
protected function validate($rules, array $messages = []): bool
{
$this->setValidator($rules, $messages);

return $this->validator->withRequest($this->request)->run();
}

/**
* A shortcut to performing validation on any input data.
*
* @param array $data The data to validate
* @param array|string $rules
* @param array $messages An array of custom error messages
*/
protected function validateData(array $data, $rules, array $messages = []): bool
{
$this->setValidator($rules, $messages);

return $this->validator->run($data);
}

/**
* @param array|string $rules
*/
private function setValidator($rules, array $messages): void
{
$this->validator = Services::validation();

Expand All @@ -157,6 +180,6 @@ protected function validate($rules, array $messages = []): bool
$rules = $validation->{$rules};
}

return $this->validator->withRequest($this->request)->setRules($rules, $messages)->run();
$this->validator->setRules($rules, $messages);
}
}
23 changes: 23 additions & 0 deletions tests/system/ControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,29 @@ public function testValidateWithStringRulesFoundUseMessagesParameter()
$this->assertSame('You must choose a username.', Services::validation()->getError());
}

public function testValidateData()
{
// make sure we can instantiate one
$this->controller = new Controller();
$this->controller->initController($this->request, $this->response, $this->logger);

$method = $this->getPrivateMethodInvoker($this->controller, 'validateData');

$data = [
'username' => 'mike',
'password' => '123',
];
$rule = [
'username' => 'required',
'password' => 'required|min_length[10]',
];
$this->assertFalse($method($data, $rule));
$this->assertSame(
'The password field must be at least 10 characters in length.',
Services::validation()->getError('password')
);
}

public function testHelpers()
{
$this->controller = new class () extends Controller {
Expand Down

0 comments on commit 69afb8d

Please sign in to comment.