Created
January 2, 2018 07:49
-
-
Save khoatran/c4390c5a6add6f613a1e739b4d2ff1b2 to your computer and use it in GitHub Desktop.
OctoberCMS model validation
This file contains hidden or 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 | |
use Carbon\Carbon; | |
use Model; | |
use Validator; | |
/** | |
* Model | |
*/ | |
class WorkingSchedule extends Model | |
{ | |
use \October\Rain\Database\Traits\Validation; | |
/* | |
* Disable timestamps by default. | |
* Remove this line if timestamps are defined in the database table. | |
*/ | |
public $timestamps = false; | |
protected $dates = ['from_time', 'to_time']; | |
/* | |
* Validation | |
*/ | |
public $rules = [ | |
'from_time' => 'required', | |
'to_time' => 'required|same_day:from_time', | |
]; | |
public $customMessages = [ | |
'same_day' => 'The :attribute and :other must match on the same day.' | |
]; | |
/** | |
* @var string The database table used by the model. | |
*/ | |
public $table = 'cmgdev_booking_doctor_working_schedule'; | |
public $belongsTo = [ | |
'clinic' => [ | |
'CmgDev\Booking\Models\Clinic', | |
'key'=>'clinic_id' | |
], | |
'doctor' => [ | |
'CmgDev\Booking\Models\Doctor', | |
'key'=>'doctor_id' | |
] | |
]; | |
public function beforeSave() { | |
/** @var Carbon $date */ | |
$date = $this->from_time; | |
$this->date_key = $date->toDateString(); | |
} | |
protected function beforeValidate() { | |
$model = $this; | |
Validator::extend('same_day', function($attribute, $value, $parameters) use ($model) { | |
/** @var Carbon $date */ | |
$date = $model->$attribute; | |
$dateValue = null; | |
if(!empty($date)) { | |
$dateValue = $date->toDateString(); | |
} | |
$compareDateAttribute = $parameters[0]; | |
/** @var Carbon $dateToCompare */ | |
$dateToCompare = $model->$compareDateAttribute; | |
$dateToCompareValue = null; | |
if(!empty($dateToCompare)) { | |
$dateToCompareValue = $dateToCompare->toDateString(); | |
} | |
return !empty($dateToCompareValue) && $dateToCompareValue === $dateValue; | |
}); | |
Validator::replacer('same_day', function($message, $attribute, $rule, $parameters) { | |
return str_replace(':other', $parameters[0], $message); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment