Commit 0c8b9dfc85a639b655e7d5d3c7dd419978f25419

Authored by Mihail
1 parent f90f5f26

add error exceptions, rewrite parser to universal composer pac

backend/components/parsers/CsvParser.php deleted
1   -<?php
2   -/**
3   -
4   - */
5   -//@ todo add exceptions
6   -namespace backend\components\parsers;
7   -
8   -
9   -use Yii;
10   -use yii\base\ErrorException;
11   -use common\components\debug\CustomVarDamp;
12   -
13   -class CsvParser implements ParserInterface
14   -{
15   -
16   -
17   - /** @var bool
18   - имеет ли файл заголовок который будет установлен ключами возвращемого массива*/
19   - public $hasHeaderRow = false;
20   - /** @var array - массив с заголовком,
21   - * если не указан и установлено свойство $hasHeaderRow - будет определен автоматически */
22   - public $keys;
23   -
24   - /** @var экземляр SplFileObject читаемого файла */
25   - public $file;
26   -
27   - /** @var int - первая строка с которой начинать парсить */
28   - public $first_line = 0;
29   -
30   - /** @var int - последняя строка до которой парсить
31   - * если не указана, то парсинг происходит до конца файла*/
32   - public $last_line = 0;
33   -
34   - /** @var int - первая колонка файла с которой начнется парсинг */
35   - public $first_column = 0;
36   -
37   - /** @var string - разделитель csv */
38   - public $delimiter = ';';
39   -
40   - /** @var bool
41   - нужно ли искать автоматически первоую значисмую строку (не пустая строка)
42   - * иначе первая строка будет взята из аттрибута $first_line */
43   - public $auto_detect_first_line = false;
44   -
45   - /** @var int - количество значимых колонок, что бы определить первую значимую строку
46   - * используется при автоопределении первой строки*/
47   - public $min_column_quantity = 5;
48   -
49   -
50   - /**
51   - метод устанвливает нужные настройки объекта SplFileObject, для работы с csv
52   - */
53   - public function setup()
54   - {
55   - $this->file->setCsvControl($this->delimiter);
56   - $this->file->setFlags(\SplFileObject::READ_CSV);
57   - $this->file->setFlags(\SplFileObject::SKIP_EMPTY);
58   - if ($this->auto_detect_first_line) {
59   - $this->shiftToFirstValuableLine();
60   - }
61   - }
62   -
63   - /**
64   - * определяет первую значимую строку,
65   - * считывается файл пока в нем не встретится строка с непустыми колонками
66   - * в количестве указанном в атрибуте min_column_quantity
67   - * в результате выполнения курсор ресурса будет находится на последней незначимой строке
68   - */
69   - protected function shiftToFirstValuableLine()
70   - {
71   -
72   - $finish = false;
73   -
74   - while (!$finish) {
75   - $j = 0;
76   - $row = $this->readRow();
77   - if ($row === false) {
78   - continue;
79   - }
80   -
81   - for ($i = 1; $i <= count($row); $i++) {
82   -
83   - if ($row[$i - 1] <> '') {
84   - $j++;
85   - }
86   -
87   - if ($j >= $this->min_column_quantity) {
88   - break 2;
89   - }
90   - }
91   - }
92   - }
93   -
94   - /**
95   - * @return array - итоговый двумерный массив с результатом парсинга
96   - * метод считывает с открытого файла данные построчно
97   - */
98   - public function read()
99   - {
100   - $return = [];
101   -
102   - $current_line = 0;
103   - $this->keys = NULL;
104   -
105   - while (($row = $this->readRow()) !== FALSE) {
106   - $current_line++;
107   -
108   - if ($this->hasHeaderRow) {
109   - if ($this->keys === NULL) {
110   - $this->keys = array_values($row);
111   - } else {
112   -
113   - if (count($this->keys) !== count($row)) {
114   -//
115   - Yii::warning("Invalid columns detected on line #$current_line .");
116   - return $return;
117   - }
118   -
119   - $return[] = array_combine($this->keys, $row);
120   - }
121   - }
122   - else
123   - {
124   - $return[] = $row;
125   - }
126   - // если у нас установлен лимит, при его достижении прекращаем парсинг
127   - if (($this->last_line) && ($current_line > $this->last_line)) {
128   - break;
129   - }
130   -
131   - }
132   -
133   - $this->closeHandler();
134   - return $return;
135   - }
136   -
137   -
138   - protected function closeHandler()
139   - {
140   - $this->file = NULL;
141   - }
142   -
143   - /**
144   - * @return array - одномерный массив результата парсинга строки
145   - */
146   - protected function readRow()
147   - {
148   -
149   - $row = $this->file->fgetcsv();
150   - if (is_array($row) && $this->first_column) {
151   -
152   - $row = array_slice($row, $this->first_column);
153   -
154   - }
155   - if (is_null($row))
156   - $row = false;
157   -
158   - return $row;
159   -
160   - }
161   -
162   -
163   -}
164 0 \ No newline at end of file
backend/components/parsers/CustomCsvParser.php
... ... @@ -9,7 +9,7 @@
9 9 namespace backend\components\parsers;
10 10  
11 11  
12   -class CustomCsvParser extends CsvParser {
  12 +class CustomCsvParser extends \yii\multiparser\CsvParser {
13 13  
14 14 protected function readRow()
15 15 {
... ...
backend/components/parsers/ParserConfigurator.php deleted
1   -<?php
2   -/**
3   - * Created by PhpStorm.
4   - * User: Cibermag
5   - * Date: 04.09.2015
6   - * Time: 18:17
7   - */
8   -
9   -namespace backend\components\parsers;
10   -
11   -
12   -class ParserConfigurator {
13   - public static function getConfiguration ()
14   - {
15   - return [
16   - 'class' => 'backend\components\parsers\CustomCsvParser',
17   - // 'file' => $this->fileObject,
18   - 'auto_detect_first_line' => true,
19   - ];
20   - }
21   -
22   -}
23 0 \ No newline at end of file
backend/components/parsers/ParserHandler.php deleted
1   -<?php
2   -namespace backend\components\parsers;
3   -use common\components\debug\CustomVarDamp;
4   -
5   -use Yii;
6   -
7   -
8   -class ParserHandler {
9   -
10   -/** @var string */
11   - private $filePath;
12   -
13   - /** @var instance of SplFileObject */
14   - private $fileObject;
15   -
16   - /** @var string - extension of file $filePath */
17   - private $extension;
18   -
19   - /** @var string - extension of file $filePath */
20   - private $mode;
21   -
22   - /**
23   - * @param string first line in file for parsing
24   - */
25   - public function __construct( $filePath, $mode )
26   - {
27   - $this->filePath = $filePath;
28   - $this->mode = $mode;
29   -
30   - try {
31   - $this->fileObject = new \SplFileObject( $this->filePath , 'r' );;
32   - } catch (\ErrorException $e) {
33   - Yii::warning("Ошибка открытия файла {$this->filePath}");
34   - }
35   -
36   - //preg_match( '/\.[^\.]+$/i',$filePath, $resultArray );
37   - $this->extension = $this->fileObject->getExtension();
38   - }
39   -
40   - public function run(){
41   -
42   - $parser = Yii::createObject( ParserConfigurator::getConfiguration() );
43   - $parser->setup();
44   - return $parser->read();
45   - }
46   -}
47   -
backend/components/parsers/ParserInterface.php deleted
1   -<?php
2   -/**
3   - * Created by PhpStorm.
4   - * User: Cibermag
5   - * Date: 04.09.2015
6   - * Time: 18:25
7   - */
8   -
9   -namespace backend\components\parsers;
10   -
11   -
12   -interface ParserInterface {
13   - public function setup();
14   -
15   - public function read();
16   -
17   -
18   -}
19 0 \ No newline at end of file
backend/models/UploadFileParsingForm.php
... ... @@ -3,7 +3,7 @@ namespace backend\models;
3 3  
4 4 use yii\base\Model;
5 5 use yii\web\UploadedFile;
6   -use backend\components\parsers\ParserHandler;
  6 +use yii\multiparser\ParserHandler;
7 7 use Yii;
8 8 use common\components\debug\CustomVarDamp;
9 9  
... ... @@ -51,7 +51,8 @@ class UploadFileParsingForm extends Model
51 51 }
52 52  
53 53 public function readFile($filePath){
54   - $parser = new ParserHandler( $filePath, $this );
  54 +
  55 + $parser = new ParserHandler( $filePath );
55 56 $data = $parser->run();
56 57  
57 58 if( !is_array($data) ){
... ...
common/components/debug/CustomVarDamp.php renamed to common/components/CustomVarDamp.php
... ... @@ -5,7 +5,7 @@
5 5 * Date: 27.08.2015
6 6 * Time: 16:47
7 7 */
8   -namespace common\components\debug;
  8 +namespace common\components;
9 9 use yii\helpers\BaseVarDumper;
10 10  
11 11 class CustomVarDamp extends BaseVarDumper {
... ...
composer.json
... ... @@ -17,7 +17,8 @@
17 17 "php": ">=5.4.0",
18 18 "yiisoft/yii2": ">=2.0.6",
19 19 "yiisoft/yii2-bootstrap": "*",
20   - "yiisoft/yii2-swiftmailer": "*"
  20 + "yiisoft/yii2-swiftmailer": "*",
  21 + "yiisoft/multiparser": "*"
21 22 },
22 23 "require-dev": {
23 24 "yiisoft/yii2-codeception": "*",
... ...