/
ImportForm.php
109 lines (95 loc) · 2.58 KB
/
ImportForm.php
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
namespace yz\admin\import;
use Goodby\CSV\Import\Standard\Interpreter;
use Goodby\CSV\Import\Standard\Lexer;
use Goodby\CSV\Import\Standard\LexerConfig;
use yii\base\InvalidCallException;
use yii\base\InvalidConfigException;
use yii\base\Model;
use yii\helpers\FileHelper;
use yii\helpers\Json;
use yii\web\UploadedFile;
/**
* Class ImportForm
*
* @property array $fieldsArray
* @property int $importCounter
*/
class ImportForm extends Model implements ImporterInterface
{
use Importer;
/**
* @var BatchImportAction
*/
public $action;
/**
* @var UploadedFile
*/
public $file;
/**
* List of extensions that are allowed
* @var array
*/
protected $allowedExtensions = ['csv', 'xls', 'xlsx'];
public function init()
{
parent::init();
$this->initImporter();
}
public function rules()
{
return [
[['file', 'encoding', 'fields', 'separator',], 'required'],
[['file'], 'file', 'extensions' => $this->allowedExtensions, 'checkExtensionByMimeType' => false],
[['skipFirstLine'], 'boolean'],
[['separator'], 'string', 'length' => 1],
[['encoding'], 'in', 'range' => array_keys(self::getEncodingValues())],
];
}
public static function getEncodingValues()
{
return [
self::ENCODING_CP1251 => \Yii::t('admin/import', 'Windows-1251'),
self::ENCODING_UTF8 => \Yii::t('admin/import', 'UTF-8'),
];
}
public function attributeLabels()
{
return [
'file' => \Yii::t('admin/import', 'Excel/CSV file'),
'encoding' => \Yii::t('admin/import', 'Encoding'),
'fields' => \Yii::t('admin/import', 'Fields'),
'skipFirstLine' => \Yii::t('admin/import', 'Skip first line'),
'separator' => \Yii::t('admin/import', 'Separator'),
];
}
public function load($data, $formName = null)
{
if (parent::load($data, $formName)) {
$this->file = UploadedFile::getInstance($this, 'file');
return true;
} else {
return false;
}
}
public function process()
{
return $this->processImport();
}
/**
* Returns path to the imported file
* @return string
*/
public function getImportedFileName()
{
return $this->file->tempName;
}
/**
* Returns MIME of the file
* @return string
*/
public function getImportedMime()
{
return FileHelper::getMimeTypeByExtension($this->file->name);
}
}