CsvExport   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 10
c 1
b 0
f 0
lcom 0
cbo 1
dl 0
loc 68
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
C make() 0 36 8
A _parseCsv() 0 9 2
1
<?php
2
namespace CsvCombine\Export;
3
4
use CsvCombine\Export\AppExport;
5
use Exception;
6
7
/**
8
 * CsvExport
9
 *
10
 * @copyright Copyright (C) 2017 hagiwara.
11
 * @license http://www.opensource.org/licenses/mit-license.php The MIT License
12
 * @author hagiwara
13
 */
14
class CsvExport extends AppExport {
15
16
    /*
17
     * make CSVの生成アクション
18
     *
19
     * @param array $list 出力のための配列(二次元配列が基本)
20
     * @param string $filePath 出力ファイルパス
21
     * @param array $options 下記パラメータを必要に応じて設定
22
     * delimiter 区切り文字の設定(デフォルトは",")
23
     * line_feed_code 改行コード(デフォルトは\r\n)
24
     * export_encoding 入力するファイルのエンコード(デフォルトはSJIS-win
25
     * array_encoding 出力する配列のエンコード(デフォルトはUTF-8
26
     */
27
    public function make($list, $filePath, $options = [])
28
    {
29
        $options = $this->getOptions($options);
30
        extract($options);
31
        $csvList = array();
32
        mb_convert_variables($exportEncoding, $arrayEncoding, $list);
33
        //$listにカンマか"がいた時の対応
34
        if (isset($list)) {
35
            if (is_array($list)) {
36
                foreach ($list as $k => $list1) {
37
                    if (is_array($list1)) {
38
                        foreach ($list1 as $m => $v) {
39
                            if (is_array($v)){
40
                                //3次元以上の配列の時はエラー
41
                                throw new Exception('array layer error');
42
                            }
43
                            $csvList[$k][$m] = $this->_parseCsv($v, $delimiter);
44
                        }
45
                    } else {
46
                        //1次元の時は1列目に値が入る。
47
                        $csvList[0][$k] = $this->_parseCsv($list1, $delimiter);
48
                    }
49
                }
50
            } else {
51
                //文字列の時は1カラムに値が入るだけ。
52
                $csvList[0][0] = $this->_parseCsv($list, $delimiter);
53
            }
54
        }
55
56
        $fp = fopen($filePath, 'w');
57
        foreach ($csvList as $fields) {
58
            fputs($fp, implode($delimiter, $fields) . $lineFeedCode);
59
        }
60
        fclose($fp);
61
        return true;
62
    }
63
64
    /*
65
     * _parseCsv
66
     * csv(など)の形式に変更
67
     *
68
     * @param string $v 変換する値
69
     * @param string $delimiter 区切り文字
70
     */
71
    private function _parseCsv($v, $delimiter)
72
    {
73
        //区切り文字・改行・ダブルクオートの時
74
        if (preg_match('/[' . $delimiter . '\\n"]/', $v)) {
75
            $v = str_replace('"', '""', $v);
76
            $v = '"' . $v . '"';
77
        }
78
        return $v;
79
    }
80
81
}
82