FixedLengthExportComponent::getRawData()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
namespace CsvCombine\Controller\Component;
3
use Cake\Controller\Component;
4
use Cake\Core\Configure;
5
use Cake\Event\Event;
6
use Cake\Network\Exception\MethodNotAllowedException;
7
8
9
/**
10
 * FixedLengthExportComponent  code license:
11
 *
12
 * @copyright Copyright (C) 2011 hagiwara.
13
 * @since CakePHP(tm) v 1.3
14
 * @license http://www.opensource.org/licenses/mit-license.php The MIT License
15
 */
16
class FixedLengthExportComponent extends Component {
17
18
    private $_controller;
19
    private $_defaultOptions = [
20
        'file_name' => 'export.txt',
21
        'line_feed_code' => "\r\n",
22
        'directory' => TMP,
23
        'export_encoding' => 'SJIS-win',
24
        'array_encoding' => 'UTF-8',
25
        'extra_fixed_options' => []
26
    ];
27
    private $_textData = '';
28
29
    /**
30
     * コンポーネント初期化
31
     *
32
     * @access public
33
     */
34
    public function startup(Event $event) {
35
        $this->_controller = $event->subject();
0 ignored issues
show
Deprecated Code introduced by
The method Cake\Event\Event::subject() has been deprecated with message: 3.4.0 use getSubject() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
36
    }
37
38
    /*
39
     * export 固定長の出力アクション
40
     *
41
     * @param array $list 出力のための配列(二次元配列が基本)
42
     * @param array $fixed_options 出力のための固定長の設定(各カラムのバイト数及び型)
43
     * @param array $options 下記パラメータを必要に応じて設定
44
     * file_name 出力ファイル名(デフォルトはexport.txt)
45
     * line_feed_code 改行コード(デフォルトは\r\n)
46
     * $directory 一時保存ディレクトリ(デフォルトはTMP,最終的に削除をする)
47
     * export_encoding 出力するファイルのエンコード(デフォルトはSJIS-win
48
     * array_encoding 入力する配列のエンコード(デフォルトはUTF-8
49
     * extra_fixed_options 出力のための固定長の設定(列によって桁数が異なる場合の設定)
50
     */
51
    public function export($list, $fixed_options, $options)
52
    {
53
        $options = array_merge($this->_defaultOptions,$options);
54
        extract($options);
55
56
        //layoutを切って autoRenderも外しておく
57
        $this->_controller->viewBuilder()->layout('ajax');
58
        $this->_controller->autoRender = false;
59
60
        //headerのセット
61
        $save_directory = $this->make($list, $fixed_options, $options);
62
        // 日本語ファイル名出力のため
63
        setlocale(LC_ALL, 'ja_JP.UTF-8');
64
        $basename = basename($save_directory);
65
66
        // ファイル名の変換(IE対応)
67 View Code Duplication
        if (strstr(env('HTTP_USER_AGENT'), 'MSIE') || strstr(env('HTTP_USER_AGENT'), 'Trident') || strstr(env('HTTP_USER_AGENT'), 'Edge')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
68
            $basename = mb_convert_encoding($basename, "SJIS", "UTF-8");
69
        }
70
        $this->_controller->response->file($save_directory, ['download' => true, 'name' => $basename]);
71
    }
72
73
    /*
74
     * make 固定長の作成アクション
75
     *
76
     * @param array $list 出力のための配列(二次元配列が基本)
77
     * @param array $fixed_options 出力のための固定長の設定(各カラムのバイト数)
78
     * @param array $options 下記パラメータを必要に応じて設定
79
     * file_name 出力ファイル名(デフォルトはexport.txt)
80
     * line_feed_code 改行コード(デフォルトは\r\n)
81
     * $directory 一時保存ディレクトリ(デフォルトはTMP,最終的に削除をする)
82
     * export_encoding 出力するファイルのエンコード(デフォルトはSJIS-win
83
     * array_encoding 入力する配列のエンコード(デフォルトはUTF-8
84
     * extra_fixed_options 出力のための固定長の設定(列によって桁数が異なる場合の設定)
85
     */
86
    public function make($list, $fixed_options, $options)
87
    {
88
        Configure::write('debug', 0);
89
        ini_set("memory_limit", -1);
90
        set_time_limit(0);
91
92
        $this->_textData = '';
93
        $options = array_merge($this->_defaultOptions,$options);
94
        extract($options);
95
96
        mb_convert_variables($export_encoding, $array_encoding, $list);
97
98
        // keyを振りなおしておく。
99
        $list = array_merge($list);
100
        $list_count = count($list);
101
        //$listにカンマか"がいた時の対応
102
        $return_text = '';
103
        foreach ($list as $row => $list_val) {
104
            $column_options = $fixed_options;
105 View Code Duplication
            if (array_key_exists($row + 1, $extra_fixed_options)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
106
                $column_options = $extra_fixed_options[$row + 1];
107
            } elseif (array_key_exists($row - $list_count, $extra_fixed_options)) {
108
                $column_options = $extra_fixed_options[$row - $list_count];
109
            }
110
111
            foreach ($column_options as $fixed_option_key => $fixed_info) {
112
                if (!array_key_exists($fixed_option_key, $list_val)) {
113
                    //必要なデータが存在しないエラー
114
                    throw new MethodNotAllowedException('data not exist');
115
                } else if (strlen($list_val[$fixed_option_key]) > $fixed_info['length']) {
116
                    throw new MethodNotAllowedException('length error');
117
                }
118
119
                if ($fixed_info['type'] == 'text') {
120
                    $return_text .= str_pad($list_val[$fixed_option_key], $fixed_info['length']);
121
                } elseif ($fixed_info['type'] == 'integer') {
122
                    $return_text .= sprintf('%0' . $fixed_info['length'] . 's', ($list_val[$fixed_option_key]));
123
                } else {
124
                    throw new MethodNotAllowedException('type error');
125
                }
126
            }
127
            $return_text .= $line_feed_code;
128
        }
129
130
        $this->_textData = $return_text;
131
        $save_directory = $directory . $file_name;
132
        $fp = fopen($save_directory, 'w');
133
        fwrite($fp, $return_text);
134
135
        fclose($fp);
136
137
        return $save_directory;
138
    }
139
140
    /*
141
     * getRawData ファイルに出力した生テキストデータを取得
142
     */
143
    public function getRawData()
144
    {
145
        return $this->_textData;
146
    }
147
}
148