Created
October 22, 2020 11:23
-
-
Save zabaala/b719d23fa637aebdba0601ccd5e771d3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace App\Support\Validation; | |
abstract class Validation | |
{ | |
/** | |
* @var array | |
*/ | |
private array $data = []; | |
/** | |
* Define data to be validated. | |
* | |
* @param array $data | |
* @return void | |
*/ | |
protected function setData(array $data) : void | |
{ | |
$this->data = $data; | |
} | |
/** | |
* Define all rules that will be used to validate the data. | |
* | |
* @return array | |
*/ | |
abstract protected function rules() : array; | |
/** | |
* Define messages to validation rules. | |
* | |
* @return array | |
*/ | |
abstract protected function messages() : array; | |
/** | |
* @throws ValidationException | |
*/ | |
public function validate() | |
{ | |
$validation = validator($this->data, $this->rules(), $this->messages()); | |
if ($validation->fails()) { | |
throw new ValidationException($validation->errors()); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Support\Validation; | |
use Illuminate\Contracts\Support\MessageBag; | |
class ValidationException extends \Exception | |
{ | |
/** | |
* @var MessageBag | |
*/ | |
private MessageBag $errors; | |
public function __construct(MessageBag $messageBag) | |
{ | |
$this->errors = $messageBag; | |
parent::__construct($messageBag->first()); | |
} | |
/** | |
* @return array | |
*/ | |
public function all() | |
{ | |
return $this->errors->all(); | |
} | |
/** | |
* @return string | |
*/ | |
public function first() | |
{ | |
return $this->errors->first(); | |
} | |
/** | |
* @return mixed | |
*/ | |
public function last() | |
{ | |
$errors = $this->all(); | |
return end($errors); | |
} | |
/** | |
* @return string | |
*/ | |
public function __toString() | |
{ | |
return $this->first(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment