将一个功能拆分为两个

Split one function into two

为了可重用性,我打算将我的功能拆分为两个功能。基本上,该功能的概念是加载输入文件然后预览数据。

工作代码

public function uploadImportCsv()
    {
        $file = Input::file('file');
        $extension = $file->getClientOriginalExtension();
        $filename = sha1($file->getClientOriginalName().time()) . ".{$extension}";
        //upload to s3
        #doing upload to s3

        $data = [
            'title'=>[],
            'value'=>[]
            ];
    $results = Excel::load(Input::file('file'), function($reader){

            })->get();
    foreach ($results as $result) {
        foreach ($result as $key => $value) {
            if(!in_array($key, $data['title'])){
                array_push($data['title'], $key);
            }       
        }
        array_push($data['value'], $result);
    }

        return Response::json(['filename' => $filename, 'data' => $data]);
    }

拆分后

public function previewCsv()
    {
        //Preview table
        $data = [
                'title'=>[],
                'value'=>[]
                ];
        $results = Excel::load(Input::file('file'), function($reader){

                })->get();
        foreach ($results as $result) {
            foreach ($result as $key => $value) {
                if(!in_array($key, $data['title'])){
                    array_push($data['title'], $key);
                }       
            }
            array_push($data['value'], $result);
        }
        return Response::json(['data' => $data]);
    }

    public function uploadImportCsv()
    {
        $file = Input::file('file');
        $extension = $file->getClientOriginalExtension();
        $filename = sha1($file->getClientOriginalName().time()) . ".{$extension}";
        //upload to s3
        #doing upload to s3

        $data = $this->previewCsv();


        return Response::json(['filename' => $filename,'data' => $data]);
    }

我从预览功能中调用了该功能,但它不起作用。

如果您需要相同的结果,则无需 return 来自 previewCsv 函数的 json 对象。

public function previewCsv()
{
    ....
    return $data;
}