namespace App\Libraries;
class WorkDays {
protected $work_days=null;
protected $nation_holidays=['01-01','01-06','04-25','05-01','06-02','08-15','11-01','12-08','12-25','12-26'];
public $add_no_work=null;
public $yearWorking=null;
public $results=
[
'calendar'=>[],
'holidays'=>[],
'cleared'=>[],
'diff_date'=>[
]
];
public function __construct($options=[]) {
$this->makeOptions($options);
(null===$this->work_days)?$this->work_days=range(1,5):null;
}
public static function getInstance($options=[]){
return (new self($options));
}
private function makeOptions($opt=[]){
array_walk($opt,function($v,$k){
(property_exists($this,$k))?$this->$k=$v:null;
});
$this->yearWorking=array_unique($this->yearWorking);
sort($this->yearWorking);
array_map(function($el){
$this->add_no_work[]=date('m-d',easter_date($el));
},$this->yearWorking);
}
public static function createCalendar($year,$options=[]){
$options['yearWorking']=[$year];
$instance=self::getInstance($options);
$instance->createEcc($instance)->saveCalendar($instance)->filteringCalendar($instance);
dd($instance->results);
return $instance->results;
}
public static function createDiffDate($start,$end,$options=[]){
if(strtotime($start)>strtotime($end)){$t=$start;$start=$end;$end=$t;}
$options['yearWorking']=[date('Y',strtotime($start)),date('Y',strtotime($end))];
$instance=self::getInstance($options);
$instance->saveCalendar($instance);
$in=(new \DateTime())->setTimestamp(strtotime($start));
$en=(new \DateTime())->setTimestamp(strtotime($end));
return array_slice($instance->results['calendar'],$in->format('z'),($en->format('z')-$in->format('z'))+1);
}
private function saveCalendar(WorkDays $instance){
$last=null;
foreach ($instance->yearWorking as $year){
array_map(function($el) use (&$instance,&$last,$year){
(null===$last)?$last=new \DateTime($year.'-01-01'):$last->add(new \DateInterval('P1D'));
$instance->results['calendar'][]=['day'=>$last->format('Y-m-d'),
'd_w'=>$last->format('w'),
'day_y'=>$last->format('z'),
'work'=>$this->checkDays($instance,$last)];
},range(1,date('z', strtotime($year.'-12-31'))+1));
}
return $this;
}
private function filteringCalendar(WorkDays $instance){
$instance->results['cleared']=array_values(array_filter($instance->results['calendar'],function($el){
return($el['work'])?$el['day']:null;
}));
return $this;
}
private function checkDays(WorkDays $instance, \DateTime $check){
$r=true;
if(!in_array($check->format('w'),$instance->work_days))$r=false;
if($r && in_array($check->format('Y-m-d'),$instance->results['holidays']))$r=false;
return $r;
}
private function createEcc(WorkDays $instance){
foreach ( $instance->yearWorking as $item ) {
foreach ($instance->nation_holidays as $el)
$instance->results['holidays'][]=$item.'-'.$el;
foreach ($instance->add_no_work as $el)
$instance->results['holidays'][]=$item.'-'.$el;
}
return $this;
}
}