Commit 2f5b6b2f authored by hj's avatar hj

更新提交

parent 848cbaad
......@@ -11,6 +11,7 @@
namespace App\Http\Controllers\V1\Chemicals;
use App\Services\Api\ChemicalsMsdsService;
use App\Services\Api\RhawnOrdersService;
use Illuminate\Http\Request;
use Jiannei\Response\Laravel\Support\Facades\Response;
......@@ -30,15 +31,16 @@ class MsdsController extends Controller
{
use Helpers;
public function __construct(RhawnOrdersService $rhawnOrdersService)
public function __construct(ChemicalsMsdsService $chemicalsMsdsService)
{
$this->rhawnOrdersService= $rhawnOrdersService;
$this->controllerType = 'rhawn';
$this->chemicalsMsdsService= $chemicalsMsdsService;
}
public function getMsds(Request $request)
{
$this->chemicalsMsdsService->getMsds('270912-72-6');
$customerCode = $request->get('customer_code');
$companyCode = $request->get('company_code');
......
<?php
namespace App\Repositories\Contracts;
use Prettus\Repository\Contracts\RepositoryInterface;
interface FileManageRepository extends RepositoryInterface
{
}
<?php
namespace App\Repositories\Criteria;
use Illuminate\Database\Eloquent\Builder;
use App\Repositories\Criteria\Criteria;
class BaseCriteria extends Criteria
{
protected function condition(Builder $query): void
{
if ($this->request->has('created_at')) {
$createdAt = $this->request->offsetGet('created_at');
if(!empty($createdAt)){
list($start,$end) = explode(',',$createdAt);
if(!preg_match('/[0-9]{4}\-[0-9]{2}\-[0-9]{2}\ [0-9]{2}\:[0-9]{2}\:[0-9]{2}/i',$start)){
$start = $start. ' 00:00:00';
}
if(!preg_match('/[0-9]{4}\-[0-9]{2}\-[0-9]{2}\ [0-9]{2}\:[0-9]{2}\:[0-9]{2}/i',$end)){
$end = $end. ' 23:59:59';
}
if(!empty($start) && !empty($end)){
$query->whereRaw('created_at >= "'.$start.'" and created_at < "'.$end.'"');
}
}
}
if ($this->request->has('createdAt')) {
$createdAt = $this->request->offsetGet('createdAt');
if(!empty($createdAt)){
list($start,$end) = explode(',',$createdAt);
if(!preg_match('/[0-9]{4}\-[0-9]{2}\-[0-9]{2}\ [0-9]{2}\:[0-9]{2}\:[0-9]{2}/i',$start)){
$start = $start. ' 00:00:00';
}
if(!preg_match('/[0-9]{4}\-[0-9]{2}\-[0-9]{2}\ [0-9]{2}\:[0-9]{2}\:[0-9]{2}/i',$end)){
$end = $end. ' 23:59:59';
}
if(!empty($start) && !empty($end)){
$query->whereRaw('created_at >= "'.$start.'" and created_at < "'.$end.'"');
}
}
}
}
}
<?php
namespace App\Repositories\Eloquent;
use App\Repositories\Contracts\FileManageRepository;
use App\Repositories\Models\FileManage;
use Prettus\Validator\Contracts\ValidatorInterface;
use App\Repositories\BaseRepository;
class FileManageRepositoryEloquent extends BaseRepository implements FileManageRepository
{
/**
* 定义validator的检索规则
* @var \string[][]
*/
public $rules = [
ValidatorInterface::RULE_CREATE => [
'uniqueid' => 'required|string',
'name' => 'required|string',
'type' => 'required|string',
'extension' => 'required|string',
'path' => 'required|string',
'mime_type' => 'required|string',
'byte_size' => 'required',
],
];
/**
* Specify Model class name.
*
* @return string
*/
public function model()
{
return FileManage::class;
}
public function saveUplodFiles($fileImage)
{
$saveParams = $fileImage;
if($file = $this->getFileByUniqueId($saveParams['uniqueid'])){
$saveParams['updated_at'] = date('Y-m-d H:i:s',time());
$file = $file->update($saveParams);
}else{
$saveParams['type'] = (isset($saveParams['type']) && !empty($saveParams['type'])) ? $saveParams['type'] : 'image';
$saveParams['created_at'] = date('Y-m-d H:i:s',time());
$file = $this->create($saveParams);
}
return $file;
}
public function getFileByUniqueId($id)
{
$file = $this->findWhere(['uniqueid' => $id]);
return $file->first();
}
}
<?php
/**
* Created by Reliese Model.
*/
namespace App\Repositories\Models;
use Carbon\Carbon;
/**
* Class FileManage
*
* @property int $id
* @property string $uniqueid
* @property string $name
* @property string $extension
* @property string $type
* @property string $path
* @property string $mime_type
* @property int $byte_size
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property string $model_name
* @property string $model_data_id
*
* @package App\Repositories\Models
*/
class FileManage extends Model
{
protected $table = 'file_manage';
protected $casts = [
'byte_size' => 'int'
];
protected $fillable = [
'uniqueid',
'name',
'extension',
'type',
'path',
'mime_type',
'byte_size',
'model_name',
'model_data_id',
'created_by'
];
}
<?php
namespace App\Services\Api;
use App\Services\FileService;
use Illuminate\Support\Facades\Storage;
class ChemicalsMsdsService
{
public function __construct()
{
}
public function getMsds($cas)
{
$findResult = shell_exec('find '.env('MSDS_FILE_DIR').' -iname \''.$cas.'\' -print');
if(is_null($findResult)){
return null;
}
$msds_html = file_get_contents(env('MSDS_FILE_DIR').'/'.$cas.'/'.$cas.'_sds_cn.html');
dd($msds_html);
dd(Storage::exists(env('MSDS_FILE_DIR')));
if(Storage::exists(env('MSDS_FILE_DIR').'/'.$cas)){
dd(123);
}
$fileService = app(FileService::class);
dd($fileService->getFileFolderPath());
}
}
<?php
namespace App\Services;
use App\Exceptions\NotFoundHttpException;
use App\Exceptions\ServerRunTimeException;
use App\Repositories\Contracts\FileManageRepository;
use App\Services\Traits\BaseService;
use App\Support\Traits\Helpers;
use Illuminate\Contracts\Filesystem\Factory as FilesystemFactory;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Sopamo\LaravelFilepond\Filepond;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class FileService
{
use Helpers, BaseService;
public function __construct(FileManageRepository $fileManageRepository)
{
$this->setRepository($fileManageRepository);
}
/**
* 文件上传
* @param UploadedFile $file
* @return array|null
*/
public function uploadFile(UploadedFile $file)
{
$fileInfo = $this->getUploadFileInfo($file);
$fileName = $fileInfo['name'].'.'.$fileInfo['extension'];
$realPath = $this->getFileFolderPath().'/'.$fileName;
if(
$this->saveToFile($realPath,$file->getContent())
){
$fileSave = $fileInfo;
$fileSave['uniqueid'] = $this->getBase64Path($realPath);
$fileSave['type'] = $this->isImageType($fileInfo) ? 'image' : 'file';
$fileSave['path'] = $realPath;
$saveResult = $this->saveFileRecord($fileSave);
if($saveResult){
$fileUrl = $this->getDownloadUrl($saveResult->uniqueid);
return ['url' => $fileUrl, 'file' => $saveResult->uniqueid];
}
}
return null;
}
public function getFileFolderPath($folderName = '')
{
$folder = $folderName;
if(empty($folder)){
$folder = Str::random();
}
return $this->getStoragePath($folder,'file');
}
/**
* 保存图片
* @param UploadedFile $file
* @throws ServerRunTimeException
*/
public function saveUploadImage(UploadedFile $file)
{
$newFile = $file->storeAs($this->getFileFolderPath(), $file->getClientOriginalName(), $this->getStorageDisk());
if(!$newFile){
throw new ServerRunTimeException('图片保存失败');
}
$imageStoragePath = $this->getBase64Path($newFile);
$saveImage = $this->getUploadFileInfo($file);
$saveImage['uniqueid'] = $imageStoragePath;
$saveImage['path'] = $newFile;
$result = $this->saveFileRecord($saveImage);
if($result){
$imageUrl = $this->getImageUrl($imageStoragePath);
return ['url' => $imageUrl, 'image' => $imageStoragePath];
}
return null;
}
public function getFileSize($path): string
{
return ceil(filesize(Storage::path($path))/1000)."k";
}
public function getUploadFileInfo(UploadedFile $file): array
{
$fileInfo = [];
$originalName = $file->getClientOriginalName();
$pos = strrpos($file->getClientOriginalName(), '.');
$originalName = false === $pos ? $originalName : substr($originalName, 0, $pos);
$fileInfo['name'] = $originalName;
$fileInfo['extension'] = $file->guessClientExtension();
$fileInfo['mime_type'] = $file->getClientMimeType();
$fileInfo['byte_size'] = $file->getSize();
return $fileInfo;
}
public function getBase64Path($path)
{
return app(Filepond::class)->getServerIdFromPath($path);
}
public function getImageUrl($path, $type = 'image')
{
$path = $type.'/'.$path;
return $this->getFileSystemDisk()->url($path);
}
public function getDownloadUrl($path)
{
$path = 'download/'.$path;
return $this->getFileSystemDisk()->url($path);
}
public function download($path)
{
if (! trim($path)) {
throw new NotFoundHttpException('文件无法读取,路径无效');
}
return $this->getFileSystemDisk()->download($this->loadPath($path));
}
public function downloadFile($path)
{
if (!trim($path)) {
throw new NotFoundHttpException('文件无法读取,路径无效');
}
return $this->getFileSystemDisk()->download($this->loadPath($path));
}
public function getStoragePath($path, $type = 'image'): string
{
$localPath = 'upload/'.$type.'/'.date('Ymd',time()).'/';
$storagePath = $localPath.$path;
if(!Storage::exists($storagePath)){
Storage::makeDirectory($storagePath);
}
return $storagePath;
}
public function getStorageDisk()
{
return config('filesystems.default');
}
public function getUploadImageMineType()
{
return ['image/apng','image/jpeg','image/png'];
}
public function isImageType($file)
{
$png = strpos($file['mime_type'], 'png');
$jpg = strpos($file['mime_type'], 'jpeg');
$gif = strpos($file['mime_type'], 'gif');
if(!$png && !$jpg && !$gif){
return false;
}
return true;
}
public function isPdf($fileInfo)
{
return strpos($fileInfo['mime_type'], 'pdf');
}
public function isPpt($fileInfo)
{
return strpos($fileInfo['mime_type'], 'presentationml.presentation');
}
public function isExcel($fileInfo): bool
{
return strpos($fileInfo['mime_type'], 'ms-excel') || strpos($fileInfo['mime_type'], 'spreadsheetml.sheet');
}
public function isWord($fileInfo): bool
{
return strpos($fileInfo['mime_type'], 'msword') || strpos($fileInfo['mime_type'], 'wordprocessingml.document');
}
public function loadPath($path)
{
$filePath = Crypt::decryptString($path);
if(!$filePath){
throw new NotFoundHttpException('图片或文件不存在');
}
return $filePath;
}
/**
* 读取文件内容,返回base64
* @param $path
* @return mixed
*/
public function loadFile($path)
{
return $this->getFileSystemDisk()->get($this->loadPath($path));
}
public function saveToFile($path,$content)
{
return $this->getFileSystemDisk()->put($path,$content);
}
public function getFileSystemDisk()
{
return app(FilesystemFactory::class)->disk($this->getStorageDisk());
}
public function updateFileExModelData($fileUid, $updateParams)
{
$file = $this->getRepository()->findWhere(['uniqueid' => $fileUid])->first();
if(!$file){
throw new ServerRunTimeException('上传文件记录未找到');
}
return $file->update($updateParams);
}
public function deleteFileByModelData($fileUid)
{
$file = $this->getRepository()->findWhere(['uniqueid' => $fileUid])->first();
if($file){
$this->removeFile($fileUid);
$file->delete();
}
return true;
}
public function removeFile($path): bool
{
$fileInfo = $this->getRepository()->getFileByUniqueId($path);
if(!$fileInfo){
throw new NotFoundHttpException('图片或文件不存在');
}
$fileInfoArr = current($this->collectionToArray([$fileInfo]));
$filePath = $fileInfoArr['path'];
str_replace($fileInfoArr['name'].'.'.$fileInfoArr['extension'],'',$filePath);
if($fileInfo->delete() && Storage::exists($filePath)/*$this->getRepository()->delete($fileInfo->id)*/){
Storage::delete($fileInfoArr['path']) && Storage::deleteDirectory($filePath);
}
return true;
}
public function getFileListByUniqueId($uniqueIds)
{
$fileList = $this->getRepository()->findWhereIn('uniqueid', (array)$uniqueIds);
if($fileList){
return $this->collectionToArray($fileList);
}
return null;
}
public function getFileListByModelData($modelName, $modelId)
{
$fileList = $this->getRepository()->findWhere(['model_name' => $modelName, 'model_data_id' => $modelId]);
if($fileList){
return $this->collectionToArray($fileList);
}
return null;
}
/**
* 验证上传的图片是否有效
* @param $path
* @param $validType
* @return bool
*/
public function validUploadFile($path, $validType = null): bool
{
$validResult = false;
$fileInfo = $this->getFileListByUniqueId($path);
if($fileInfo){
$fileInfo = current($fileInfo);
if(!is_null($validType)){
$validType = is_array($validType) ? $validType : [$validType];
}
foreach($validType as $type){
if(!$validResult){
switch($type){
case 'image': $this->isImageType($fileInfo) && $this->loadFile($path) ? $validResult = true : $validResult = false;break;
case 'svg': $this->isImageType($fileInfo) && $this->loadFile($path) ? $validResult = true : $validResult = false;break;
case 'pdf': $validResult = $this->isPdf($fileInfo);break;
case 'word': $validResult = $this->isWord($fileInfo);break;
case 'excel': $validResult = $this->isExcel($fileInfo);break;
case 'ppt': $validResult = $this->isPpt($fileInfo);break;
default: $validResult = strpos($fileInfo['mime_type'], $type) && $this->loadFile($path);
}
}
/*if($type == 'image'){
if($this->isImageType($fileInfo) && $this->loadFile($path)){
$validResult = true;
break;
}
}else{
if($type == 'pdf'){
$validResult = $this->isPdf($fileInfo);
break;
}else if($type == 'excel'){
$validResult = $this->isExcel($fileInfo);
break;
}else{
$validResult = strpos($fileInfo['mime_type'], $type) && $this->loadFile($path);
}
}*/
}
}
return $validResult;
}
public function saveFileRecord($fileSaveParams)
{
return $this->getRepository()->saveUplodFiles($fileSaveParams);
}
}
<?php
namespace App\Services\Traits;
use App\Exceptions\ServerRunTimeException;
use App\Repositories\Criteria\BaseCriteria;
use App\Services\AuthService as adminAuth;
use App\Services\Traits\DataEntriesService;
use App\Services\YyBao\Auth\AuthService as frontAuth;
use App\Services\YyBao\CustomersService;
use App\Services\YyBao\ImportExportTasksService;
use Illuminate\Support\Facades\DB;
trait BaseService
{
protected $repository;
protected $guard;
public function setRepository($repository)
{
$this->repository = $repository;
}
public function getRepository()
{
return $this->repository;
}
public function setGuard($guardName)
{
$this->guard = $guardName;
}
public function getGuard()
{
return $this->guard;
}
public function moneyFromat($money, $fromat = true)
{
$money = bcdiv($money, 100 ,2);
if($fromat){
return is_numeric($money) ? sprintf("%.2f", substr(sprintf("%.3f", $money), 0, -1)) : '';
}
return $money;
}
public function getList($requestParams, BaseCriteria $pushCriteria)
{
$this->getRepository()->pushCriteria($pushCriteria);
if(empty($requestParams['page_size']) || $requestParams['page_size'] == 0){
$requestParams['page_size'] = 10;
}
return $this->getRepository()->listPageByPaginate($requestParams['page_size']);
}
public function collectionToArray($collection, $model = null)
{
return $this->getRepository()->transformData(
collect($collection)->map(function($collect){
return !is_array($collect) ? $collect->toArray() : $collect;
}), $model
);
}
}
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFileManageTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('file_manage', function (Blueprint $table) {
$table->id();
$table->longText('uniqueid')->comment('uniqueid')->nullable(false);
$table->string('name')->comment('文件名称')->nullable(false);
$table->string('extension')->comment('扩展名')->nullable(false);
$table->string('type')->comment('图片类型')->nullable(false)->default('image');
$table->text('path')->nullable(false)->comment('保存路径');
$table->string('mime_type')->nullable(false)->comment('mime类型');
$table->integer('byte_size')->nullable(false)->comment('文件大小');
$table->string('model_name')->nullable()->comment('模型名称');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('file_manage');
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment