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

Update Same.php #129

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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 src/Helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,31 @@ public static function arrayGet(array $array, $key, $default = null)
return $array;
}

/**
*
* @param array $array
* @param string|null $key
* @return mixed
*/
public static function arrayIsset(array $array, $key)
{
if (is_null($key)) {
return false;
}

if (array_key_exists($key, $array)) {
return true;
}

foreach (explode('.', $key) as $segment) {
if (is_array($array) && array_key_exists($segment, $array)) {
return true;
}
}

return false;
}

/**
* Flatten a multi-dimensional associative array with dots.
* Adapted from: https://github.com/illuminate/support/blob/v5.3.23/Arr.php#L81
Expand Down
2 changes: 1 addition & 1 deletion src/Rules/Same.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class Same extends Rule
{

/** @var string */
protected $message = "The :attribute must be same with :field";
protected $message = "The :attribute must be same as :field";

/** @var array */
protected $fillableParams = ['field'];
Expand Down
32 changes: 30 additions & 2 deletions src/Validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,8 @@ protected function validateAttribute(Attribute $attribute)
$attributeKey = $attribute->getKey();
$rules = $attribute->getRules();

$inputIsset = $this->inputIsset($attributeKey);

$value = $this->getValue($attributeKey);
$isEmptyValue = $this->isEmptyValue($value);

Expand Down Expand Up @@ -169,9 +171,9 @@ protected function validateAttribute(Attribute $attribute)
}
}

if ($isValid) {
if ($isValid && ($value!==null || $inputIsset)) {
$this->setValidData($attribute, $value);
} else {
} else if (!$isValid) {
$this->setInvalidData($attribute, $value);
}
}
Expand Down Expand Up @@ -592,6 +594,17 @@ public function getValue(string $key)
return Helper::arrayGet($this->inputs, $key);
}

/**
* Given $key and get value
*
* @param string $key
* @return mixed
*/
public function inputIsset(string $key):bool
{
return Helper::arrayIsset($this->inputs, $key);
}

/**
* Set input value
*
Expand Down Expand Up @@ -686,6 +699,21 @@ public function getValidData(): array
return $this->validData;
}


/**
* Get valid data or throw exepction
*
* @throws \Rakit\Validation\ValidationException
* @return array
*/
public function validated(): array
{
if ($this->fails()) {
throw new ValidationException($this);
}
return $this->getValidData();
}

/**
* Set invalid data
*
Expand Down
84 changes: 84 additions & 0 deletions src/ValidationException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
<?php

namespace Rakit\Validation;

use Exception;

class ValidationException extends Exception
{
/**
* The validator instance.
*
* @var Validation
*/
public $validation;

/**
* The status code to use for the response.
*
* @var int
*/
public $status = 422;

/**
* Create a new exception instance.
*
* @param Validation $validation
* @return void
*/
public function __construct($validation)
{
parent::__construct(static::summarize($validation));

$this->validation = $validation;
}

/**
* Create an error message summary from the validation errors.
*
* @param Validation $validation
* @return string
*/
protected static function summarize($validation)
{
$messages = $validation->errors()->all();

if (! count($messages) || ! is_string($messages[0])) {
return 'The given data was invalid.';
}

$message = array_shift($messages);

if ($count = $validation->errors()->count()) {
$pluralized = $count === 1 ? 'error' : 'errors';

$message .= ' '."and $count more $pluralized";
}

return $message;
}

/**
* Get all the validation error messages.
*
* @return array
*/
public function getErrors():array
{
return $this->validation->errors()->toArray();
}

/**
* Set the HTTP status code to be used for the response.
*
* @param int $status
* @return $this
*/
public function status($status)
{
$this->status = $status;

return $this;
}

}
81 changes: 81 additions & 0 deletions tests/ValidatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use PHPUnit\Framework\TestCase;
use Rakit\Validation\Rule;
use Rakit\Validation\Rules\UploadedFile;
use Rakit\Validation\ValidationException;
use Rakit\Validation\Validator;

class ValidatorTest extends TestCase
Expand Down Expand Up @@ -1282,6 +1283,7 @@ public function testGetValidData()
'thing' => 'exists',
], [
'thing' => 'required',
'name' => 'alpha',
'items.*.product_id' => 'required|numeric',
'emails.*' => 'required|email',
'items.*.qty' => 'required|numeric',
Expand Down Expand Up @@ -1370,6 +1372,85 @@ public function testGetInvalidData()
$this->assertFalse(isset($stuffs['two']));
}

public function testValidated()
{
$validation = $this->validator->validate([
'emails' => [
'[email protected]',
'[email protected]'
],
'thing' => 'exists',
], [
'thing' => 'required',
'emails.*' => 'required|email',
]);

$validData = $validation->validated();

$this->assertEquals([
'emails' => [
0 => '[email protected]',
1 => '[email protected]'
],
'thing' => 'exists',
], $validData);
}

public function testValidatedException()
{
$this->expectException(ValidationException::class);
$validation = $this->validator->validate([
'items' => [
[
'product_id' => 1,
'qty' => 'invalid'
]
],
'emails' => [
'[email protected]',
'something',
'[email protected]'
],
'stuffs' => [
'one' => '1',
'two' => '2',
'three' => 'three',
],
'thing' => 'exists',
], [
'thing' => 'required',
'items.*.product_id' => 'required|numeric',
'emails.*' => 'required|email',
'items.*.qty' => 'required|numeric',
'something' => 'required|in:on,off',
'stuffs' => 'required|array',
'stuffs.one' => 'numeric',
'stuffs.two' => 'numeric',
'stuffs.three' => 'numeric',
]);
$validation->validated();
}

public function testValidatedExceptionData()
{
try {
$validation = $this->validator->validate([
], [
'thing' => 'required'
]);
$validation->validated();
} catch (ValidationException $e) {
$this->assertSame(
[
'thing' => [
'required'=> 'The Thing is required'
]
],
$e->getErrors()
);
}
}

public function testRuleInInvalidMessages()
{
$validation = $this->validator->validate([
Expand Down