2020-02-13 01:03:54 +09:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Rules;
|
|
|
|
|
|
|
|
use Illuminate\Contracts\Validation\Rule;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* CSVインポート機能の日時バリデーションルール
|
|
|
|
* @package App\Rules
|
|
|
|
*/
|
|
|
|
class CsvDateTime implements Rule
|
|
|
|
{
|
|
|
|
const VALID_FORMATS = [
|
|
|
|
'Y/m/d H:i:s',
|
|
|
|
'Y/n/j G:i:s',
|
|
|
|
'Y/m/d H:i',
|
|
|
|
'Y/n/j G:i',
|
|
|
|
];
|
|
|
|
|
2020-02-16 14:28:30 +09:00
|
|
|
const MINIMUM_TIMESTAMP = 946652400; // 2000-01-01 00:00:00 JST
|
|
|
|
const MAXIMUM_TIMESTAMP = 4102412399; // 2099-12-31 23:59:59 JST
|
|
|
|
|
|
|
|
/** @var string Validation error message */
|
2020-02-16 22:06:12 +09:00
|
|
|
private $message = ':attributeの形式は "年/月/日 時:分" にしてください。';
|
2020-02-16 14:28:30 +09:00
|
|
|
|
2020-02-13 01:03:54 +09:00
|
|
|
/**
|
|
|
|
* Create a new rule instance.
|
|
|
|
*
|
|
|
|
* @return void
|
|
|
|
*/
|
|
|
|
public function __construct()
|
|
|
|
{
|
|
|
|
//
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Determine if the validation rule passes.
|
|
|
|
*
|
|
|
|
* @param string $attribute
|
|
|
|
* @param mixed $value
|
|
|
|
* @return bool
|
|
|
|
*/
|
|
|
|
public function passes($attribute, $value)
|
|
|
|
{
|
|
|
|
// この辺の実装の元ネタは、LaravelのValidatesAttributes#validateDateFormat()
|
|
|
|
|
|
|
|
if (!is_string($value)) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
foreach (self::VALID_FORMATS as $format) {
|
|
|
|
$date = \DateTime::createFromFormat('!' . $format, $value);
|
2020-02-16 14:28:30 +09:00
|
|
|
if (!$date) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
$timestamp = (int) $date->format('U');
|
|
|
|
if ($timestamp < self::MINIMUM_TIMESTAMP || self::MAXIMUM_TIMESTAMP < $timestamp) {
|
2020-02-16 22:06:12 +09:00
|
|
|
$this->message = ':attributeは 2000/01/01 00:00 〜 2099/12/31 23:59 の間のみ対応しています。';
|
2020-02-16 14:28:30 +09:00
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
2020-02-13 01:03:54 +09:00
|
|
|
|
2020-02-16 14:28:30 +09:00
|
|
|
$formatted = $date->format($format);
|
|
|
|
if ($formatted === $value) {
|
2020-02-13 01:03:54 +09:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get the validation error message.
|
|
|
|
*
|
|
|
|
* @return string
|
|
|
|
*/
|
|
|
|
public function message()
|
|
|
|
{
|
2020-02-16 14:28:30 +09:00
|
|
|
return $this->message;
|
2020-02-13 01:03:54 +09:00
|
|
|
}
|
|
|
|
}
|