UploadFileParsingForm.php
1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php
namespace backend\models;
use yii\base\ErrorException;
use yii\base\Model;
use yii\web\UploadedFile;
use Yii;
use common\components\CustomVarDamp;
/**
* UploadForm is the model behind the upload form.
*/
class UploadFileParsingForm extends Model
{
/**
* @var UploadedFile file attribute
*/
// chosen file
public $file;
// file path after save
public $file_path;
// 0 - custom file (user should choose in $file field)
// 1 - csv template file from data/template.csv
// 2 - xml template file from data/template.xml
// 3 - xlsx template file from data/template.xlsx
// 4 - xls template file from data/template.xls
// 5 - txt template file from data/template.txt
public $file_type = 0;
public function rules()
{
$client_func = <<< JS
function(attribute, value) {
return $('input[name=UploadFileParsingForm[file_type]]').val() == '0';
}
JS;
return [
['file_type', 'in', 'range' => range( 0, 5 ) ],
['file', 'required', 'when' => function(){
return !$this->file_type;
} , 'whenClient' => $client_func],
[['file'], 'file', 'extensions' => ['csv', 'xlsx', 'xml', 'xls', 'txt'], 'checkExtensionByMimeType' => false ],
['file_path', 'safe'],
];
}
public function attributeLabels()
{
return [
'file' => Yii::t('app', 'Custom file'),
];
}
public function readFile( $options = [] ){
$data = Yii::$app->multiparser->parse( $this->file_path, $options );
if( !is_array( $data ) || count($data) == 0 ){
throw new ErrorException("Parser return empty array. Check file and configuration settings (config.php)");
}
if( !$this->file_path && file_exists( $this->file_path ) )
unlink( $this->file_path );
return $data;
}
}