简化if语句用于确定不同文件类型的响应

时间:2017-09-17 16:26:48

标签: php laravel

我在我的函数中使用了很多if语句,根据扩展名确定每种不同类型文件返回的内容类型响应,如下所示:

if(($post->ext == 'doc') || ($post->ext == 'docx')) {
            return (new Response($file, 200))->header('Content-Type', 'application/msword');
        }

if(($post->ext == 'xls') || ($post->ext == 'xlsx')) {
            return (new Response($file, 200))->header('Content-Type', 'application/vnd.ms-excel');
        }

if(($post->ext == 'ppt') || ($post->ext == 'pptx')) {
            return (new Response($file, 200))->header('Content-Type', 'application/vnd.ms-powerpoint');
        }

if($post->ext == 'pdf') {
            return (new Response($file, 200))->header('Content-Type', 'application/pdf');
        }

if($post->ext == 'zip') {
            return (new Response($file, 200))->header('Content-Type', 'application/zip');
        }

if($post->ext == 'rar') {
            return (new Response($file, 200))->header('Content-Type', 'application/x-rar-compressed');
        }

有没有办法可以简化这个来减少if语句?

4 个答案:

答案 0 :(得分:0)

你可以使用开关()

   switch( $post->ext ){

      case 'doc':
      case 'docx':
         return (new Response($file, 200))->header('Content-Type', 'application/msword');
      break;

      case 'xls':
      case 'xlsx':
         return (new Response($file, 200))->header('Content-Type', 'application/vnd.ms-powerpoint');
      break;

      case 'ppt':
      case 'pptx':
         return (new Response($file, 200))->header('Content-Type', 'application/vnd.ms-powerpoint');
      break;

      case  'pdf':
        return (new Response($file, 200))->header('Content-Type', 'application/pdf');
      break;

       case  'zip':
        return (new Response($file, 200))->header('Content-Type', 'application/zip');
      break;         
       case  'rar':
        return (new Response($file, 200))->header('Content-Type', 'application/x-rar-compressed');
      break;   

   }

答案 1 :(得分:0)

如果您要手动解析,只需创建一个函数来从扩展中获取内容类型。

鉴于扩展是获取正确内容类型的可靠方法,我建议使用其他内容,例如mime_content_type,但它确实需要依赖。

Switch statements

 return (new Response($file, 200))->header('Content-Type', this->fetchContentType($file));

答案 2 :(得分:0)

由于这里似乎唯一改变的是输出的内容类型,我倾向于不使用代码,而是简单而简单地添加数据查找。

<?php
// ....
$extToType = [
    'doc' => 'application/msword',
    'docx' => 'application/msword',
    'pdf' => 'application/pdf',
    // more...  
];

if (isset($extToType[$ext])) {
   return (new Response($file, 200))
       ->header('Content-Type', $extToType[$ext]);
}

现在你可以轻松更新数据数组和几行代码。

然而,实际上查看文件内容以返回mime类型的东西将更为可取。

答案 3 :(得分:0)

您可以使用内容类型作为键将所有扩展名放在数组中。

$contentTypes  = ["msword"=>["doc","docx"],"vnd.ms-excel"=>["xls","xlsx"],"vnd.ms-powerpoint"=>["ppt","pptx"],"pdf"=>["pdf"],"zip"=>["zip"],"x-rar-compressed"=>["rar"]];

foreach ($contentTypes as $key=>$type)
{
 if(array_search($post->ext,$type){
   return (new Response($file, 200))->header("Content-Type", "application/{$key}");
  }
}