<?php
declare(strict_types=1);
namespace App\Model;
use Hyperf\Snowflake\IdGeneratorInterface;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Utils\Str;
use PhpOffice\PhpSpreadsheet\IOFactory;
use \PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
class Tool extends Model
{
/**
* 生成id
* @return int
*/
public static function generateId()
{
$container = ApplicationContext::getContainer();
$generator = $container->get(IdGeneratorInterface::class);
$id = $generator->generate();
return $id;
}
/**
* 解析 已生成的id
* @param $id
* @return \Hyperf\Snowflake\Meta
*/
public static function degenerateId($id)
{
$container = ApplicationContext::getContainer();
$generator = $container->get(IdGeneratorInterface::class);
$meta = $generator->degenerate($id);
return $meta;
}
/**
* 删除文件
* @param $file
* @return bool
*/
public static function deleteFile($file)
{
$filePath = config('document_root') . $file;
if (is_file($filePath)) {
unlink($filePath);
return true;
}
return false;
}
/**
* curl get
*/
public static function curl_get_https($url, $param = '')
{
$cur = curl_init($url);
if ($param) {
curl_setopt($cur, CURLOPT_POST, 1);
curl_setopt($cur, CURLOPT_POSTFIELDS, $param);
}
curl_setopt($cur, CURLOPT_REFERER, config('main_url'));
// curl_setopt($cur, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($cur, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($cur, CURLOPT_HEADER, 0);
curl_setopt($cur, CURLOPT_TIMEOUT, 30);
curl_setopt($cur, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($cur, CURLOPT_RETURNTRANSFER, 1);
$rec = curl_exec($cur);
curl_close($cur);
return $rec;
}
/**
* 下载远程文件
* @param $url
* @param string $filename
* @return mixed
*/
public static function download($url, $filename = 'images.png')
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
$file = curl_exec($ch);
curl_close($ch);
$resource = fopen($filename, 'a');
fwrite($resource, $file);
fclose($resource);
return true;
}
/**
* curl_post
* @param {*} $url
* @param {*} $data
* @return {*}
*/
public static function curl_post($url, $data = array())
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 500);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_URL, $url);
$res = curl_exec($curl);
curl_close($curl);
return $res;
}
/**
* 日志文件读取
* @param $filename 文件名
* @param string $source 文件来源
* @return array
*/
public static function readFileContent($filename, $source = '')
{
$content = [];
$fh = @fopen($filename, 'r');
if ($fh) {
while (!feof($fh)) {
$row = fgets($fh, 10240);
if (!$row) continue;
$data = [];
if ($source == 'error_log') {
$row = json_decode($row, true);
$data = $row;
$data['create_time'] = $row["datetime"] ? date('Y-m-d H:i:s', strtotime($row["datetime"])) : null;
unset($data["channel"], $data["extra"], $data["datetime"], $row);
$data["context"] = json_encode($data["context"]);
$data['node'] = '';
$data['geoip'] = '';
$data['action'] = '';
} else if ($source == 'nginx_log') {
$row_arr = explode("\" \"", $row);
foreach ($row_arr as $key => &$item) {
$item = trim(trim(trim($item, '"')), '"');
if ($item == '-') $item = '';
}
$data['remote_addr'] = $row_arr[0] ?: '';
$data['remote_user'] = $row_arr[2] ?: '';
$data['time_local'] = date('Y-m-d H:i:s', strtotime(trim(trim($row_arr[3], ']'), '[')));
$data['http_host'] = $row_arr[4] ?: '';
$data['request'] = $row_arr[5] ?: '';
$data['status'] = $row_arr[6] ?: '';
$data['body_bytes_sent'] = $row_arr[7] ?: '';
$data['http_referer'] = $row_arr[8] ?: '';
$data['http_user_agent'] = $row_arr[9] ?: '';
$data['http_x_forwarded_for'] = $row_arr[10] ?: '';
$data['upstream_cache_status'] = $row_arr[11] ?: '';
$data['request_time'] = $row_arr[12] ?: '';
$data['upstream_response_time'] = $row_arr[13] ?: '';
}
$content[] = $data;
}
}
fclose($fh);
return $content;
}
/**
* 格式化为 label value数组
* @param $arr
* @return array
*/
public static function formatDict($arr)
{
$new_arr = [];
foreach ($arr as $key => $item) {
$new_arr[] = ['label' => $key, 'value' => $item];
}
return $new_arr;
}
/**
* phpoffice上传+实例化
* @param {*} $file
* @return {*}
*/
public static function phpoffice($file)
{
$file_info = $file->toArray();
// 后缀
$ext = strtolower($file->getExtension());
$allowedArr = ['xls', 'xlsx', 'csv'];
if (!in_array($ext, $allowedArr)) {
return self::failure('上传格式不允许');
}
// 大小
if (isset($file_info['size'])) {
if ($file_info['size'] > 5 * 1024 * 1024) {
return self::failure('文件大小不能超过5M');
}
}
// 路径
$folderPath = '/file/excel/' . date('Ymd') . '/';
$filePath = config('document_files') . $folderPath;
if (!is_dir($filePath)) mkdir($filePath, 0755, true);
$fileName = Str::random(16);
$filePathUrl = $filePath . $fileName . '.' . $ext;
$file->moveTo($filePathUrl);
if (!$file->isMoved()) {
return self::failure('上传失败');
}
chmod($filePathUrl, 0755);
$file_url = $folderPath . $fileName . '.' . $ext;
// 有Xls和Xlsx格式两种
if ($ext == 'xlsx') {
$objReader = IOFactory::createReader('Xlsx');
} else {
$objReader = IOFactory::createReader('Xls');
}
$objReader->setReadDataOnly(TRUE);
$obj = $objReader->load(config('document_files') . $file_url);
return $obj;
}
/**
* 身份证号获取年龄
* @param {*} $idCard
* @return {*}
*/
public static function getAge($idCard = '')
{
if ($idCard) {
# 1.从身份证中获取出生日期
$birth_Date = strtotime(substr($idCard, 6, 8)); //截取日期并转为时间戳
# 2.格式化[出生日期]
$Year = date('Y', $birth_Date); //yyyy
$Month = date('m', $birth_Date); //mm
$Day = date('d', $birth_Date); //dd
# 3.格式化[当前日期]
$current_Y = date('Y'); //yyyy
$current_M = date('m'); //mm
$current_D = date('d'); //dd
# 4.计算年龄()
$age = $current_Y - $Year; //今年减去生日年
if ($Month > $current_M || $Month == $current_M && $Day > $current_D) { //深层判断(日)
$age--; //如果出生月大于当前月或出生月等于当前月但出生日大于当前日则减一岁
}
# 返回
return $age;
}
}
/**
* 15/18位数身份证号获取性别
* @param {*} $idCard
* @return {*}
*/
public static function getSex($idCard = '')
{
if ($idCard) {
return substr($idCard, (strlen($idCard) == 15 ? -2 : -1), 1) % 2 ? '1' : '2';
}
}
/**
* 15/18位数身份证号获取出生年月日
* @param {*} $idCard
* @return {*}
*/
public static function getBirthday($idCard = '')
{
if ($idCard) {
if (strlen($idCard) == 18) {
return substr($idCard, 6, 4) . "-" . substr($idCard, 10, 2) . "-" . substr($idCard, 12, 2);
} elseif (strlen($idCard) == 15) {
return "19" . substr($idCard, 6, 2) . "-" . substr($idCard, 8, 2) . "-" . substr($idCard, 10, 2);
}
}
}
}