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

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

本文介绍了简化if语句用于确定不同文件类型的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using a lot of if statements in my function to determine which content-type response to return for each different type of files based on their extension like below :

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语句?

Is there a way I can simplify this to reduce the if statements ?

推荐答案

由于这里唯一要更改的是输出的内容类型,因此我倾向于不使用代码,而是使用简单且简单地添加到数据查询中.

Since the only thing that appears to be changing here is the content-type for the output, I'd be inclined to not use code, but a simple and trivially added-to data lookup.

<?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]);
}

现在您可以轻松地更新数据数组和几行代码.

And now you have a trivial to update data-array, and a couple of lines of code.

实际上最好查看文件内容以返回mime类型的文件.

Something that actually looked at the contents of the file to return the mime-type would be far preferable however.

这篇关于简化if语句用于确定不同文件类型的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 19:29