Skip to content

Instantly share code, notes, and snippets.

@zabaala
Created October 22, 2020 11:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zabaala/b719d23fa637aebdba0601ccd5e771d3 to your computer and use it in GitHub Desktop.
Save zabaala/b719d23fa637aebdba0601ccd5e771d3 to your computer and use it in GitHub Desktop.
<?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());
}
}
}
<?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