zzwy2/app/service/Tool.php

103 lines
2.8 KiB
PHP
Executable File

<?php
namespace app\service;
use app\model\Category;
use app\model\Article;
class Tool
{
//删除文件
public static function delFile($path)
{
if(!empty(trim($path))){
$realPath = app()->getRootPath() . ltrim($path, '/');
if (file_exists($realPath)) {
$info = pathinfo($realPath);
$source = $info['dirname'] . DIRECTORY_SEPARATOR . $info['filename'] . '*.' . $info['extension'];
foreach(glob($source) as $filename){
if(is_file($filename)){
unlink($filename);
}
}
clearstatcache();// 清除缓存
}
}
}
/**
* 删除目录下的所有文件和子目录
* 调用完毕后请用clearstatcache()清理缓存
*/
public static function removeByPath($path)
{
if(is_dir($path)) {
if($handle = @opendir($path)) {
while (($file = readdir($handle)) !== false){
if($file != '.' && $file != '..') {
$child = $path.'/'.$file;
is_dir($child) ? self::removeByPath($child) : @unlink($child);
}
}
}
closedir($handle);
} elseif (is_file($path)) {
@unlink($path);
} else {
return false;
}
return true;
}
//去除字符串空格
public static function trimSpace($str)
{
return str_replace(' ', '', trim($str));
}
//获取文章链接
public static function getArticleUrl($article)
{
if(empty($article)){
return '';
}
// if(!empty($article['link'])){
// return $article['link'];
// }
if(empty($article['route'])){
return url('article/detail', ['id' => $article['id']]);
}
$category = Category::getById($article['category_id']);
$categoryRoute = '';
if(isset($category['route']) && !empty($category['route'])){
$categoryRoute = $category['route'];
}
$url = '/';
if(!empty($categoryRoute)){
$url .= $categoryRoute . '/';
}
return $url . $article['route'] . '.html';
}
/**
* 格式化金钱字段
* @param $money
* @return float
*/
public static function moneyFormat($money)
{
$money = is_string($money) ? trim($money) : $money;
return is_numeric($money) ? number_format($money, 2, '.', '') : 0;
}
// 获取客户端IP
public static function get_client_ip() {
$forwarded = request()->header("x-forwarded-for");
if($forwarded){
$ip = explode(',',$forwarded)[0];
}else{
$ip = request()->ip();
}
return $ip;
}
}