Laravel timestamp validator

Laravel 5.1, Laravel 5.2, Lara ... The code progresses, optimizes and develops. An arrays validator has appeared in the new (5.2) version, for example, but what if you need to validate the incoming timestamp? That's right, writing a
Once upon a time there lived one project on Laravel 5.1. More precisely, its API side lives. There is a need to "drive" back and forth various dates. But how to drive them if time zones exist? It was decided to install the server in UTC + 0 and communicate using timestamp, which can be easily converted to the right time on the front end. Okay, no questions about that. Except one - how to validate incoming data? Create your own validator.
The full validator code is at the very end of the article.
Go!
In the app / Extensions / Validators folder, create a file and name it TimestampValidator.php .
namespace Lame\Extensions\Validators;
use Illuminate\Validation\Validator;
class TimestampValidator extends Validator{
}
We need to accept that the incoming date matches “before” and “after”.
Consider the first example. We have the date of birth of the user. The user must be over 10 years old, i.e. born before 2016. Accordingly, we need to accept a date that will be until 2016. In the validation rules, indicate:
/** Берем текущую дату, отнимаем 10 лет, прибавляем один день и получаем timestamp от необходимой даты */
$date = Carbon::now()->subYears(10)->addDay(1)->timestamp;
/** Указываем, что входящая дата в формате timestamp должна быть до нужной даты в timestamp */
$rules = [
"bDay" => "numeric|before_timestamp:".$date,
];
The rule "before_timestamp" has appeared. We return to our validator and create a method that will carry out the necessary check. The name of the method should have the following structure: "validate <rule in camelCase format>". $ value among the input parameters is the value that came from outside. $ parameters - an array of parameters that are specified in the rules (before_timestamp: ". $ date).
public function validateBeforeTimestamp($attribute, $value, $parameters)
{
$value = (int)$value;
if ((int)$parameters[0] <= 0) {
throw new \Exception("Timestamp parameter in the beforeTimestamp validator not valid!");
}
if ($value != "" && $value >= $parameters[0]) {
return false;
}
return true;
}
Second example. We need to create a task with a deadline. The minimum deadline is 4 hours. Create rules:
$date = Carbon::now()->addHours(4)->timestamp;
$rules = [
"deadline" => "required|numeric|after_timestamp:".$date
];
A new rule has appeared - “after_timestamp”. We process it in our validator:
public function validateAfterTimestamp($attribute, $value, $parameters)
{
$value = (int)$value;
if ((int)$parameters[0] <= 0) {
throw new \Exception("Timestamp parameter in the beforeTimestamp validator not valid!");
}
if ($value != "" && $value <= $parameters[0]) {
return false;
}
return true;
}
To connect our validator, I created my ServiceProvider in the app / Providers folder - CustomValidateServiceProvider.php .
На этом, в принципе всё. Сообщения об ошибках указываются в файле validation.php.
"custom" => [
"deadline" => [
"after_timestamp" => "Deadline should be minimum 4 hours"
],
"bDay" => [
"before_timestamp" => "Age should be minimum 10 years",
"numeric" => "Birthday date should be in timestamp"
]
]
Полный код класса "Date before which should be input timestamp"]
* @return bool
* @throws \Exception
*/
public function validateBeforeTimestamp($attribute, $value, $parameters)
{
$value = (int)$value;
if ((int)$parameters[0] <= 0) {
throw new \Exception("Timestamp parameter in the beforeTimestamp validator not valid!");
}
if ($value != "" && $value >= $parameters[0]) {
return false;
}
return true;
}
/**
* @param $attribute
* @param $value
* @param $parameters = ["date" => "Date before which should be input timestamp"]
* @return bool
* @throws \Exception
*/
public function validateAfterTimestamp($attribute, $value, $parameters)
{
$value = (int)$value;
if ((int)$parameters[0] <= 0) {
throw new \Exception("Timestamp parameter in the beforeTimestamp validator not valid!");
}
if ($value != "" && $value <= $parameters[0]) {
return false;
}
return true;
}
#endregion
}
С помощью date, after, before timestamp не проверишь. Или можно проверить? Если можно, буду рад в комментариях, сообщениях прочитать существующие варианты.