文中所提Http类 可以在博客中找到,代码中所使用的cache是减少不必要的重复请求,可自行调整。代码如下:
<?php
class Calendar {
use Http;
protected static $_instance;
protected $_data;
public function __construct($date = '')
{
if (empty($date)) {
$date = date('Y-01');
}
$_data = cache('calendar:' . $date);
if (empty($_data)) {
$this->_data = $this->getHoliday($date);
cache('calendar:' . $date, $this->_data);
} else {
$this->_data = $_data;
}
}
/**
* 获取年度法定节假日
* @return array
*/
public function getHoliday($date)
{
$result = $this->getRequest("http://opendata.baidu.com/api.php?query={$date}&format=json&resource_id=6018", [], [], false);
$result = mb_convert_encoding($result, 'utf8', 'gbk');
$result = json_decode($result, true);
if (isset($result['status']) && $result['status'] == 0) {
if (!empty($result['data'][0]['holiday'])) {
$festival = array_column($result['data'][0]['holiday'], 'list');
$return = [];
if (is_array($festival)) foreach ($festival as $item) {
$return += (array)array_column($item, 'status', 'date');
}
$_data = $return;
} else {
throw new \Exception('节假日获取异常');
}
} else {
throw new \Exception('接口异常');
}
return $return;
}
public static function getInstance($date = '')
{
if (empty($date)) {
$date = date('Y-01');
}
if (!isset(self::$_instance[$date])) {
self::$_instance[$date] = new self();
}
return self::$_instance[$date];
}
/**
* 判断指定日期是否是工作日
* @return boolean
*/
public function isWork($date)
{
$d = new \DateTime($date);
$_date = $d->format('Y-m-d');
$flag = true;
if (isset($this->_data[$_date])) {
if ($this->_data[$_date] == 2) {
$flag = false;
}
} else {
$w = $d->format('N'); //周几
$flag = !in_array($w, [6, 7]) ? true : false;
}
return $flag;
}
/**
* 获取指定日期的下一个工作日
*/
public function getNextWorkDate($date)
{
$time = strtotime($date);
$i = 1;
while($i < 10) {
$_tmpDate = date('Y-m-d', strtotime("+{$i} days", $time));
if ($this->isWork($_tmpDate)) {
return $_tmpDate;
} else {
$i++;
}
}
}
public function getData()
{
return $this->_data;
}
/**
* 获取法定节假日假期
*/
public function getHolidayDate()
{
return array_keys(array_filter($this->_data, function($v) {
return $v == 1;
}));
}
}